add VoIP
[mirror/userdir-ldap.git] / ud-mailgate
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 #   Prior copyright probably rmurray, troup, joey, jgg -- weasel 2008
5 #   Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
6
7 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os;
8 import pwd
9 from userdir_gpg import *;
10 from userdir_ldap import *;
11
12 # Error codes from /usr/include/sysexits.h
13 ReplyTo = ConfModule.replyto;
14 PingFrom = ConfModule.pingfrom;
15 ChPassFrom = ConfModule.chpassfrom;
16 ChangeFrom = ConfModule.changefrom;
17 ReplayCacheFile = ConfModule.replaycachefile;
18
19 EX_TEMPFAIL = 75;
20 EX_PERMFAIL = 65;      # EX_DATAERR
21 Error = 'Message Error';
22 SeenKey = 0;
23 SeenDNS = 0;
24 mailRBL = {}
25 mailRHSBL = {}
26 mailWhitelist = {}
27 SeenList = {}
28 DNS = {}
29
30 ArbChanges = {"c": "..",
31               "l": ".*",
32               "facsimileTelephoneNumber": ".*",
33               "telephoneNumber": ".*",
34               "postalAddress": ".*",
35               "postalCode": ".*",
36               "loginShell": ".*",
37               "emailForward": "^([^<>@]+@.+)?$",
38               "jabberJID": "^([^<>@]+@.+)?$",
39               "ircNick": ".*",
40               "icqUin": "^[0-9]*$",
41               "onVacation": ".*",
42               "labeledURI": ".*",
43               "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
44               "mailDisableMessage": ".*",
45               "mailGreylisting": "^(TRUE|FALSE)$",
46               "mailCallout": "^(TRUE|FALSE)$",
47               "VoIP": ".*",
48 };
49
50 DelItems = {"c": None,
51             "l": None,
52             "facsimileTelephoneNumber": None,
53             "telephoneNumber": None,
54             "postalAddress": None,
55             "postalCode": None,
56             "emailForward": None,
57             "ircNick": None,
58             "onVacation": None,
59             "labeledURI": None,
60             "latitude": None,
61             "longitude": None,
62             "icqUin": None,
63             "jabberJID": None,
64             "jpegPhoto": None,
65             "dnsZoneEntry": None,
66             "sshRSAAuthKey": None,
67             "sshDSAAuthKey": None,
68             "birthDate" : None,
69             "mailGreylisting": None,
70             "mailCallout": None,
71             "mailRBL": None,
72             "mailRHSBL": None,
73             "mailWhitelist": None,
74             "mailDisableMessage": None,
75             "VoIP": None,
76             };
77
78 # Decode a GPS location from some common forms
79 def LocDecode(Str,Dir):
80    # Check for Decimal degrees, DGM, or DGMS
81    if re.match("^[+-]?[\d.]+$",Str) != None:
82       return Str;
83
84    Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
85    
86    # Check for DDDxMM.MMMM where x = [nsew]
87    Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
88    if Match != None:
89       G = Match.groups();
90       Deg = G[0]; Min = G[2]; Dr = G[1];
91
92    # Check for DD.DD x 
93    Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
94    if Match != None:
95       G = Match.groups();
96       Deg = G[0]; Dr = G[1];
97
98    # Check for DD:MM.MM x 
99    Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
100    if Match != None:
101       G = Match.groups();
102       Deg = G[0]; Min = G[1]; Dr = G[2];
103
104    # Check for DD:MM:SS.SS x
105    Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
106    if Match != None:
107       G = Match.groups();
108       Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
109       
110    # Some simple checks
111    if float(Deg) > 180:
112       raise "Failed","Bad degrees";
113    if Min != None and float(Min) > 60:
114       raise "Failed","Bad minutes";
115    if Sec != None and float(Sec) > 60:
116       raise "Failed","Bad seconds";
117       
118    # Pad on an extra leading 0 to disambiguate small numbers
119    if len(Deg) <= 1 or Deg[1] == '.':
120       Deg = '0' + Deg;
121    if Min != None and (len(Min) <= 1 or Min[1] == '.'):
122       Min = '0' + Min;
123    if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
124       Sec = '0' + Sec;
125    
126    # Construct a DGM/DGMS type value from the components.
127    Res = "+"
128    if Dr == Dir[1]:
129       Res = "-";
130    Res = Res + Deg;
131    if Min != None:
132       Res = Res + Min;
133    if Sec != None:
134       Res = Res + Sec;
135    return Res;
136               
137 # Handle changing a set of arbitary fields
138 #  <field>: value
139 def DoArbChange(Str,Attrs):
140    Match = re.match("^([^ :]+): (.*)$",Str);
141    if Match == None:
142       return None;
143    G = Match.groups();
144
145    attrName = G[0].lower();
146    for i in ArbChanges.keys():
147       if i.lower() == attrName:
148          attrName = i;
149          break;
150    if ArbChanges.has_key(attrName) == 0:
151       return None;
152
153    if re.match(ArbChanges[attrName],G[1]) == None:
154       raise Error, "Item does not match the required format"+ArbChanges[attrName];
155
156 #   if attrName == 'birthDate':
157 #      (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
158 #    $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
159 #    if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
160 #      if ($bd_mo == 2) {
161 #        if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
162 #          $bd_ok = 1;
163 #        } elsif ($bd_day <= 28) {
164 #          $bd_ok = 1;
165 #        }
166 #      } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
167 #       if ($bd_day <= 30) {
168 #         $bd_ok = 1;
169 #       }
170 #      } else {
171 #       if ($bd_day <= 31) {
172 #         $bd_ok = 1;
173 #       }
174 #      }
175 #    }
176 #  } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
177 #    $bd_ok = 1;
178 #  }
179    Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
180    return "Changed entry %s to %s"%(attrName,G[1]);
181
182 # Handle changing a set of arbitary fields
183 #  <field>: value
184 def DoDel(Str,Attrs):
185    Match = re.match("^del (.*)$",Str);
186    if Match == None:
187       return None;
188    G = Match.groups();
189
190    attrName = G[0].lower();
191    for i in DelItems.keys():
192       if i.lower() == attrName:
193          attrName = i;
194          break;
195    if DelItems.has_key(attrName) == 0:
196       return "Cannot erase entry %s"%(attrName);
197
198    Attrs.append((ldap.MOD_DELETE,attrName,None));
199    return "Removed entry %s"%(attrName);
200
201 # Handle a position change message, the line format is:
202 #  Lat: -12412.23 Long: +12341.2342
203 def DoPosition(Str,Attrs):
204    Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
205    if Match == None:
206       return None;
207
208    G = Match.groups();
209    try:
210       sLat = LocDecode(G[0],"ns");
211       sLong = LocDecode(G[1],"ew");
212       Lat = DecDegree(sLat,1);
213       Long = DecDegree(sLong,1);
214    except:
215       raise Error, "Positions were found, but they are not correctly formed";
216
217    Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
218    Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
219    return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
220
221 # Handle an SSH authentication key, the line format is:
222 #  [options] 1024 35 13188913666680[..] [comment]
223 def DoSSH(Str,Attrs):
224    Match = SSH2AuthSplit.match(Str);
225    if Match == None:
226       Match = re.compile('^1024 (\d+) ').match(Str)
227       if Match is not None:
228          return "SSH1 keys not supported anymore"
229       return None;
230    
231    global SeenKey;
232    if SeenKey:
233      Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
234      return "SSH Key added "+FormatSSHAuth(Str);
235       
236    Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
237    SeenKey = 1;
238    return "SSH Keys replaced with "+FormatSSHAuth(Str);
239
240 # Handle changing a dns entry
241 #  host IN A     12.12.12.12
242 #  host IN AAAA  1234::5678
243 #  host IN CNAME foo.bar.    <- Trailing dot is required
244 #  host IN MX    foo.bar.    <- Trailing dot is required
245 def DoDNS(Str,Attrs,DnRecord):
246    cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
247    arecord     = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
248    mxrecord    = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
249    #aaaarecord  = re.match('^[-\w]+\s+IN\s+AAAA\s+((?:[0-9a-f]{1,4})(?::[0-9a-f]{1,4})*(?::(?:(?::[0-9a-f]{1,4})*|:))?)$',Str,re.IGNORECASE)
250    aaaarecord  = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
251
252    if cnamerecord == None and\
253       arecord == None and\
254       mxrecord == None and\
255       aaaarecord == None:
256      return None;
257
258    # Check if the name is already taken
259    G = re.match('^([-\w+]+)\s',Str)
260    if G == None:
261      raise Error, "Hostname not found although we already passed record syntax checks"
262    hostname = G.group(1)
263
264    # Check for collisions
265    global l;
266    # [JT 20070409 - search for both tab and space suffixed hostnames
267    #  since we accept either.  It'd probably be better to parse the
268    #  incoming string in order to construct what we feed LDAP rather
269    #  than just passing it through as is.]
270    filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
271    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
272    for x in Rec:
273       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
274          return "DNS entry is already owned by " + GetAttr(x,"uid")
275
276    global SeenDNS;
277    global DNS;
278
279    if cnamerecord:
280      if DNS.has_key(hostname):
281        return "CNAME and other RR types not allowed: "+Str
282      else:
283        DNS[hostname] = 2
284    else:
285      if DNS.has_key(hostname) and DNS[hostname] == 2:
286        return "CNAME and other RR types not allowed: "+Str
287      else:
288        DNS[hostname] = 1
289
290    if cnamerecord != None:
291      sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
292    elif arecord != None:
293      ipaddress = arecord.group(1)
294      for quad in ipaddress.split('.'):
295        if not (int(quad) >=0 and int(quad) <= 255):
296          return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
297      sanitized = "%s IN A %s"% (hostname, ipaddress)
298    elif mxrecord != None:
299      priority = mxrecord.group(1)
300      mx = mxrecord.group(2)
301      sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
302    elif aaaarecord != None:
303      ipv6address = aaaarecord.group(1)
304      parts = ipv6address.split(':')
305      if len(parts) > 8:
306        return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
307      if len(parts) <= 2:
308        return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
309      if parts[0] == "":
310        parts.pop(0)
311      if parts[-1] == "":
312        parts.pop(-1)
313      seenEmptypart = False
314      for p in parts:
315        if len(p) > 4:
316          return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
317        if p == "":
318          if seenEmptypart:
319            return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
320          seenEmptypart = True
321      sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
322    else:
323      raise Error, "None of the types I recognize was it.  I shouldn't be here.  confused."
324
325    if SeenDNS:
326      Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
327      return "DNS Entry added "+sanitized;
328
329    Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
330    SeenDNS = 1;
331    return "DNS Entry replaced with "+sanitized;
332
333 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
334 def DoRBL(Str,Attrs):
335    Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
336    if Match == None:
337       return None
338    
339    if Match.group(1) == "rbl":
340       Key = "mailRBL"
341    if Match.group(1) == "rhsbl":
342       Key = "mailRHSBL"
343    if Match.group(1) == "whitelist":
344       Key = "mailWhitelist"
345    Host = Match.group(2)
346
347    global SeenList
348    if SeenList.has_key(Key):
349      Attrs.append((ldap.MOD_ADD,Key,Host))
350      return "%s added %s" % (Key,Host)
351       
352    Attrs.append((ldap.MOD_REPLACE,Key,Host))
353    SeenList[Key] = 1;
354    return "%s replaced with %s" % (Key,Host)
355
356 # Handle an [almost] arbitary change
357 def HandleChange(Reply,DnRecord,Key):
358    global PlainText;
359    Lines = re.split("\n *\r?",PlainText);
360
361    Result = "";
362    Attrs = [];
363    Show = 0;
364    for Line in Lines: 
365       Line = Line.strip()
366       if Line == "":
367          continue;
368
369       # Try to process a command line
370       Result = Result + "> "+Line+"\n";
371       try:
372          if Line == "show":
373            Show = 1;
374            Res = "OK";
375          else:
376            Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
377                  DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
378                  DoDel(Line,Attrs) or DoRBL(Line,Attrs);
379       except:
380          Res = None;
381          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
382          
383       # Fail, if someone tries to send someone elses signed email to the
384       # daemon then we want to abort ASAP.
385       if Res == None:
386          Result = Result + "Command is not understood. Halted\n";
387          break;
388       Result = Result + Res + "\n";
389
390    # Connect to the ldap server
391    l = ldap.open(LDAPServer);
392    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
393    AccessPass = F.readline().strip().split(" ")
394    F.close();
395
396    # Modify the record
397    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
398    oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
399    if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1) 
400        or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
401       raise Error, "This account is locked";
402    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
403    l.modify_s(Dn,Attrs);
404
405    Attribs = "";
406    if Show == 1:
407       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
408       if len(Attrs) == 0:
409          raise Error, "User not found"
410       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
411       
412    Subst = {};
413    Subst["__FROM__"] = ChangeFrom;
414    Subst["__EMAIL__"] = EmailAddress(DnRecord);
415    Subst["__ADMIN__"] = ReplyTo;
416    Subst["__RESULT__"] = Result;
417    Subst["__ATTR__"] = Attribs;
418
419    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
420    
421 # Handle ping handles an email sent to the 'ping' address (ie this program
422 # called with a ping argument) It replies with a dump of the public records.
423 def HandlePing(Reply,DnRecord,Key):
424    Subst = {};
425    Subst["__FROM__"] = PingFrom;
426    Subst["__EMAIL__"] = EmailAddress(DnRecord);
427    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
428    Subst["__ADMIN__"] = ReplyTo;
429
430    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
431
432 # Handle a change password email sent to the change password address
433 # (this program called with the chpass argument)
434 def HandleChPass(Reply,DnRecord,Key):
435    # Generate a random password
436    Password = GenPass();
437    Pass = HashPass(Password);
438       
439    # Use GPG to encrypt it      
440    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
441                         "0x"+Key[1],Key[4]);
442    Password = None;
443
444    if Message == None:
445       raise Error, "Unable to generate the encrypted reply, gpg failed.";
446
447    if (Key[4] == 1):
448       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
449    else:
450       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
451              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
452    
453    Subst = {};
454    Subst["__FROM__"] = ChPassFrom;
455    Subst["__EMAIL__"] = EmailAddress(DnRecord);
456    Subst["__CRYPTTYPE__"] = Type;
457    Subst["__PASSWORD__"] = Message;
458    Subst["__ADMIN__"] = ReplyTo;
459    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
460    
461    # Connect to the ldap server
462    l = ldap.open(LDAPServer);
463    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
464    AccessPass = F.readline().strip().split(" ")
465    F.close();
466    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
467
468    # Check for a locked account
469    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
470    if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
471              or GetAttr(Attrs[0],"userPassword").startswith("!"):
472       raise Error, "This account is locked";
473
474    # Modify the password
475    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
476    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
477    l.modify_s(Dn,Rec);
478
479    return Reply;
480       
481 # Start of main program
482
483 # Drop messages from a mailer daemon.
484 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
485    sys.exit(0);
486
487 ErrMsg = "Indeterminate Error";
488 ErrType = EX_TEMPFAIL;
489 try:
490    # Startup the replay cache
491    ErrType = EX_TEMPFAIL;
492    ErrMsg = "Failed to initialize the replay cache:";
493    RC = ReplayCache(ReplayCacheFile);
494    RC.Clean();
495
496    # Get the email 
497    ErrType = EX_PERMFAIL;
498    ErrMsg = "Failed to understand the email or find a signature:";
499    Email = mimetools.Message(sys.stdin,0);
500    Msg = GetClearSig(Email);
501
502    ErrMsg = "Message is not PGP signed:"
503    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
504       Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
505       raise Error, "No PGP signature";
506    
507    # Check the signature
508    ErrMsg = "Unable to check the signature or the signature was invalid:";
509    Res = GPGCheckSig(Msg[0]);
510
511    if Res[0] != None:
512       raise Error, Res[0];
513       
514    if Res[3] == None:
515       raise Error, "Null signature text";
516
517    # Extract the plain message text in the event of mime encoding
518    global PlainText;
519    ErrMsg = "Problem stripping MIME headers from the decoded message"
520    if Msg[1] == 1:
521       try:
522          Index = Res[3].index("\n\n") + 2;
523       except ValueError:
524          Index = Res[3].index("\n\r\n") + 3;
525       PlainText = Res[3][Index:];
526    else:
527       PlainText = Res[3];   
528
529    # Check the signature against the replay cache
530    ErrMsg = "The replay cache rejected your message. Check your clock!";
531    Rply = RC.Check(Res[1]);
532    if Rply != None:
533       raise Error, Rply;
534
535    # Connect to the ldap server
536    ErrType = EX_TEMPFAIL;
537    ErrMsg = "An error occured while performing the LDAP lookup";
538    global l;
539    l = ldap.open(LDAPServer);
540    l.simple_bind_s("","");
541
542    # Search for the matching key fingerprint
543    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
544
545    ErrType = EX_PERMFAIL;
546    if len(Attrs) == 0:
547       raise Error, "Key not found"
548    if len(Attrs) != 1:
549       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
550
551    RC.Add(Res[1]);
552
553    # Determine the sender address
554    ErrMsg = "A problem occured while trying to formulate the reply";
555    Sender = Email.getheader("Reply-To");
556    if Sender == None:
557       Sender = Email.getheader("From");
558    if Sender == None:
559       raise Error, "Unable to determine the sender's address";
560
561    # Formulate a reply
562    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
563    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
564
565    # Dispatch
566    if sys.argv[1] == "ping":
567       Reply = HandlePing(Reply,Attrs[0],Res[2]);
568    elif sys.argv[1] == "chpass":
569       if PlainText.strip().find("Please change my Debian password") != 0:
570          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
571       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
572    elif sys.argv[1] == "change":
573       Reply = HandleChange(Reply,Attrs[0],Res[2]);
574    else:
575       print sys.argv;
576       raise Error, "Incorrect Invokation";
577
578    # Send the message through sendmail      
579    ErrMsg = "A problem occured while trying to send the reply";
580    Child = os.popen("/usr/sbin/sendmail -t","w");
581 #   Child = os.popen("cat","w");
582    Child.write(Reply);
583    if Child.close() != None:
584       raise Error, "Sendmail gave a non-zero return code";
585
586 except:
587    # Error Reply Header
588    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
589    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
590
591    # Error Body
592    Subst = {};
593    Subst["__ERROR__"] = ErrMsg;
594    Subst["__ADMIN__"] = ReplyTo;
595
596    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
597    List = traceback.extract_tb(sys.exc_traceback);
598    if len(List) > 1:
599       Trace = Trace + "Python Stack Trace:\n";
600       for x in List:
601          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
602
603    Subst["__TRACE__"] = Trace;
604
605    # Try to send the bounce
606    try:
607       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
608
609       Child = os.popen("/usr/sbin/sendmail -t","w");
610       Child.write(ErrReplyHead);
611       Child.write(ErrReply);
612       if Child.close() != None:
613          raise Error, "Sendmail gave a non-zero return code";
614    except:
615       sys.exit(EX_TEMPFAIL);
616       
617    if ErrType != EX_PERMFAIL:
618       sys.exit(ErrType);
619    sys.exit(0);
620