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