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