Index: head/contrib/sendmail/CACerts =================================================================== --- head/contrib/sendmail/CACerts (revision 249728) +++ head/contrib/sendmail/CACerts (revision 249729) @@ -1,102 +1,102 @@ -# $Id: CACerts,v 8.5 2011/05/06 23:05:10 ca Exp $ +# $Id: CACerts,v 8.6 2013/01/18 15:14:17 ca Exp $ # This file contains some CA certificates that are used to sign the # certificates of mail servers of members of the sendmail consortium # who may reply to questions etc sent to sendmail.org. # It is useful to allow connections from those MTAs that can present # a certificate signed by one of these CA certificates. # Certificate: Data: Version: 3 (0x2) Serial Number: - c2:3c:61:67:3b:0a:cc:5e - Signature Algorithm: md5WithRSAEncryption - Issuer: C=US, ST=California, L=Berkeley, O=Endmail Org, OU=MTA, CN=Claus Assmann CA RSA 2009/emailAddress=ca+ca-rsa2009@esmtp.org + f1:41:b3:3d:ba:bd:33:49 + Signature Algorithm: sha1WithRSAEncryption + Issuer: C=US, ST=California, L=Berkeley, O=Endmail Org, OU=MTA, CN=Claus Assmann CA RSA 2012/emailAddress=ca+ca-rsa2012@esmtp.org Validity - Not Before: May 14 04:42:18 2009 GMT - Not After : May 13 04:42:18 2012 GMT - Subject: C=US, ST=California, L=Berkeley, O=Endmail Org, OU=MTA, CN=Claus Assmann CA RSA 2009/emailAddress=ca+ca-rsa2009@esmtp.org + Not Before: Mar 10 02:47:46 2012 GMT + Not After : Mar 10 02:47:46 2015 GMT + Subject: C=US, ST=California, L=Berkeley, O=Endmail Org, OU=MTA, CN=Claus Assmann CA RSA 2012/emailAddress=ca+ca-rsa2012@esmtp.org Subject Public Key Info: Public Key Algorithm: rsaEncryption - RSA Public Key: (2048 bit) - Modulus (2048 bit): - 00:d5:f8:d3:48:38:75:df:2e:6b:8b:c4:8d:1d:41: - 5e:ad:4b:96:3d:48:c2:dc:e5:ff:61:98:95:32:03: - e9:b6:71:5a:68:31:bc:e1:5c:aa:0e:70:a7:bc:51: - b7:13:6a:78:54:ae:a6:d0:44:49:1b:5e:37:5b:59: - 20:01:47:a7:ec:41:4c:11:79:8c:25:c1:1b:c0:ed: - 85:b2:de:0f:10:9f:e7:b2:a3:c4:f1:fc:85:51:aa: - d6:68:49:51:3e:04:e1:eb:e9:cd:87:1b:d0:9d:97: - 7b:4c:e1:1e:b1:6a:be:01:0a:a9:97:9a:50:89:e3: - 66:06:4c:07:cb:7e:99:70:13:e8:b4:9c:e7:e6:52: - 38:c0:64:90:42:d0:f5:cf:22:46:22:60:e9:34:70: - 1d:e3:d1:13:33:3a:31:ba:13:06:a8:c2:34:90:47: - c5:a1:bd:2d:7d:98:21:70:de:22:d0:13:11:e5:08: - dd:a0:77:0b:df:34:a7:07:55:de:5a:71:f6:6c:9e: - ec:f7:45:75:1f:22:a9:84:06:c6:4f:84:3d:4e:05: - d7:e4:e5:98:41:61:7b:8e:c9:3b:a6:ed:31:80:7d: - fd:fa:f0:dc:b7:07:82:b8:ec:27:20:39:5f:78:95: - f1:0d:93:8d:f9:4d:21:08:fd:72:89:01:ff:2c:a0: - 71:9d + Public-Key: (2048 bit) + Modulus: + 00:a2:80:fc:c6:ce:7f:60:38:65:f4:38:f9:7a:d9: + 87:fd:47:eb:3f:2c:4a:c9:38:77:6a:77:94:92:7f: + 83:3d:99:57:2c:5f:37:bb:ba:12:10:17:56:fa:eb: + 43:a6:4b:4c:1e:30:32:07:94:2f:5a:d8:65:49:29: + fa:24:d1:f0:0b:45:2d:e5:d5:cb:7d:60:dc:a6:ce: + a4:47:35:30:ee:5e:8d:c2:30:e7:a7:63:32:b0:59: + 80:cc:8c:99:64:77:8f:50:8e:88:51:47:36:ea:9a: + f3:b4:c0:8c:a6:ab:c6:42:57:88:b9:5f:9f:61:15: + bb:79:65:93:ca:a9:fd:17:eb:87:26:8b:eb:b7:2b: + 7e:33:05:2b:ba:c0:46:f7:08:fd:da:c1:50:9b:3d: + 26:83:5c:53:97:89:2c:cc:5f:f2:7b:a8:b7:3d:fb: + f2:b4:89:0d:43:ef:18:5c:21:75:71:cc:f0:c2:a3: + 84:69:c0:a7:f3:9b:de:c1:c7:5a:5c:7e:68:da:49: + 71:af:58:a8:51:9f:bd:f9:3d:bb:a5:92:fa:7b:1d: + 52:f5:fe:90:59:95:27:65:a4:af:97:9a:4f:01:39: + 59:7d:08:6f:a1:8f:42:47:49:bf:12:52:53:39:74: + 8d:62:3b:bd:4c:4f:05:0f:c4:b9:3e:da:a8:0e:96: + 05:2d Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: - A7:61:FA:31:AF:A8:E2:5E:93:B6:84:9E:74:08:A2:76:50:87:69:7C + 08:38:E3:88:92:53:6E:F1:56:69:27:44:B5:4C:A0:18:CA:06:97:EB X509v3 Authority Key Identifier: - keyid:A7:61:FA:31:AF:A8:E2:5E:93:B6:84:9E:74:08:A2:76:50:87:69:7C - DirName:/C=US/ST=California/L=Berkeley/O=Endmail Org/OU=MTA/CN=Claus Assmann CA RSA 2009/emailAddress=ca+ca-rsa2009@esmtp.org - serial:C2:3C:61:67:3B:0A:CC:5E + keyid:08:38:E3:88:92:53:6E:F1:56:69:27:44:B5:4C:A0:18:CA:06:97:EB + DirName:/C=US/ST=California/L=Berkeley/O=Endmail Org/OU=MTA/CN=Claus Assmann CA RSA 2012/emailAddress=ca+ca-rsa2012@esmtp.org + serial:F1:41:B3:3D:BA:BD:33:49 X509v3 Basic Constraints: - CA:TRUE + CA:TRUE X509v3 Subject Alternative Name: - email:ca+ca-rsa2009@esmtp.org + email:ca+ca-rsa2012@esmtp.org X509v3 Issuer Alternative Name: - email:ca+ca-rsa2009@esmtp.org - Signature Algorithm: md5WithRSAEncryption - b3:38:e0:da:a8:07:d8:cc:b8:4d:8c:20:a6:06:2c:f8:27:db: - 8e:28:0f:39:bd:d9:24:c7:9f:e0:4d:d6:b6:63:42:36:0f:d8: - 70:41:e7:9e:a2:24:64:05:ea:85:97:ac:f2:cc:c2:a6:71:bb: - 30:21:c1:c7:c4:54:34:1d:30:09:f0:9b:74:27:93:59:12:4c: - 53:0b:8c:3e:d0:39:ed:4a:d0:d9:66:24:d8:e7:e5:9c:a8:6d: - 5f:56:5d:9a:91:fe:1b:7d:b9:7c:79:9e:1c:b9:71:74:14:f8: - 0c:30:50:f9:b1:22:56:a8:4d:6f:4b:9b:e5:8a:81:33:1b:77: - 75:f6:d8:ce:d4:90:34:86:34:d1:86:75:a9:e1:23:e6:af:c1: - 8e:28:97:47:20:4d:1b:57:09:39:f4:56:01:d2:87:43:3e:29: - f6:c4:5b:7d:8f:9e:bd:ad:36:79:cf:09:70:43:30:21:98:23: - 31:c8:0d:39:ee:77:e1:4a:44:1a:5c:79:2f:6c:ec:8a:3c:db: - 99:a0:11:bc:1a:46:24:51:e7:75:d6:9a:db:ad:dd:55:d4:dd: - ca:81:a0:10:77:96:91:9c:76:30:38:18:f0:82:43:b3:7c:41: - 64:4c:4e:da:66:22:67:cf:b7:d7:10:ba:ed:f4:6d:43:59:00: - d0:82:1e:07 + email:ca+ca-rsa2012@esmtp.org + Signature Algorithm: sha1WithRSAEncryption + 9a:8f:4d:23:5b:30:80:e1:94:e4:66:9c:3a:17:8b:79:49:5b: + ec:5d:e5:a1:22:2d:71:37:a1:51:e7:1d:b1:0d:a9:9b:aa:a9: + 0d:c7:cd:d6:24:f9:e0:f0:57:be:4f:74:0c:4b:7a:42:4c:70: + 19:2e:8e:eb:cb:1b:00:26:27:eb:1c:42:33:d5:ec:32:b4:6c: + 7d:a3:04:a1:5c:00:49:c9:0d:4c:4d:28:37:06:22:77:ec:40: + 15:25:3a:23:84:ae:1f:da:90:dd:c9:dc:27:ee:7c:ec:e5:df: + b8:ba:1e:3f:ee:c2:91:a2:3f:22:92:1e:f3:06:7e:aa:e9:c3: + 11:2d:3d:2f:85:f7:fc:d7:e2:f8:6d:70:a6:40:62:69:e7:52: + ed:1b:19:38:72:86:08:a1:3d:47:c8:68:82:41:db:db:2a:52: + 25:d7:49:aa:9e:c5:83:22:7d:2f:0b:df:8c:90:2d:b5:aa:33: + c7:9b:e8:39:8f:bb:79:5b:13:2d:4e:a9:69:59:c7:09:26:e2: + b5:53:80:86:72:bb:7c:be:e9:46:5b:d8:b2:78:42:d6:5d:c3: + bb:3a:3b:5f:0f:e8:c3:60:fb:88:9f:3a:2b:9f:d3:7d:9f:c7: + 32:aa:4d:34:a7:66:a1:25:16:95:a6:69:e7:86:a3:5c:b9:b9: + df:58:05:e3 -----BEGIN CERTIFICATE----- -MIIFJzCCBA+gAwIBAgIJAMI8YWc7CsxeMA0GCSqGSIb3DQEBBAUAMIGlMQswCQYD +MIIFJzCCBA+gAwIBAgIJAPFBsz26vTNJMA0GCSqGSIb3DQEBBQUAMIGlMQswCQYD VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTERMA8GA1UEBxMIQmVya2VsZXkx FDASBgNVBAoTC0VuZG1haWwgT3JnMQwwCgYDVQQLEwNNVEExIjAgBgNVBAMTGUNs -YXVzIEFzc21hbm4gQ0EgUlNBIDIwMDkxJjAkBgkqhkiG9w0BCQEWF2NhK2NhLXJz -YTIwMDlAZXNtdHAub3JnMB4XDTA5MDUxNDA0NDIxOFoXDTEyMDUxMzA0NDIxOFow +YXVzIEFzc21hbm4gQ0EgUlNBIDIwMTIxJjAkBgkqhkiG9w0BCQEWF2NhK2NhLXJz +YTIwMTJAZXNtdHAub3JnMB4XDTEyMDMxMDAyNDc0NloXDTE1MDMxMDAyNDc0Nlow gaUxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMREwDwYDVQQHEwhC ZXJrZWxleTEUMBIGA1UEChMLRW5kbWFpbCBPcmcxDDAKBgNVBAsTA01UQTEiMCAG -A1UEAxMZQ2xhdXMgQXNzbWFubiBDQSBSU0EgMjAwOTEmMCQGCSqGSIb3DQEJARYX -Y2ErY2EtcnNhMjAwOUBlc210cC5vcmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw -ggEKAoIBAQDV+NNIOHXfLmuLxI0dQV6tS5Y9SMLc5f9hmJUyA+m2cVpoMbzhXKoO -cKe8UbcTanhUrqbQREkbXjdbWSABR6fsQUwReYwlwRvA7YWy3g8Qn+eyo8Tx/IVR -qtZoSVE+BOHr6c2HG9Cdl3tM4R6xar4BCqmXmlCJ42YGTAfLfplwE+i0nOfmUjjA -ZJBC0PXPIkYiYOk0cB3j0RMzOjG6EwaowjSQR8WhvS19mCFw3iLQExHlCN2gdwvf -NKcHVd5acfZsnuz3RXUfIqmEBsZPhD1OBdfk5ZhBYXuOyTum7TGAff368Ny3B4K4 -7CcgOV94lfENk435TSEI/XKJAf8soHGdAgMBAAGjggFWMIIBUjAdBgNVHQ4EFgQU -p2H6Ma+o4l6TtoSedAiidlCHaXwwgdoGA1UdIwSB0jCBz4AUp2H6Ma+o4l6TtoSe -dAiidlCHaXyhgaukgagwgaUxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9y +A1UEAxMZQ2xhdXMgQXNzbWFubiBDQSBSU0EgMjAxMjEmMCQGCSqGSIb3DQEJARYX +Y2ErY2EtcnNhMjAxMkBlc210cC5vcmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCigPzGzn9gOGX0OPl62Yf9R+s/LErJOHdqd5SSf4M9mVcsXze7uhIQ +F1b660OmS0weMDIHlC9a2GVJKfok0fALRS3l1ct9YNymzqRHNTDuXo3CMOenYzKw +WYDMjJlkd49QjohRRzbqmvO0wIymq8ZCV4i5X59hFbt5ZZPKqf0X64cmi+u3K34z +BSu6wEb3CP3awVCbPSaDXFOXiSzMX/J7qLc9+/K0iQ1D7xhcIXVxzPDCo4RpwKfz +m97Bx1pcfmjaSXGvWKhRn735Pbulkvp7HVL1/pBZlSdlpK+Xmk8BOVl9CG+hj0JH +Sb8SUlM5dI1iO71MTwUPxLk+2qgOlgUtAgMBAAGjggFWMIIBUjAdBgNVHQ4EFgQU +CDjjiJJTbvFWaSdEtUygGMoGl+swgdoGA1UdIwSB0jCBz4AUCDjjiJJTbvFWaSdE +tUygGMoGl+uhgaukgagwgaUxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9y bmlhMREwDwYDVQQHEwhCZXJrZWxleTEUMBIGA1UEChMLRW5kbWFpbCBPcmcxDDAK -BgNVBAsTA01UQTEiMCAGA1UEAxMZQ2xhdXMgQXNzbWFubiBDQSBSU0EgMjAwOTEm -MCQGCSqGSIb3DQEJARYXY2ErY2EtcnNhMjAwOUBlc210cC5vcmeCCQDCPGFnOwrM -XjAMBgNVHRMEBTADAQH/MCIGA1UdEQQbMBmBF2NhK2NhLXJzYTIwMDlAZXNtdHAu -b3JnMCIGA1UdEgQbMBmBF2NhK2NhLXJzYTIwMDlAZXNtdHAub3JnMA0GCSqGSIb3 -DQEBBAUAA4IBAQCzOODaqAfYzLhNjCCmBiz4J9uOKA85vdkkx5/gTda2Y0I2D9hw -QeeeoiRkBeqFl6zyzMKmcbswIcHHxFQ0HTAJ8Jt0J5NZEkxTC4w+0DntStDZZiTY -5+WcqG1fVl2akf4bfbl8eZ4cuXF0FPgMMFD5sSJWqE1vS5vlioEzG3d19tjO1JA0 -hjTRhnWp4SPmr8GOKJdHIE0bVwk59FYB0odDPin2xFt9j569rTZ5zwlwQzAhmCMx -yA057nfhSkQaXHkvbOyKPNuZoBG8GkYkUed11prbrd1V1N3KgaAQd5aRnHYwOBjw -gkOzfEFkTE7aZiJnz7fXELrt9G1DWQDQgh4H +BgNVBAsTA01UQTEiMCAGA1UEAxMZQ2xhdXMgQXNzbWFubiBDQSBSU0EgMjAxMjEm +MCQGCSqGSIb3DQEJARYXY2ErY2EtcnNhMjAxMkBlc210cC5vcmeCCQDxQbM9ur0z +STAMBgNVHRMEBTADAQH/MCIGA1UdEQQbMBmBF2NhK2NhLXJzYTIwMTJAZXNtdHAu +b3JnMCIGA1UdEgQbMBmBF2NhK2NhLXJzYTIwMTJAZXNtdHAub3JnMA0GCSqGSIb3 +DQEBBQUAA4IBAQCaj00jWzCA4ZTkZpw6F4t5SVvsXeWhIi1xN6FR5x2xDambqqkN +x83WJPng8Fe+T3QMS3pCTHAZLo7ryxsAJifrHEIz1ewytGx9owShXABJyQ1MTSg3 +BiJ37EAVJTojhK4f2pDdydwn7nzs5d+4uh4/7sKRoj8ikh7zBn6q6cMRLT0vhff8 +1+L4bXCmQGJp51LtGxk4coYIoT1HyGiCQdvbKlIl10mqnsWDIn0vC9+MkC21qjPH +m+g5j7t5WxMtTqlpWccJJuK1U4CGcrt8vulGW9iyeELWXcO7OjtfD+jDYPuInzor +n9N9n8cyqk00p2ahJRaVpmnnhqNcubnfWAXj -----END CERTIFICATE----- Index: head/contrib/sendmail/PGPKEYS =================================================================== --- head/contrib/sendmail/PGPKEYS (revision 249728) +++ head/contrib/sendmail/PGPKEYS (revision 249729) @@ -1,2301 +1,2438 @@ This file contains the PGP keys used to sign the various versions of sendmail. You can add them to your PGP keyring using: PGP 2.X: pgp -ka PGPKEYS PGP 5.X: pgpk -a PGPKEYS GPG: gpg --import PGPKEYS Other versions of PGP may require you to separate each key into a separate file and add them one at a time. Type Bits KeyID Created Expires Algorithm Use pub 1024 0x16F4CCE9 1999-06-23 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 18 A4 51 78 CA 72 D4 A7 ED 80 BA 8A C4 98 71 1D uid Sendmail Security -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 gpExpdV7qPrw9k01j5rod5PjZlG8zV0= =SR28 -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use +pub 2048 5207CAD3 2013-01-02 ------- RSA Sign & Encrypt +fingerprint: B87D 4569 86F1 9484 07E5 CCB4 3D68 B25D 5207 CAD3 +uid Sendmail Signing Key/2013 + +-----BEGIN PGP PUBLIC KEY BLOCK----- +Version: GnuPG v1.4.13 (Darwin) + +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 +=kpXE +-----END PGP PUBLIC KEY BLOCK----- + +Type Bits KeyID Created Expires Algorithm Use pub 2048 CEEEF43B 2011-12-14 ------- RSA Sign & Encrypt fingerprint: CA7A 8F39 A241 9FFF B0A9 AB27 8E5A E9FB CEEE F43B uid Sendmail Signing Key/2012 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.9 (OpenBSD) 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 =qHzF -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 2048 A97884B0 2011-01-04 ------- RSA Sign & Encrypt fingerprint: 5872 6218 A913 400D E660 3601 39A4 C77D A978 84B0 uid Sendmail Signing Key/2011 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.9 (OpenBSD) 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 =pDAG -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 2048 85410ABE 2010-02-19 ------- RSA Sign fingerprint: B175 9644 5303 5DCE DD7B E919 604D FBF2 8541 0ABE uid Sendmail Signing Key/2010 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.9 (OpenBSD) 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 A4NAZlDwxoivB/5PTy67pX+AC1JgvPPafUMu =6Xeh -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xA77F2429 2009-01-01 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 33 3A 62 61 2C F3 21 AA 4E 87 47 F2 2F 2C 40 4D uid Sendmail Signing Key/2009 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.8 (OpenBSD) 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 wzfu =RCyv -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xF6B30729 2008-01-18 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 07 FB 9A F9 F7 94 4B E4 0F 28 D1 8E 23 6F A2 B0 uid Sendmail Signing Key/2008 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.8 (Darwin) mQCNA0eP9NsAAAEEAM5xPc5UXm01Mnqad8NPc5RkbeWcotxNOZXwrz4qQM6sr/E2 lEMGgo5FOjWJX3tjtys8gfXZJihz3XMD5RleniW3RIhc2tbTJotNq9Qq9+LmiuBs lT32O3ZSKsQtHQSfZ0j2bIabC/aQ4Dhfz13wz7x6VvRGwDbX3Niq8Mr2swcpAAUR tDFTZW5kbWFpbCBTaWduaW5nIEtleS8yMDA4IDxzZW5kbWFpbEBTZW5kbWFpbC5P Ukc+iQCVAwUQR4/029iq8Mr2swcpAQGa3QP+O6q/DvRLzM03AwIrEPRjdswejima 4BjKYYVQ1Qa7m4pyQeY/0CJScqu5A7p+kCrLqznmHu5aeezvjZy1mW7OCScPrCN9 yC3IJdu7oX6mGZwPdUnsEyJvtHmiRXkumJtncmhcTZyplmt9ZDHVADQUQWRnyuex oToSOeMPjS8YBpSJAJUDBRBHj/Xol0MBGHCTuEEBAYnzBAC5U2c8RtxNwwV4wh7V Q4isNyXcYqUlUL5ZjtsP5+vuHz4d1CtT/tD4jGagy6J30xUuwUcF7AlNLIcn4z98 GqF/aMCANut3dpGbzzvLYg+SkKkrZKH6fF4QPbdotp8NWKeiihoqD+hD6sVNc3zZ /JymsmD1T346VpRTwKf4JzkJG4kAlQMFEEeP9hEee7PIr5WWJQEBP1sD/3I5VeiC lW9fmwaAyOt/BrPIfsieL2TLysXCQbXFObNqqdR9APPlmQAtFdERjopQZu+VKvZd pInWGaIegibPr4ZyGHmGxmJwYyHCt0MNvjY2oA1WPVRvXz2dno7Q5SFDR0sQaFKe 4knKfzGu8fngy//R1vlO+UE3vTQ3cgTaIpDsiQCVAwUQR4/2GXCgJE0e+ZJRAQEH 6QP9FVDSFnXCSPy+tNFlLhtpjVOEqREG30iezAVZlx+yJVSb3/sG0LRCvXB1w3td jzW7A1iCvEQVb1yuNSFPb6Dq7TKoSpS8XZyCIetCpzab06D319Ubfcs2lHaDioY6 ibSaysDrBDETyXg1eQBIUQ+9iltfkI6HRpm5vgz8d4iwieqJAJUDBRBHj/YgyNXt KZX2F3EBASjtBACNzoDfjET153Zd3PQlj2X6b9BzjS8XHsjMuo+F04u9o3g78MSt +g2HW5Xi1ORh/LFSrkK7Qi9jLREr3dKQM9jjhfvxidN80H8jNyUIUJ3d1/K123rP z7GuXhXCfDCq/tjveUiVkoxQ1Q5h2OsXKqC0p7C7qpXKTg2CHLdbYTg/rIkAlQMF EEeP9mAhg+GxOW8HiQEBRpAEAI9MQwE6xoG08vdkrn8/tZEfK/h3zc3UgT5sjME3 NPbWD9o0W/KlIA7JKIpIYbX1M3GgGU5rlWmFyuRD5XVvu4NJ761PXAHenhg3wEk9 TySAwH7Edlhr0M1goALxpjiAzrh+hc0x2rz2jMcuRQlSh19MMe9sc9pDgUaXl7QJ Z51oiQCVAwUQR4/2colpYrhnjAoDAQHWPAP6AlqqzMhKJtWxVP4k10r06MwuUkOn tAeuPL4semoKb8lTtuBG14vADXsoavifuq2iv4KQCncGn3yWglCUjG46DKLluZyG uWjE44PEEiIs1zYzWo9F1Nw2C5VDR41/rzLqNctqr+bXac0lO3aRLgW1SkqJLI41 M+yXMYkf99dM4cuJAJUDBRBHj/Z6OCLbR8w3Ty0BAUwaBACH9QViBa/sejJULNu8 3i8B5tq0HOKvAzAQp/a79MxdFnhL8XrIhsTrprh3+/JvljrWLkfMe2tsVBTdTMJf snjjCijgtuCKaR5ESyu1Kl2E8mhp1A032LWRYYrxSyJqklqNem4HeZAN4N1CzMoS Iw5ELNeocuNmkBQn1xmkMYXiC4kAlQMFEEeP9pKcHL3i41xWNQEBqjgD/i9sEpQo 0YTW77za+n2rQD3141UZwql/F4cO0ds4sLSwJ3h4Ba8OkATHU1W2LbpogvpfvL6B 1H+4D7vo/VY/fSiNGUb8TjZfcj65ACToYokxK6PwBHL85jaWGh83kMS8pYDBL7zP sJ3sCyayKwAXOFpT7doaZU5FsC7tNMwlnRCuiQCVAwUQR4/2t29Sk9ijm6ZVAQGP TQP/Qbj1ZsqZfQn+7SXPmW0Y9+xUUQ351ecD1UX3yhuL195djP/O7ebeTiCBFkaG gWfMZtNCtaPQr1BhXBF9Xkum4IseUlRz1mTsdrhbAVtL6mGWMYcxQFTx13pHiGYS IaJhc+XQIxc7wmfW2LjOZpcHi0E2dhcjMEoWZGyEzKI/cJ2JAJUDBRBHj/bE71iW ZNQy4Z0BAe8aA/4oiv/MRmiRdDrVY8kTIZWb4whGYLqKEScOEuqir0PrMtyEUkzP YpkM1u3Cf4+zbtmgN16sx6DfyHAVGyI0U14hvnQhuVrrBs23dxGj2iciu14BvNJU YVaAoAWSp8qA14fDOAGd1H/InQmDZJrAiH61wQwjLrU1oI44Dr+55KHgO4kAlQMF EEeP9s3BnB0lEtNGHQEBxk4D/2WTAGSVuwDUGeIaHM1NVrgRcFFqrz37farxYNKx 7jZ1EqJXZXTqtSAUVc5LB8ko7V0P8w7CLso3Jj3hvFdYOt+6howpI/FO1Ur6RbTC ik6RUMbHRvIxpcTzZvRmWlMGcMdJFcCxsliOG7cyjpeuisaGJFIhyqfpAdqMKRn2 jOrqiQCVAwUQR4/5GcApykAW9MzpAQFuCgQAjaPwttPvJNegPa/KqZFVVO/VDaRm 9Aeiktw8lWlTE7BJ9SIePdsTEbKIzER/gVt85bOptJo6xpXaodoIjXWiSD+PHbdz tuEp88zv0B0mJcKSRIPt/u+baAgR2dKR1jlNvEjbpCm9rei+vqRNREpdrk32ls5d VwtrkbnFDuzLcgKJAJUDBRBHj/r11uCh/k++Kt0BAQvcBACq594Jrh+y+Pqf4bCL 8LrBqspvPL9MTMWDdwWvT7Yoaa+cyApuUWqpkyh8alWAwxnJmyw9I14zBr219862 0Rb1oCo2TDL/pMz8WVpyjD0RIxs4FcoJODD52kYxhLadKk0OrCXfrpWvIcp4sRJa kOWK3QzpD/0NtFJLZ+BnNq39h4kAlQMFEEeP+wK92o/WP+p9/QEBtVID/1AxNsk7 /ktDwz/khcTsCLILgtuKh+7jZa6K8FhhoqNXbjyUhZYjGne6No72KJ52P6P7iPLu SPDOmhu+z0kNTTm0KsWRSzQeUD08qyoB3qNcdxcRgAOJHl0MCXUwSxumfBb4iJq2 5282RCnsKroyWAhV8KjoJer1hTKCsu58Lqrv =jDs3 -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0x7093B841 2006-12-16 ---------- RSA Sign & Encrypt f16 Fingerprint16 = D9 FD C5 6B EE 1E 7A A8 CE 27 D9 B9 55 8B 56 B6 uid Sendmail Signing Key/2007 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.5 (OpenBSD) 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 as8y =w7F1 -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xAF959625 2005-12-31 ---------- RSA Sign & Encrypt f16 Fingerprint16 = E3 F4 97 BC 9F DF 3F 1D 9B 0D DF D5 77 9A C9 79 uid Sendmail Signing Key/2006 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) mQCNA0O3FKgAAAEEALUfKjFiXc8T2XS4C8N/jJQkProkzyl7mdN0xVKqokMy9/rx nbji5dG7WlxyJX3jI9eypZV/d5+KpXljvyC+cBIxhhmsEhVT6AsOkxlg/Y8Gmb5Q bn2mAiyeaylvcFeHLjBA+CaMByDms97M6FbiSzdXx6JtLP1Tdx57s8ivlZYlAAUR tDFTZW5kbWFpbCBTaWduaW5nIEtleS8yMDA2IDxzZW5kbWFpbEBTZW5kbWFpbC5P Ukc+iQCVAwUQQ7cUqB57s8ivlZYlAQEn6gQApe1I5DhI/Y+fwI8hjx7Ydd8LQ553 CoBYnvoqrxybSZtOc3D7LHoKIb01R2hx71O282soxjL6N9SGnGQMcVPINXAcJ0Z0 mTCpUZc+QtItS44R3aqp27q0C8FTt885/pkKT0cQM/9EjWRv3kI+f39gl+MwcA3I AV4NJmTpi6ASzmmJAJUDBRBDtxYm71iWZNQy4Z0BAbnQA/wIfK6PT+zTefydUovI G3dDLGGxMowpdG5yQwPwkAEIPFlbLhYsk8E9t8sLsLI1briqKaqxZkHo9ggPNkZU 6Kojwrs7imUZj4AMVL7HDqOlb+jHeYsg3yq/KzKIy3i1fmyUYA/cddSJOp3a0zjy IISZ9VPR6/KaOj8cLKTQqZG6tYkAlQMFEEO3FjvBnB0lEtNGHQEBJWgD/RkJuAVQ LL0cEe/VBUi4CmW3iGF+mAokJZn750ibVQg25SjDUc0UScxyvSnl8ehu3fjWmsEu ckHbzBWkMx/cnCb7xG5Ve1HGgzsBjFpvcQUM07y4JCFOfTOl3WiYP311EKBp2tnL 2i/kdD1IVITswAEQ7XId1NBIuf4P71v16rj/iQCVAwUQQ7cWRL3aj9Y/6n39AQGO uAQApQ5v6HZkgFNKT+SaXJOsqtk+xQQd19QfQQ2U13uaJ0nQ0i4O11WUTM9qfdWF utTlDTZKeEdz+Zb67KnuIi8PHyMpBPV1BGvWNqeiEN0Q5TmkxmaXBXTWtGeHoWw4 Jxaic4LdunSNDIpE0A9zfeaj9YJGX87I3KMf1DQ3h+FCRRWJAJUDBRBDtxZZfEtn baAOFWMBAVi/A/0bQQvU747R5bMC0vQLRMVOtq6rDwNPlXoFhzW26AU2Pb+mKCkU ugVqjFaAWm2ILxKvkjgDyfw6b62IvEK4rHJbfwH/FeIfi6e0+ye+TpXcCzXkARTm FHld0IERIXpaUA6XarNlWfiqaZN0YLpCQH0M29kTFvIfyoUHn9LgvBLe1YkAlQMF EEO3Fl9vUpPYo5umVQEBVtwEAIaSvlhM+gIKnlxN/1hpcG9639bLlUTkAt2gtn2w 4hPDZxMpblkQhcn3JcO9GD0BHNrV5qYBn3bLFwTG2FIoaROS4XyH8GPbEBWGNg9d IGm3kLdLTWsRVCtlkLKE74ipiiaN8JhPRGAtFUjcDVSSkGNzw2jBHP0hrQEKga9R wElSiQCVAwUQQ7cWepwcveLjXFY1AQFA/AP7BRC5j+Hed/B/RjbsbX3mxk4DprEh 6IijxC/2XAZbk1e25GspBO9Pbqs/2GufGCFX60Jj1FQJ2+vq8vg7chNNZ5XNEJse 6GrQtUx2/mEKMtvWGbWGSn53ET+AzmLne/u+f3bIh1OtXXro7w8OUkK9J+ZdG/9V J/a0nYTlPUw6o3KJAJUDBRBDtxaE1uCh/k++Kt0BAf14BAC4mGT1gE0aoW8rn7kk XJ3an4hThBZVuR2GS+rvwioEsIk2xe4NEFwJPGKmKq+C4vb0OWSiRev5l1fPx13x tWDGcm2k3SukDOHB0le6gS0RQx/WHCTe/lRKiQ3w/IuhLmrDfmoOOkDj6KVb5fA0 x0Uvd4ycXUPSoJcBq7dwNg0f8YkAlQMFEEO3Foo4IttHzDdPLQEB6N0D/3LRqVT4 Dhw6UmDIre9Tag8EmqTu3R8wFTmmEYDQ+7CxW+ZbJyYEDZp/WU/6xmOE2TSHaFPQ lgFEAaN1Cp4N9IXAM2EqeNK3fJOAsv4F5NOXbVtGJhyqG4aDUBZPvr/p123cpiiH 2yVIvHDkaacX1Tq/kECpKLj4k5D+dQYrUVdCiQCVAwUQQ7cWl4lpYrhnjAoDAQG9 pQQAg78+p2O+g7qPh1dAMcnQrI1eW3fTntWbadoKPXO5oFr/n+a74Go0D9+8J9Tt iW3C11KR3w1q+af5wp+viJfe8YDEwvm5gcmoCxPnwOeSAzdquujnQZRE5lynr6r7 QzJOFZv457qzndC2P5qSODCkmVC6uAsRxo4Xq/zflzRXmzCJAJUDBRBDtxaeIYPh sTlvB4kBAcvhA/9LBX9mskFW9IpA3Y5slRV1G2GFv0DXV79295p8OCKlZhEfk1y+ JyvT2hdnseD3Id2cyoMlEk57gJBuDrKdjeOLBMIJ2lOKGE6dLAsywSYkyFnngXu7 6QvoTS0mE+ahJlT9VDz79Jl6W+118cIeYzzt1TP8c1WkWBCJJcvge390BYkAlQMF EEO3FqXI1e0plfYXcQEB7W0D/AjxxjEMuS3UedxXI8VQzTB2o3c0o5DdlK2SXgHP SFxr9feksucCanCoYfuTWgxm/Ioy7cxtVNZT1dAHfn2MSrGN+2Adoep8E/o6PyiD t3pCzowtXFS1wjq1j/MX5SJoDrGl0VT1sQXsWh2uOFaeMfH1w9/r9Zkl1RYXYOEn /jkmiQCVAwUQQ7cWunCgJE0e+ZJRAQGTqgQAtdhMXLTw+tBCshX/CdLhrD0byRN5 omeib2QWmxdi7Djyz1wbDMBhnssM3SHUj/kRiorTnjv7qU8TS4z9r9zXw9U7XjCO T/CRepb3siiHzMU4KI5bxdg0ZAsauCVDel5MItT7OlK2Fjv4vCYam/jHGYXe6AEY dbARTWInDsFK7VCJAJUDBRBDtxgXwCnKQBb0zOkBAQHXA/47Mvt5oI8f2JbOMLkV E14upGU+zXYeWH7j9L4AYRzjl/Lg7tT+LBTjh+HEdl2UIMdYASrC6WbKEbatb4dr nu/pxd7/QaeSMV00P9j+Cfa3uIWn6HFUi+TH5fkLwERfkcLHKZ5SshZal9KTbjzv uwZsArnsNN0A/d1gUqljdDI/K4kAlQMFEEO7cAXPHrUDIjJ6AQEBYWMEAIJ5g1oG cL28orl4J7SxhOMyQODgaPRHusnWTBsa/ufUugVSR0g+3a2Pzyuq9xWqYStHf50N hdFx45JtPmkAiWuiBsyycVbBq/ursCeL2SCQPBCcbIfB+4BUbWoU62QA0a+sY5bW mitsU1FB2Mxd7QWqIBW4jqwB0nsAVxShRdWliJwEEAECAAYFAkO7mAoACgkQ+IYW ZdmHE1gcHAQAkMZ2julBDdx5TeQ3rrFus44snaHiq5exlN1wIJrVIhJzmOcHq5i5 ysfoKSha0cYf6F+6kTFxNL/Y9mneisg+rWfgRYmHDzNvXcuyAY/g6rwkRoyVN70q XhWXdY6nA29E5VH52pKCdjQgpbdyO6JDglLzfq7jVljCuPq8+PXqN+OIRgQQEQIA BgUCQ7uYzAAKCRDEsQeYhXlqI6AlAJ48z/+X/bUYIu1yekM+Wa3uN1SgSQCePzZl iV3/rvMdwqhHZPfM00GQQxOIRgQQEQIABgUCQ7vkHwAKCRAJp6JK0eWCB903AJ9x Jkm4hmDjMy8+ynBwFrnKzmGUgQCdGoOE+xbNHN2kArmTHDvzd80yQAeJAJUDBRJD u9CCXx7Ib4gMnlUBAfFkA/wP/qNyveNU4ZyJt+Ft/1xIYV4Gk/FJ4MOfpRlDYaN7 z2FXCjXtWeoxEJ8hqtWUMBuQHSm5T49Zv7Tb+6jtflscL3E/Kz3nIIr3Tzu1iNIM m3dzI37Qdk/7tnP2fp1fO2VbrQC7CtQTYODko6vTUSLap4+NWbidGNQMSEXAFfBK 2okAlQMFEEO776zh1PwU5tB0cQEBZrEEAMjAS0ahmy5KzFgRMrrI3RkrcKwi+Hnj Vuw6UowvW7tUhIkdFuXpd/a2YczU2Enivu7uSJgUD/2KzurD60ahJjSkC/l8xDNs v5wvbB+nYCOVDEvL32tvGiyLyT72MpkwT3ECYXFdlwpk2P7bk87tA9isuue0Nqvr TlO5vpTGYrPoiEYEEBECAAYFAkO9OlsACgkQorv7JAz5Vve2KACdGpTb2FWBtvXB cyIoyLoYGLWwtSYAoLDtcY9f816jYC3awv42YCMLuKuE =bh1L -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0x1EF99251 2004-12-30 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 4B 38 0E 0B 41 E8 FC 79 E9 7E 82 9B 04 23 EC 8A uid Sendmail Signing Key/2005 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 Zg== =LVEV -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0x95F61771 2003-12-10 ---------- RSA Sign & Encrypt Key fingerprint = 46 FE 81 99 48 75 30 B1 3E A9 79 43 BB 78 C1 D4 uid Sendmail Signing Key/2004 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 Dhl1CXPwZ/GWUw== =Ehw6 -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0x396F0789 2003-01-15 ---------- RSA Sign & Encrypt Key fingerprint = C4 73 DF 4A 97 9C 27 A9 EE 4F B2 BD 55 B5 E0 0F uid Sendmail Signing Key/2003 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) mQCNAz4ktksAAAEEAM9Vrk1RpJV8oPwEUPPbqUY14VYc/LY5JQYV8ZU704C4c65D L7VRxnO1U2FcJsd8IXz0Dd8xf5r5x3HMj00zEYe4x89gUEBW8bUODL3oH5Ww9064 2Cxlq7qK3nNPtct4QrXTadg378CJrsgVQ3V/L1Zaj1Tt7J2PByGD4bE5bweJAAUT tDFTZW5kbWFpbCBTaWduaW5nIEtleS8yMDAzIDxzZW5kbWFpbEBTZW5kbWFpbC5P Ukc+iQCVAwUQPiS2SyGD4bE5bweJAQHbfAQAixSSHRd464OikvI7cPBkCVG7v/jo n3/jc3fbOD3Y2jO+1L5K7SswDh2DwHfSx1BiUvhJutQPLbHv0SmrJwPQwR/DTi2e PQV0dCx1rv+ztRjXaE7tLA5XsS8RTiBXfQRNamxUqPVA1hCAl6ulBbZ+uIGG8F6H LgRV8jvNqjDxcKyJAJUDBRM+JLd071iWZNQy4Z0BATagBACq7IebGrBRDJtwPcps O2K9eb1PPkMg57MYE5OmnNgMnMtVWBnMz+V+7Dg+72Hh+B8AL+0tRLNFxCWCr8Q0 iW08kzgKA891NyZcvGyYCGr1vbaxGpHcb8wdgLE/2nu5E5poksA1x+Bo+ojJga17 r5XKiOoSIR3ubyAtm4PrXlo14okAlQMFEz4kt8bBnB0lEtNGHQEBa6oEALajY9IY M8zZkuuGNvZvjYKX1wt+TQwobFPOucx8RPT2NENF2jg+tstaansWBEXtFBbJO4Pw MkbGrSirdUMjy20SZKZV9SbVUtT3JbZjrD844N7emc97DNZNd5p52FjSX3518U8A e8p0K8+L4/o/P0UnEJodz+u6gTDPSlPJwJamiQCVAwUTPiS37m9Sk9ijm6ZVAQH4 mAP/ZccU08EeDnjwGXAIYXNRTxxdfmlyR1GvCinrDrKBfdoNSzzHkwHIwWsXuMkg mEcGeXNlXxBsEJTiBuXbKOyxnjMhxBX02mFgMNyYjcy9Vu7+zXiJSUgSAVlwontm 083bNqH1yoE+fwF9xWQX3UVMvkQXS1yAKuE457GvflnEkjGJAJUDBRM+JLgFnBy9 4uNcVjUBAfSZBACZAHhb+RCbihhAvk5LMgNznUkKEU+p002FQpk5+hMSDI+nVwTK D/2XdZe1P6hrKxJGWXjp0BXmZAonZB15b8DgdLDyCqTv+RLVPKTnpj+sGsBaq972 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 =ZdQs -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use sec+ 1024 0x678C0A03 2001-12-18 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 7B 02 F4 AA FC C0 22 DA 47 3E 2A 9A 9B 35 22 45 uid Sendmail Signing Key/2002 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 /EKFyOJWbfpUkVFOs0BhLhkspg== =lzX6 -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xCC374F2D 2000-12-14 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 59 AF DC 3E A2 7D 29 56 89 FA 25 70 90 0D 7E C1 uid Sendmail Signing Key/2001 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 RFljVEUVKZ/GGg== =Fv9l -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xE35C5635 1999-12-13 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 81 8C 58 EA 7A 9D 7C 1B 09 78 AC 5E EB 99 08 5D uid Sendmail Signing Key/2000 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 /tsXVdsdUQCdHWZaQyXqjOc46HDAvpUMY79Xr6s= =DfZ7 -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xA39BA655 1999-01-04 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 25 73 4C 8E 94 B1 E8 EA EA 9B A4 D6 00 51 C3 71 uid Sendmail Signing Key/1999 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 9wrG5w== =ghHr -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xD432E19D 1998-03-14 ---------- RSA Sign & Encrypt f16 Fingerprint16 = F9 32 40 A1 3B 3A B6 DE B2 98 6A 70 AF 54 9D 26 uid Sendmail Signing Key/1998 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) mQCNAzUKkdIAAAEEAKvdxY+iy7eLqxP5StbpZuxYNPWLye98bXA8oKwrEm1vy7Xq LBg3uNXjlMtwcNW/r+oFu5A++2R+1qC7w/0867C+52D2zkfGRH3hn9Lh6YaA5uIP LPbMGB3Tepbtj/lAtOJb7JKdybF7fkxkEUmwhuA5kAo1rKKWNu9YlmTUMuGdAAUT tDFTZW5kbWFpbCBTaWduaW5nIEtleS8xOTk4IDxzZW5kbWFpbEBTZW5kbWFpbC5P Ukc+iQCVAwUQNQqUqXxLZ22gDhVjAQHaYQQAiFITCRAEKhLlgjcFlehTDmVMFb92 1jiclN6377xe+A2zEtq4p3R8IwwiVTGeBzs0Zmnrlo+fAdVFYBjIYCtwKVTwd72U v6kxX40CjNkx6q264hUjILOumQ2P85/Aqg7wmnK9vM85CkmhKwu7b1OHsY+EFAlo U9CWyVjwSQqzHnaJAJUDBRA1CpJ4I+Ri1L97pCEBAcRtA/0czuj3hK7YiVL3zZaV EUnqw30auexjm0D+LhPpsHN7OM3im3z4+/4Pv2O2CH7nZhAsgRN9N+qdf3fCVGHq Y/ULkdsxKNbPEjSEWI+dqUWj6EyMSewKvBo7Zvljii6tBsM48ohtkWTo4B1/SuJb FM5TgXu2PMTgWHsT2DFb82wb/YkAlQMFEDUKkmfBnB0lEtNGHQEBmCwEALZgc6V1 mvRL/dqtGwdt38Uuw430cdM1Nk0FlkQsGXVWY49A1yrLAcuPQi8wzx4GS0LhtIeo vmrQ91DBaKxvxkboqM4orYf7PB5exSS9RQlTN2ezaf6IT9hVJHtXoYxU51Iny7hp r5t8L7od0gue9SNsLWjW9PZH1eKz83/g5VJZiQCVAwUQNQqSVu9YlmTUMuGdAQEv nwP9GvBao9wPX0r1aplZgkUItDwWGBbF8qQLgX5rM8b8IAxvHboIp8fbCkzhVxI7 v0IdYc0u1hrY3YfCNNbELu09JEcvtsl3hhmXnalOxCEdjoMUiHSb5f04sTBNOhD6 IWQqixDizoVzW5XljHBvgxWJhBus/dPJ6hdZPahioVd0oLiJAJUDBRA1CqZRAPLZ Ceu7G0EBAYlJBACumnB7zeAOpuj0y9h0Cgh0DleNWnqpHzTus4lbt3vw/cMpKmXt nGxMb4HE9rp6CHuuy3NumH9JHa9lwgb0T6bc0Zbc+LX1j0tKMC4BIsfEbFiOMSXU P+meyMUGY67VysVEeTqCgG4FqK7yOhnJsxjwDxJTIlrMoYwSSmsF4/R8Y4kAlQMF EDULPLgGfl7Yv7VlaQEBWZ0EALAGPhQbVEPTp2Hfm76ZRWjYJ8iDn98znfsHRYhS A/yIXF17eDtSkYU/ANOPNT8g5fOCWKjfLTJX4Al78rbHeGeKS+eO21WQCh8AF7Bv vZZWJZ0CyNnO++hzyamsOG1Z5Lrt/WQQPK4Jv5ZyqK3f2nGDufHuyQuIXxsdd+BX oqp3iQEVAwUQNQwe/ReiaPz3pQGjAQFowAgAk2fARyp4iyRl89ZZHGY09HpRbwQS 4jeDIEkBPBpSCBXIELgR7UonSoTwHD0nGHuwgdil5Zjl3PAlQJdo47Sh+hLCMoN/ mg0aI0vSnOxnnVgIcAigzlEAe03R12frWp32SjXJE1GdeFQWlzkk/6BoujKybvI1 oRr8OeAb8WzwmUr0c4VITEdb/J5c85yriHIuWpqYWIq5gb7evdj6JTKXly3gFp9R bwwd2tjlHYu6O7dHuEsmm4n4iK3rEglILvWIoS4kVV80v6IUE3xgLAVf7tnF5iNc nXcA386xUBB17zNvJDiUrciX17TuZsIVvIQnB519NN/ZVr1KpHSbLgMyZokBFQMF EDUMH1shtWni44zO8QEBGOEH+gKn6blq8L2AJ7Q2Pcw26Do4J9xlRPFKrDgAgy6y U9x509y4BeAZ6yn9RV0iGwhgzbdd57QrUpgcYNKGXSC/tJZZj2h3CZ06m1zaGtJ0 ig0dN7MU9gqZZMLy9f1EZmCwXeZHXL8t8lUMv8KEoq8+vvghCRvDNUgyQpkwcIOh rSu9yJ+OeJ8SpucL0ebJE3MmP2JYmqBCBg3pbr8bWvzjZ2Ny40OiyRnuXFP/jC2f ll6oMi8rOpWhjTTuHyrWEG9AxI8xeI5WsEOrJHH6stlmXJM1NtlJQ0D3qCdLn81M vitLgTPb/xUepRkFdBhZESG5BPDwT5hm1w7m7yhVohcH8AOJAJUDBRA1C3M0THwE EmD/AfUBAbzlA/9nDPPyBD9T1ygEHBsS2ZztO7enSk9DaYmt2jsqQ413UnpbhybR zZiuHXpqgG1p5GkYjP2Cw1DtT/dHu2nrD6Mf9j/4QYaRi0sdWLMTKVFPDlT+j1G0 Ag7/yCMhPv2xr3JOLPppCFiYPkdqRfmKnCWdCtrXmBvu4EiLTj1IXtc1WIkAlQMF EDUMLbdfHshviAyeVQEBQOUD/0QsDaDnzgcQHbtvJvDM0x+JYuejbvQEXh6k/cDP dLIC8XLZMd0uuAWE12SL1pm6J0q6+csKELascFKyOWTRoNrkWC5m1ltgRuyfXq3z Ur9SfL0KlfWFLXRsmGRd5V37u5H9kRjeTRlyiOeAcAMzaLunI9dK8sWet4p03GLy GOHQiQCVAwUQNQrIVW2DN4pRurLtAQG7gQP6AxTbsJ3Az+bwEgymYYo7EWADJGoB e1r48/0YjocxddhcXJSGL5dRNqY8NURSyvw/dDtjH81mVIbRlZR0QS4D2Jp94Q5/ mrWyqBW6Ah1EFtihncY3o/g1sxEC0hIj0/CklQmNttxeIGt1rRVyKxHa0tYkDtNW w+y5xZQSkE0yin2JAJUDBRA1CrJtdMsnjUUcGpkBAQ11A/4rp8Oy2cVbkrHHIxxM 2dML/tqNOgOGaB5tEISgtpv9xy1sVuEEA5T6rQJefeC0K00M3Mb3Sy4uumSaX3Io yTQr3XD3FZ4Q0n0AWR0ppRBvepqINfn/yeNF7268SDIMstQjlD9GzyCobqrR+VLT pxF7wXqyHcLyfqQjRiM9ZNTzAokAlQMFEDUKyAd3HZKuiXLHwQEB0+cEAJ308jCg rgWPcSstZH8Q8AoQajdxYMqImoQaqxC8zWjX7BK57pEFLelI3uXqkeEyqIGH0Yqc SvHQSSe2vLe3DohfGraCL2VK+b3Dw9IOaff4+ZFlxLVsqNiq13Z6aqRuKJ5uNjhI 0q9PPBZ8xzOMGfa3cMmW18INJvrVyTu3ENXUiQCVAgUQNQqcZHfUAfkkYu7tAQFr tAQA45cSUfYgq3d0RGx3RLUL0H+Bku5xMH2YuRJfpEI/Oc0Z1l/G7AfoR0pTqo9p uCu21glCUWm4TvUEaGJjT7q2pmcoLO3LCavNVAZHNTPQvjJgu/Z8+290yR9Ln/f8 4F1/zcRe4Gakq2weDM+h3gH914vXW7FoGJePc1X+azQ7pYCJARUDBRA1DBz15mc5 PORZW/UBATL3B/0aknENUHmJ6+axITL1ZODUe/KqFmLRgvCl2g///FtMHlMCUyWy q+MkyiHyjbgh1eN6gsCHUSHiROQdXMRRSxZm4FVsjznisjybCqzd93lBQQyKJ6XX KWu9SjJq/b6yg83byTgHZRW6kwjmDal97kVyHtV1WZBGDJ+v9nCY2tSvqujtNQbJ LWrHp447BSIXBBpMkF/J+cbl7yZLiUN8I1SnLYYttmKOtfD33eL41oKT2LK+j8sI kCd4XbcGoMJ+DExDVhFeiwwXWzomvTP42Wv0b8DYI+xeuE+AyARxJ5AVbGUBl4sZ qVuNMDZWhc0GLpT10RUeJ5HJVAGIWB2fLIsEiEYEEBECAAYFAjYOsI8ACgkQkKql f7AyFqOJ+gCfUIx3JYVnHib7dOfK9XbWXj9P6CoAn0Dd1JFMfXzHz0HODBhkMmJ3 7zKfiEYEEBECAAYFAjlTojoACgkQNNEFKz99GFEFXQCfR02mflvmFNb8uGlhOvxi Nt12kpAAn0uA3cx9aug8PHcqPcezdwPSWYWeiEYEEBECAAYFAj73BGAACgkQuCGJ Ap2ytbwliACgtmjNLo38Xv0KZXlU5tx54BQY+t8AnRsFftvOUwMJVA59oKrl3I5c I3SmiEYEEBECAAYFAj/V+mQACgkQUhjaYK3rgYsKgQCeIyf51Q8863lVdKLUDzTd jSK1rvsAn2ZxBCocmQh4YCvwRz1w4qqNZx04iEYEEBECAAYFAj/V+0sACgkQpNZc M1A3Zmf+qQCghIFSHbIMvME4+5Cucw08WL75mvEAmQEclbF5ShaYfcBxx+OZXDhV opS3 =j99z -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0x12D3461D 1997-05-07 ---------- RSA Sign & Encrypt f16 Fingerprint16 = CA AE F2 94 3B 1D 41 3C 94 7B 72 5F AE 0B 6A 11 uid Sendmail Signing Key/1997 -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 /g4qSHU= =6cVF -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 2048 0x0C8B8333 2011-12-14 ---------- RSA Sign & Encrypt f20 Fingerprint20 = B080 979F 4D04 3E19 D05A 369C 629E F8EE 0C8B 8333 sub 2048 0x6763ED11 2011-12-14 ---------- RSA uid Sendmail, Inc. Security Officer -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.11 (Darwin) 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 G09zJuZGoDdC9KhhogEVj4Ow+ydV =qF87 -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xA0F8AA0C 2006-03-17 ---------- DSA Sign & Encrypt f20 Fingerprint20 = 770E 4AC8 8A97 B69E 6E75 0605 1043 2518 A0F8 AA0C sub 2048 0x6E613854 2006-03-17 ---------- Diffie-Hellman uid Sendmail, Inc. Security Officer [REVOKED] -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.11 (Darwin) mQGiBEQbQzgRBAC7QmIW2r0oJ9Ixk1ewPxfwN1CU15k2ORBzRVIcO1UcLm6I5t3Z Gorbj22J8xNyY67yQ3pi5O+pffl5LujEKTco3D3sHhHnpz8vIaBiLyVUG3dCHZwU FP1jh9l5UqZ+QzXGAi969PMKkVyuWCHvUWNYLG+2RTwj8Ju7+NIzmv9RMwCg5nGw ftSHOf/hnfujlcHCLWtV1IsD/3NpxdobEobm+Zlkjk2nH1NtqwMDdnbBbj5U8jku LuhwZsvHbzie42JoroT/WI713JU3z1LrcwBYPxQGgVXlsyQi1ilJmd/JCsp9SpFN kqbog8zz7lZKD7PwRIduicPlXVft063DbABwTIi7YGv8xFnLt9vIix2gSco766KY rjPOA/9dlGIXq2HP6BGqYtZE6A6RwL2ujAXfene8hYLaMg8t52XyHvJDeay3siKy EhXt2tn+CyheTzKHXE7WdYGVIZq8OUBoJy/6eaL/paVbzw0SlhCuXNEP6J8SQClA rXDAwbl2SODl9T9eVUUbm7bQxdD942qCv+jhvBzAJrrHmZ0KPYhJBCARAgAJBQJE G1GyAh0DAAoJEBBDJRig+KoM86gAmgNUdUqrkiyji3OrzgzJOvvvGgPJAJ9mbH/M PYHevtf0D4/YGAWDKIEkNrQ/U2VuZG1haWwsIEluYy4gU2VjdXJpdHkgT2ZmaWNl ciA8c2VjdXJpdHktb2ZmaWNlckBzZW5kbWFpbC5jb20+iGEEExECACEFAkQbQzgC GwMHCwkIBwMCAQQVAggDBBYCAwECHgECF4AACgkQEEMlGKD4qgwt0QCdHD2sFnc1 cKILKClUR2Ad3x+OyysAoMTKNOPxq/burquoqt0rN8QnPkctiEYEEBECAAYFAkQb S9wACgkQGPUDgCTCeAKDiwCfae3NkBOnjSBa6E6ftmrDbzQYC9YAoN2Z8jaq1kM2 pXmC0s/QTIIsPc3iiJwEEAECAAYFAkQbS+sACgkQfEtnbaAOFWNKEQQAgIKzIX/E vAj4BaG13i3EYdvcSG0mfYsV4NVIdrDPnV3UmgbGBskgjkUyWHlUTJZ/AExcYyuT QNuivkH8pQKsXNUpm020PXvJg7t0/ZKTTv0tXyz2OT3OLKhw1O+qUOOrkxgSpfg7 UgQLTbZ0Ol1faP8iSTM5649rAOpqbPi8tneInAQQAQIABgUCRBtL9QAKCRDAKcpA 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 Z9M/bQ== =nJIt -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0xBF7BA421 1995-02-23 ---------- RSA Sign & Encrypt f16 Fingerprint16 = C0 28 E6 7B 13 5B 29 02 6F 7E 43 3A 48 4F 45 29 uid Eric P. Allman -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 0Qg0kzeGssNK0n6OoA== =pWwn -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use sec+ 1024 0xA00E1563 1998-03-07 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 66 39 58 9A 83 5F 52 26 88 E4 59 36 5A 94 D9 48 uid Gregory Neil Shapiro uid Gregory Neil Shapiro -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 =eOEB -----END PGP PUBLIC KEY BLOCK----- Type Bits KeyID Created Expires Algorithm Use pub 1024 0x22327A01 1999-05-30 ---------- RSA Sign & Encrypt f16 Fingerprint16 = 03 3D 49 6D E4 D9 D6 01 F8 9D B0 3A 3D 68 6A 86 uid Claus Assmann (PGP2) -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.4 (Darwin) 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 =nES8 -----END PGP PUBLIC KEY BLOCK----- -$Revision: 8.40 $, Last updated $Date: 2012/01/09 04:44:59 $ +$Revision: 8.43 $, Last updated $Date: 2013/01/18 17:40:21 $ Index: head/contrib/sendmail/RELEASE_NOTES =================================================================== --- head/contrib/sendmail/RELEASE_NOTES (revision 249728) +++ head/contrib/sendmail/RELEASE_NOTES (revision 249729) @@ -1,10494 +1,10523 @@ SENDMAIL RELEASE NOTES - $Id: RELEASE_NOTES,v 8.2011 2012/12/21 18:42:16 ca Exp $ + $Id: RELEASE_NOTES,v 8.2024 2013/04/19 15:01:58 ca Exp $ This listing shows the version of the sendmail binary, the version of the sendmail configuration files, the date of release, and a summary of the changes in that release. + +8.14.7/8.14.7 2013/04/21 + Drop support for IPv4-mapped IPv6 addresses to prevent the MTA + from using a mapped address over a legitimate IPv6 address + and to enforce the proper semantics over the IPv6 + connection. Problem noted by Ulrich Sporlein. + Fix a regression introduced in 8.14.6: the wrong list of + macros was sent to a milter in the EHLO stage. + Problem found by Fabrice Bellet, reported via RedHat + (Jaroslav Skarvada). + Fix handling of ORCPT parameter for DSNs: xtext decoding + was not performed and a wrong syntax check was applied + to the "addr-type" field. Problem noted by Dan Lukes + of Obludarium. + Fix handling of NUL characters in the MIME conversion functions + so that message bodies containing them will be sent + on properly. Note: this usually also affects mails + that are not converted as those functions are used + for other purposes too. Problem noted by Elchonon + Edelson of Lockheed Martin. + Do not perform "duplicate" elimination of recipients if they + resolve to the error mailer using a temporary failure + (4xy) via ruleset 0. Problem noted by Akira Takahashi + of IIJ. + CONTRIB: Updated version of etrn.pl script from John Beck + of Oracle. + Portability: + Unlike gcc, clang doesn't apply full prototypes to K&R + definitions. 8.14.6/8.14.6 2012/12/23 Fix a regression introduced in 8.14.5: if a server offers two AUTH lines, the MTA would not read them after STARTTLS has been used and hence SMTP AUTH for the client side would fail. Problem noted by Lena. Do not cache hostnames internally in a non case sensitive way as that may cause addresses to change from lower case to upper case or vice versa. These header modifications can cause problems with milters that rely on receiving headers in the same way as they are being sent out such as a DKIM signing milter. If MaxQueueChildren is set then it was possible that new queue runners could not be started anymore because an internal counter was subject to a race condition. If a milter decreases the timeout it waits for a communication with the MTA, the MTA might experience a write() timeout. In some situations, the resulting error might have been ignored. Problem noted by Werner Wiethege. Note: decreasing the communication timeout in a milter should not be done without considering the potential problems. smfi_setsymlist() now properly sets the list of macros for the milter which invoked it, instead of a global list for all milters. Problem reported by David Shrimpton of the University of Queensland. If Timeout.resolver.retrans is set to a value larger than 20, then resolver.retry was temporarily set to 0 for gethostbyaddr() lookups. Now it is set to 1 instead. Patch from Peter. If sendmail could not lock the statistics file due to a system error, and sendmail later sends a DSN for a mail that triggered such an error, then sendmail tried to access memory that was freed before (causing a crash on some systems). Problem reported by Ryan Stone. Do not log negative values for size= nor pri= to avoid confusing log parsers, instead limit the values to LONG_MAX. Account for an API change in newer versions of Cyrus-SASL. Patch from Hajimu UMEMOTO from FreeBSD. Do not try to resolve link-local addresses for IPv4 (just as it is done for IPv6). Patch from John Beck of Oracle. Improve logging of client and server STARTTLS connection failures that may be due to incompatible cipher lists by including the reason for the failure in a single log line. Suggested by James Carey of Boeing. Portability: Add support for Darwin 11.x and 12.x (Mac OS X 10.7 and 10.8). Add support for SunOS 5.12 (aka Solaris 12). Patch from John Beck of Oracle. 8.14.5/8.14.5 2011/05/17 Do not cache SMTP extensions across connections as the cache is based on hostname which may not be a unique identifier for a server, i.e., different machines may have the same hostname but provide different SMTP extensions. Problem noted by Jim Hermann. Avoid an out-of-bounds access in case a resolver reply for a DNS map lookup returns a size larger than 1K. Based on a patch from Dr. Werner Fink of SuSE. If a job is aborted using the interrupt signal (e.g., control-C from the keyboard), perform minimal cleanup to avoid invoking functions that are not signal-safe. Note: in previous versions the mail might have been queued up already and would be delivered subsequently, now an interrupt will always remove the queue files and thus prevent delivery. Per RFC 6176, when operating as a TLS client, do not offer SSLv2. Since TLS session resumption is never used as a client, disable use of RFC 4507-style session tickets. Work around gcc4 versions which reverse 25 years of history and no longer align char buffers on the stack, breaking calls to resolver functions on strict alignment platforms. Found by Stuart Henderson of OpenBSD. Read at most two AUTH lines from a server greeting (up to two lines are read because servers may use "AUTH mechs" and "AUTH=mechs"). Otherwise a malicious server may exhaust the memory of the client. Bug report by Nils of MWR InfoSecurity. Avoid triggering an assertion in the OpenLDAP code when the connection to an LDAP server is lost while making a query. Problem noted and patch provided by Andy Fiddaman. If ConnectOnlyTo is set and sendmail is compiled with NETINET6 it would try to use an IPv6 address if an IPv4 (or unparseable) address is specified. If SASLv2 is used, make sure that the macro {auth_authen} is stored in xtext format to avoid problems with parsing it. Problem noted by Christophe Wolfhugel. CONFIG: FEATURE(`ldap_routing') in 8.14.4 tried to add a missing -T that is required, but failed for some cases that did not use LDAP. This change has been undone until a better solution can be implemented. Problem found by Andy Fiddaman. CONFIG: Add cf/ostype/solaris11.m4 for Solaris11 support. Contributed by Casper Dik of Oracle. CONTRIB: qtool.pl: Deal with H entries that do not have a letter between the question marks. Patch from Stefan Christensen. DOC: Use a better description for the -i option in sendmail. Patch from Mitchell Berger. Portability: Add support for Darwin 10.x (Mac OS X 10.6). Enable HAVE_NANOSLEEP for FreeBSD 3 and later. Patch from John Marshall. Enable HAVE_NANOSLEEP for OpenBSD 4.3 and later. Use new directory "/system/volatile" for PidFile on Solaris 11. Patch from Casper Dik of Oracle. Fix compilation on Solaris 11 (and maybe some other OSs) when using OpenSSL 1.0. Based on patch from Jan Pechanec of Oracle. Set SOCKADDR_LEN_T and SOCKOPT_LEN_T to socklen_t for Solaris 11. Patch from Roger Faulkner of Oracle. New Files: cf/ostype/solaris11.m4 8.14.4/8.14.4 2009/12/30 SECURITY: Handle bogus certificates containing NUL characters in CNs by placing a string indicating a bad certificate in the {cn_subject} or {cn_issuer} macro. Patch inspired by Matthias Andree's changes for fetchmail. During the generation of a queue identifier an integer overflow could occur which might result in bogus characters being used. Based on patch from John Vannoy of Pepperdine University. The value of headers, e.g., Precedence, Content-Type, et.al., was not processed correctly. Patch from Per Hedeland. Between 8.11.7 and 8.12.0 the length limitation on a return path was erroneously reduced from MAXNAME (256) to MAXSHORTSTR (203). Patch from John Gardiner Myers of Proofpoint; the problem was also noted by Steve Hubert of University of Washington. Prevent a crash when a hostname lookup returns a seemingly valid result which contains a NULL pointer (this seems to be happening on some Linux versions). The process title was missing the current load average when the MTA was delaying connections due to DelayLA. Patch from Dick St.Peters of NetHeaven. Do not reset the number of queue entries in shared memory if only some of them are processed. Fix overflow of an internal array when parsing some replies from a milter. Problem found by Scott Rotondo of Sun Microsystems. If STARTTLS is turned off in the server (via M=S) then it would not be initialized for use in the client either. Patch from Kazuteru Okahashi of IIJ. If a Diffie-Hellman cipher is selected for STARTTLS, the handshake could fail with some TLS implementations because the prime used by the server is not long enough. Note: the initialization of the DSA/DH parameters for the server can take a significant amount of time on slow machines. This can be turned off by setting DHParameters to none or a file (see doc/op/op.me). Patch from Petr Lampa of the Brno University of Technology. Fix handling of `b' modifier for DaemonPortOptions on little endian machines for loopback address. Patch from John Beck of Sun Microsystems. Fix a potential memory leak in libsmdb/smdb1.c found by parfait. Based on patch from Jonathan Gray of OpenBSD. If a milter sets the reply code to "421" during the transfer of the body, the SMTP server will terminate the SMTP session with that error to match the behavior of the other callbacks. Return EX_IOERR (instead of 0) if a mail submission fails due to missing disk space in the mail queue. Based on patch from Martin Poole of RedHat. CONFIG: Using FEATURE(`ldap_routing')'s `nodomain' argument would cause addresses not found in LDAP to be misparsed. CONFIG: Using a CN restriction did not work for TLS_Clt as it referred to a wrong macro. Patch from John Gardiner Myers of Proofpoint. CONFIG: The option relaytofulladdress of FEATURE(`access_db') did not work if FEATURE(`relay_hosts_only') is used too. Problem noted by Kristian Shaw. CONFIG: The internal function lower() was broken and hence strcasecmp() did not work either, which could cause problems for some FEATURE()s if upper case arguments were used. Patch from Vesa-Matti J Kari of the University of Helsinki. LIBMILTER: Fix internal check whether a milter application is compiled against the same version of libmilter as it is linked against (especially useful for dynamic libraries). LIBMILTER: Fix memory leak that occurred when smfi_setsymlist() was used. Based on patch by Dan Lukes. LIBMILTER: Document the effect of SMFIP_HDR_LEADSPC for filters which add, insert, or replace headers. From Benjamin Pineau. LIBMILTER: Fix error messages which refer to "select()" to be correct if SM_CONF_POLL is used. Based on patch from John Nemeth. LIBSM: Fix handling of LDAP search failures where the error is carried in the search result itself, such as seen with OpenLDAP proxy servers. VACATION: Do not refer to a local variable outside its scope. Based on patch from Mark Costlow of Southwest Cyberport. Portability: Enable HAVE_NANOSLEEP for SunOS 5.11. Patch from John Beck of Sun Microsystems. Drop NISPLUS from default SunOS 5.11 map definitions. Patch from John Beck of Sun Microsystems. 8.14.3/8.14.3 2008/05/03 During ruleset processing the generation of a key for a map lookup and the parsing of the default value was broken for some macros, e.g., $|, which caused the BlankSub character to be inserted into the workspace and thus failures, e.g., rules that should have matched did not. 8.14.2 caused a regression: it accessed (macro) storage which was freed before. First instance of the problem reported by Matthew Dillon of DragonFlyBSD; variations of the same bug reported by Todd C. Miller of OpenBSD, Moritz Jodeit, and Dave Hayes. Improve pathname length checks for persistent host status. Patch from Joerg Sonnenberger of DragonFlyBSD. Reword misleading SMTP reply text for FEATURE(`badmx'). Problem noted by Beth Halsema. The read timeout was fixed to be Timeout.datablock if STARTTLS was activated. This may cause problems if that value is lowered from its default. Problem noted by Jens Elkner. CONFIG: Using LOCAL_TLS_CLIENT caused the tls_client ruleset to operate incorrectly. Problem found by Werner Wiethege. LIBMILTER: Omitting some protocol steps via the xxfi_negotiate() callback did not work properly. The patchlevel of libmilter has been set to 1 so a milter can determine whether libmilter contains this fix. MAKEMAP: If a delimiter is specified (-t) use that also when dumping a map. Patch from Todd C. Miller of OpenBSD. Portability: Add support for Darwin 9.x (Mac OS X 10.5). Support shared libraries in Darwin 8 and 9. Patch from Chris Behrens of Concentric. Add support for SCO OpenServer 6, patch from Boyd Gerber. DEVTOOLS: Clarify that confSHAREDLIBDIR requires a trailing slash. Added Files: devtools/OS/Darwin.9.x devtools/OS/OSR.i386 8.14.2/8.14.2 2007/11/01 If a message was queued and it contained 8 bit characters in a From: or To: header, then those characters could be "mistaken" for internal control characters during a queue run and trigger various consistency checks. Problem noted by Neil Rickert of Northern Illinois University. If MaxMimeHeaderLength is set to a value greater than 0 (which it is by default) then even if the Linelimit parameter is 0, sendmail corrupted in the non-transfer-encoding case every MAXLINE-1 characters. Patch from John Gardiner Myers of Proofpoint. Setting the suboption DeliveryMode for DaemonPortOptions did not work in earlier 8.14 versions. Note: DeliveryMode=interactive is silently converted to background if a milter can reject or delete a recipient. Prior to 8.14 this happened only if milter could delete recipients. ClientRate should trigger when the limit was exceeded (as documented), not when it was reached. Patch from John Beck of Sun Microsystems. Force a queue run for -qGqueuegroup even if no runners are specified (R=0) and forking (F=f) is requested. When multiple results are requested for a DNS map lookup (-z and -Z), return only those that are relevant for the query (not also those in the "additional section".) If the message transfer time to sendmail (when acting as server) exceeds Timeout.queuewarn or Timeout.queuereturn and the message is refused (by a milter), sendmail previously created a delivery status notification (DSN). Patch from Doug Heath of The Hertz Corporation. A code change in Cyrus-SASL 2.1.22 for sasl_decode64() requires the MTA to deal with some input (i.e., "=") itself. Problem noted by Eliot Lear. sendmail counted a delivery as successful if PIPELINING is compiled in but not offered by the server and the delivery failed temporarily. Patch from Werner Wiethege. If getting the result of an LDAP query times out then close the map so it will be reopened on the next lookup. This should help "failover" configurations that specify more than one LDAP server. If check_compat returns $#discard then a "savemail panic" could be triggered under some circumstances (e.g., requiring a system which does not have the compile time flag HASFLOCK set). Based on patch by Motonori Nakamura of National Institute of Informatics, Japan. If a milter rejected a recipient, the count for nrcpts= in the logfile entry might have been wrong. Problem found by Petra Humann of TU Dresden. If a milter invoked smfi_chgfrom() where ESMTP arguments are not NULL, the message body was lost. Patch from Motonori Nakamura of National Institute of Informatics, Japan. sendmail(8) had a bogus space in -qGname. Patch from Peng Haitao. CONTRIB: buildvirtuser: Preserve ownership and permissions when replacing files. CONTRIB: buildvirtuser: Skip dot-files (e.g., .cvsignore) when reading the /etc/mail/virtusers/ directory. CONTRIB: buildvirtuser: Emit warnings instead of exiting where appropriate. LIBMILTER: Fix ABI backwards compatibility so milters compiled against an older libmilter.so shared library can use an 8.14 libmilter.so shared library. LIBMILTER: smfi_version() did not properly extract the patchlevel from the version number, however, the returned value was correct for the current libmilter version. 8.14.1/8.14.1 2007/04/03 Even though a milter rejects a recipient the MTA will still keep it in its list of recipients and deliver to it if the transaction is accepted. This is a regression introduced in 8.14.0 due to the change for SMFIP_RCPT_REJ. Bug found by Andy Fiddaman. The new DaemonPortOptions which begin with a lower case character could not be set in 8.14.0. If a server shut down the connection in response to a STARTTLS command, sendmail would log a misleading error message due to an internal inconsistency. Problem found by Werner Wiethege. Document how some sendmail.cf options change the behavior of mailq. Noted by Paul Menchini of the North Carolina School of Science and Mathematics. CONFIG: Add confSOFT_BOUNCE m4 option for setting SoftBounce. CONFIG: 8.14.0's RELEASE_NOTES failed to mention the addition of the confMAX_NOOP_COMMANDS and confSHARED_MEMORY_KEY_FILE m4 options for setting MaxNOOPCommands and SharedMemoryKeyFile. CONFIG: Add confMILTER_MACROS_EOH and confMILTER_MACROS_DATA m4 options for setting Milter.macros.eoh and Milter.macros.data. CONTRIB: Use flock() and fcntl() in qtool.pl if necessary. Patch from Daniel Carroll of Mesa State College. LIBMILTER: Make sure an unknown command does not affect the currently available macros. Problem found by Andy Fiddaman. LIBMILTER: The MTA did not offer SMFIF_SETSYMLIST during option negotiation. Problem reported by Bryan Costales. LIBMILTER: Fix several minor errors in the documentation. Patches from Bryan Costales. PORTABILITY FIXES: AIX 5.{1,2}: libsm/util.c failed to compile due to redefinition of several macros, e.g., SIG_ERR. Patch from Jim Pirzyk with assistance by Bob Booth, University of Illinois at Urbana-Champaign. Add support for QNX.6. Patch from Sean Boudreau of QNX Software Systems. New Files: devtools/M4/depend/QNX6.m4 devtools/OS/QNX.6.x include/sm/os/sm_os_qnx.h New Files added in 8.14.0, but not shown in the release notes entry: libmilter/docs/smfi_chgfrom.html libmilter/docs/smfi_version.html 8.14.0/8.14.0 2007/01/31 Header field values are now 8 bit clean. Notes: - header field names are still restricted to 7 bit. - RFC 2822 allows only 7 bit (US-ASCII) characters in headers. Preserve spaces after the colon in a header. Previously, any number of spaces after the colon would be changed to exactly one space. In some cases of deeply nested aliases/forwarding, mail can be silently lost. Moreover, the MaxAliasRecursion limit may be reached too early, e.g., the counter may be off by a factor of 4 in case of a sequence of .forward files that refer to others. Patch from Motonori Nakamura of Kyoto University. Fix a regression in 8.13.8: if InputMailFilters is set then "sendmail -bs" can trigger an assertion because the hostname of the client is undefined. It is now set to "localhost" for the xxfi_connect() callback. Avoid referencing a freed variable during cleanup when terminating. Problem reported and diagnosed by Joe Maimon. New option HeloName to set the name for the HELO/EHLO command. Patch from Nik Clayton. New option SoftBounce to issue temporary errors (4xy) instead of permanent errors (5xy). This can be useful for testing. New suboptions for DaemonPortOptions to set them individually per daemon socket: DeliveryMode DeliveryMode refuseLA RefuseLA delayLA DelayLA queueLA QueueLA children MaxDaemonChildren New option -K for LDAP maps to replace %1 through %9 in the lookup key with the LDAP escaped contents of the arguments specified in the map lookup. Loosely based on patch from Wolfgang Hottgenroth. Log the time after which a greet_pause delay triggered. Patch from Nik Clayton. If a client is rejected via TCP wrapper or some other check performed by validate_connection() (in conf.c) then do not also invoke greet_pause. Problem noted by Jim Pirzyk of the University of Illinois at Urbana-Champaign. If a client terminates the SMTP connection during a pause introduced by greet_pause, then a misleading message was logged previously. Problem noted by Vernon Schryver et.al., patch from Matej Vela. New command "mstat" for control socket to provide "machine readable" status. New named config file rule check_eom which is called at the end of a message, its parameter is the size of the message. If the macro {addr_type} indicates that the current address is a header address it also distinguishes between recipient and sender addresses (as it is done for envelope addresses). When a macro is set in check_relay, then its value is accessible by all transactions in the same SMTP session. Increase size of key for ldap lookups to 1024 (MAXKEY). New option MaxNOOPCommands to override default of 20 for the number of "useless" commands before the SMTP server will slow down responding. New option SharedMemoryKeyFile: if shared memory support is enabled, the MTA can be asked to select a shared memory key itself by setting SharedMemoryKey to -1 and specifying a file where to store the selected key. Try to deal with open HTTP proxies that are used to send spam by recognizing some commands from them. If the first command from the client is GET, POST, CONNECT, or USER, then the connection is terminated immediately. New PrivacyOptions noactualrecipient to avoid putting X-Actual-Recipient lines in DSNs revealing the actual account that addresses map to. Patch from Dan Harkless. New options B, z, and Z for DNS maps: -B: specify a domain that is always appended to queries. -z: specify the delimiter at which to cut off the result of a query if it is too long. -Z: specify the maximum number of entries to be concatenated to form the result of a lookup. New target "check" in the Makefile of libsm: instead of running tests implicitly while building libsm, they must be explicitly started by using "make check". Fixed some inconsistent checks for NULL pointers that have been reported by the SATURN tool which has been developed by Isil Dillig and Thomas Dillig of Stanford University. Fix a potential race condition caused by a signal handler for terminated child processes. Problem noted by David F. Skoll. When a milter deleted a recipient, that recipient could cause a queue group selection. This has been disabled as it was not intended. New operator 'r' for the arith map to return a random number. Patch from Motonori Nakamura of Kyoto University. New compile time option MILTER_NO_NAGLE to turn off the Nagle algorithm for communication with libmilter ("cork" on Linux), which may improve the communication performance on some operating systems. Patch from John Gardiner Myers of Proofpoint. If sendmail received input that contained a CR without subsequent LF (thus violating RFC 2821 (2.3.7)), it could previously generate an additional blank line in the output as the last line. Restarting persistent queue runners by sending a HUP signal to the "queue control process" (QCP) works now. Increase the length of an input line to 12288 to deal with really long lines during SMTP AUTH negotiations. Problem noted by Werner Wiethege. If ARPANET mode (-ba) was selected STARTTLS would fail (due to a missing initialization call for that case). Problem noted by Neil Rickert of Northern Illinois University. If sendmail is linked against a library that initializes Cyrus-SASL before sendmail did it (such as libnss-ldap), then SMTP AUTH could fail for the sendmail client. A patch by Moritz Both works around the API design flaw of Cyrus-SASLv2. CONFIG: Make it possible to unset the StatusFile option by undefining STATUS_FILE. By not setting StatusFile, the MTA will not attempt to open a statistics file on each delivery. CONFIG: New FEATURE(`require_rdns') to reject messages from SMTP clients whose IP address does not have proper reverse DNS. Contributed by Neil Rickert of Northern Illinois University and John Beck of Sun Microsystems. CONFIG: New FEATURE(`block_bad_helo') to reject messages from SMTP clients which provide a HELO/EHLO argument which is either unqualified, or is one of our own names (i.e., the server name instead of the client name). Contributed by Neil Rickert of Northern Illinois University and John Beck of Sun Microsystems. CONFIG: New FEATURE(`badmx') to reject envelope sender addresses (MAIL) whose domain part resolves to a "bad" MX record. Based on contribution from William Dell Wisner. CONFIG: New macros SMTP_MAILER_LL and RELAY_MAILER_LL to override the maximum line length of the smtp mailers. CONFIG: New option `relaytofulladdress' for FEATURE(`access_db') to allow entries in the access map to be of the form To:user@example.com RELAY CONFIG: New subsuboptions eoh and data to specify the list of macros a milter should receive at those stages in the SMTP dialogue. CONFIG: New option confHELO_NAME for HeloName to set the name for the HELO/EHLO command. CONFIG: dnsbl and enhdnsbl can now also discard or quarantine messages by using those values as second argument. Patches from Nelson Fung. CONTRIB: cidrexpand uses a hash symbol as comment character and ignores everything after it unless it is in quotes or preceeded by a backslash. DEVTOOLS: New macro confMKDIR: if set to a program that creates directories, then it used for "make install" to create the required installation directories. DEVTOOLS: New macro confCCLINK to specify the linker to use for executables (defaults to confCC). LIBMILTER: A new version of the milter API has been created that has several changes which are listed below and documented in the webpages reachable via libmilter/docs/index.html. LIBMILTER: The meaning of the version macro SMFI_VERSION has been changed. It now refers only to the version of libmilter, not to the protocol version (which is used only internally, it is not user/milter-programmer visible). Additionally, a version function smfi_version() has been introduced such that a milter program can check the libmilter version also at runtime which is useful if a shared library is used. LIBMILTER: A new callback xxfi_negotiate() can be used to dynamically (i.e., at runtime) determine the available protocol actions and features of the MTA and also to specify which of these a milter wants to use. This allows for more flexibility than hardcoding these flags in the xxfi_flags field of the smfiDesc structure. LIBMILTER: A new callback xxfi_data() is available so milters can act on the DATA command. LIBMILTER: A new callback xxfi_unknown() is available so milters can receive also unknown SMTP commands. LIBMILTER: A new return code SMFIS_NOREPLY has been added which can be used by the xxfi_header() callback provided the milter requested the SMFIP_NOHREPL protocol action. LIBMILTER: The new return code SMFIS_SKIP can be used in the xxfi_body() callback to skip over further body chunks and directly advance to the xxfi_eom() callback. This is useful if a milter can make a decision based on the body chunks it already received without reading the entire rest of the body and the milter wants to invoke functions that are only available from the xxfi_eom() callback. LIBMILTER: A new function smfi_addrcpt_par() can be used to add new recipients including ESMTP parameters. LIBMILTER: A new function smfi_chgfrom() can be used to change the envelope sender including ESMTP parameters. LIBMILTER: A milter can now request to be informed about rejected recipients (RCPT) too. This requires to set the protocol flag SMFIP_RCPT_REJ during option negotiation. Whether a RCPT has been rejected can be checked by comparing the value of the macro {rcpt_mailer} with "error". LIBMILTER: A milter can now override the list of macros that it wants to receive from the MTA for each protocol step by invoking the function smfi_setsymlist() during option negotiation. LIBMILTER: A milter can receive header field values with all leading spaces by requesting the SMFIP_HDR_LEADSPC protocol action. Also, if the flag is set then the MTA does not add a leading space to headers that are added, inserted, or replaced. LIBMILTER: If a milter sets the reply code to "421" for the HELO callback, the SMTP server will terminate the SMTP session with that error to match the behavior of all other callbacks. New Files: cf/feature/badmx.m4 cf/feature/block_bad_helo.m4 cf/feature/require_rdns.m4 devtools/M4/UNIX/check.m4 include/sm/misc.h include/sm/sendmail.h include/sm/tailq.h libmilter/docs/smfi_addrcpt_par.html libmilter/docs/smfi_setsymlist.html libmilter/docs/xxfi_data.html libmilter/docs/xxfi_negotiate.html libmilter/docs/xxfi_unknown.html libmilter/example.c libmilter/monitor.c libmilter/worker.c libsm/memstat.c libsm/t-memstat.c libsm/t-qic.c libsm/util.c sendmail/daemon.h sendmail/map.h 8.13.8/8.13.8 2006/08/09 Fix a regression in 8.13.7: if shared memory is activated, then the server can erroneously report that there is insufficient disk space. Additionally make sure that an internal variable is set properly to avoid those misleading errors. Based on patch from Steve Hubert of University of Washington. Fix a regression in 8.13.7: the PidFile could be removed after the process that forks the daemon exited, i.e., if sendmail -bd is invoked. Problem reported by Kan Sasaki of Fusion Communications Corp. and Werner Wiethege. Avoid opening qf files if QueueSortOrder is "none". Patch from David F. Skoll. Avoid a crash when finishing due to referencing a freed variable. Problem reported and diagnosed by Moritz Jodeit. CONTRIB: cidrexpand now deals with /0 by issuing the entire IPv4 range (0..255). LIBMILTER: The "hostname" argument of the xxfi_connect() callback previously was the equivalent of {client_ptr}. However, this did not match the documentation of the function, hence it has been changed to {client_name}. See doc/op/op.* about these macros. 8.13.7/8.13.7 2006/06/14 A malformed MIME structure with many parts can cause sendmail to crash while trying to send a mail due to a stack overflow, e.g., if the stack size is limited (ulimit -s). This happens because the recursion of the function mime8to7() was not restricted. The function is called for MIME 8 to 7 bit conversion and also to enforce MaxMimeHeaderLength. To work around this problem, recursive calls are limited to a depth of MAXMIMENESTING (20); message content after this limit is treated as opaque and is not checked further. Problem noted by Frank Sheiness. The changes to the I/O layer in 8.13.6 caused a regression for SASL mechanisms that use the security layer, e.g., DIGEST-MD5. Problem noted by Robert Stampfli. If a timeout occurs while reading a message (during the DATA phase) a df file might have been left behind in the queue. This was another side effect of the changes to the I/O layer made in 8.13.6. Several minor problems have been fixed that were found by a Coverity scan of sendmail 8 as part of the NetBSD distribution. See http://scan.coverity.com/ Note: the scan generated also a lot of "false positives", e.g., "error" reports about situations that cannot happen. Most of those code places are marked with lint(1) comments like NOTREACHED, but Coverity does not understand those. Hence an explicit assertion has been added in some cases to avoid those false positives. If the start of the sendmail daemon fails due to a configuration error then in some cases shared memory segments or pid files were not removed. If DSN support is disabled via access_db, then related ESMTP parameters for MAIL and RCPT should be rejected. Problem reported by Akihiro Sagawa. Enabling zlib compression in OpenSSL 0.9.8[ab] breaks the padding bug work-around. Hence if sendmail is linked against either of these versions and compression is available, the padding bug work-around is turned off. Based on patch from Victor Duchovni of Morgan Stanley. CONFIG: FEATURE(`dnsbl') and FEATURE(`enhdnsbl') used blackholes.mail-abuse.org as default domain for lookups, however, that list is no longer available. To avoid further problems, no default value is available anymore, but an argument must be specified. Portability: Fix compilation on OSF/1 for sfsasl.c. Patch from Pieter Bowman of the University of Utah. 8.13.6/8.13.6 2006/03/22 SECURITY: Replace unsafe use of setjmp(3)/longjmp(3) in the server and client side of sendmail with timeouts in the libsm I/O layer and fix problems in that code. Also fix handling of a buffer in sm_syslog() which could have been used as an attack vector to exploit the unsafe handling of setjmp(3)/longjmp(3) in combination with signals. Problem detected by Mark Dowd of ISS X-Force. Handle theoretical integer overflows that could triggered if the server accepted headers larger than the maximum (signed) integer value. This is prevented in the default configuration by restricting the size of a header, and on most machines memory allocations would fail before reaching those values. Problems found by Phil Brass of ISS. If a server returns 421 for an RSET command when trying to start another transaction in a session while sending mail, do not trigger an internal consistency check. Problem found by Allan E Johannesen of Worcester Polytechnic Institute. If a server returns a 5xy error code (other than 501) in response to a STARTTLS command despite the fact that it advertised STARTTLS and that the code is not valid according to RFC 2487 treat it nevertheless as a permanent failure instead of a protocol error (which has been changed to a temporary error in 8.13.5). Problem reported by Jeff A. Earickson of Colby College. Clear SMTP state after a HELO/EHLO command. Patch from John Myers of Proofpoint. Observe MinQueueAge option when gathering entries from the queue for sorting etc instead of waiting until the entries are processed. Patch from Brian Fundakowski Feldman. Set up TLS session cache to properly handle clients that try to resume a stored TLS session. Properly count the number of (direct) child processes such that a configured value (MaxDaemonChildren) is not exceeded. Based on patch from Attila Bruncsak. LIBMILTER: Remove superfluous backslash in macro definition (libmilter.h). Based on patch from Mike Kupfer of Sun Microsystems. LIBMILTER: Don't try to set SO_REUSEADDR on UNIX domain sockets. This generates an error message from libmilter on Solaris, though other systems appear to just discard the request silently. LIBMILTER: Deal with sigwait(2) implementations that return -1 and set errno instead of returning an error code directly. Patch from Chris Adams of HiWAAY Informations Services. Portability: Fix compilation checks for closefrom(3) and statvfs(2) in NetBSD. Problem noted by S. Moonesamy, patch from Andrew Brown. 8.13.5/8.13.5 2005/09/16 Store the filesystem identifier of the df/ subdirectory (if it exists) in an internal structure instead of the base directory. This structure is used decide whether there is enough free disk space when selecting a queue, hence without this change queue selection could fail if a df/ subdirectory exists and is on a different filesystem than the base directory. Use the queue index of the df file (instead of the qf file) for checking whether a link(2) operation can be used to split an envelope across queue groups. Problem found by Werner Wiethege. If the list of items in the queue is larger than the maximum number of items to process, sort the queue first and then cut the list off instead of the other way around. Patch from Matej Vela of Rudjer Boskovic Institute. Fix helpfile to show full entry for ETRN. Problem noted by Penelope Fudd, patch from Neil Rickert of Northern Illinois University. FallbackSmartHost should also be tried on temporary errors. From John Beck of Sun Microsystems. When a server responds with 421 to the STARTTLS command then treat it as a temporary error, not as protocol error. Problem noted by Andrey J. Melnikoff. Properly define two functions in libsm as static because their prototype used static too. Patch from Peter Klein. Fix syntax errors in helpfile for MAIL and RCPT commands. LIBMILTER: When smfi_replacebody() is called with bodylen equals zero then do not silently ignore that call. Patch from Gurusamy Sarathy of Active State. LIBMILTER: Recognize "421" also in a multi-line reply to terminate the SMTP session with that error. Fix from Brian Kantor. Portability: New option HASSNPRINTF which can be set if the OS has a properly working snprintf(3) to get rid of the last two (safe) sprintf(3) calls in the source code. Add support for AIX 5.3. Add support for SunOS 5.11 (aka Solaris 11). Add support for Darwin 8.x. Patch from Lyndon Nerenberg. OpenBSD 3.7 has removed support for NETISO. CONFIG: Add OSTYPE(freebsd6) for FreeBSD 6.X. Set DontBlameSendmail to AssumeSafeChown and GroupWritableDirPathSafe for OSTYPE(darwin). Patch from Lyndon Nerenberg. Some features still used 4.7.1 as enhanced status code which was supposed to be eliminated in 8.13.0 because some broken systems misinterpret it as a permanent error. Patch from Matej Vela of Rudjer Boskovic Institute. Some default values in a generated cf file did not match the defaults in the sendmail binary. Problem noted by Mike Pechkin. New Files: cf/ostype/freebsd6.m4 devtools/OS/AIX.5.3 devtools/OS/Darwin.8.x devtools/OS/SunOS.5.11 include/sm/time.h 8.13.4/8.13.4 2005/03/27 The bug fixes in 8.13.3 for connection handling uncovered a different error which could result in connections that stay in CLOSE_WAIT state due to a variable that was not properly initialized. Problem noted by Michael Sims. Deal with empty hostnames in hostsignature(). This bug could lead to an endless loop when doing LMTP deliveries to another host. Problem first reported by Martin Lathoud and tracked down by Gael Roualland. Make sure return parameters are initialized in getmxrr(). Problem found by Gael Roualland using valgrind. If shared memory is used and the RunAsUser option is set, then the owner and group of the shared memory segment is set to the ids specified RunAsUser and the access mode is set to 0660 to allow for updates by sendmail processes. The number of queue entries that is (optionally) kept in shared memory was wrong in some cases, e.g., envelope splitting and bounce generation. Undo a change made in 8.13.0 to silently truncate long strings in address rewriting because the message can be triggered for header checks where long strings are legitimate. Problem reported by Mary Verge DeSisto, and tracked down with the help of John Beck of Sun Microsystems. The internal stab map did not obey the -m flag. Patch from Rob McMahon of Warwick University, England. The socket map did not obey the -f flag. Problem noted by Dan Ringdahl, forwarded by Andrzej Filip. The addition of LDAP recursion in 8.13.0 broke enforcement of the LDAP map -1 argument which tells the MTA to only return success if and only if a single LDAP match is found. Add additional error checks in the MTA for milter communication to avoid a possible segmentation fault. Based on patch by Joe Maimon. Do not trigger an assertion if X509_digest() returns success but does not assign a value to its output parameter. Based on patch by Brian Kantor. Add more checks when resetting internal AUTH data (applies only to Cyrus SASL version 2). Otherwise an SMTP session might be dropped after an AUTH failure. Portability: Add LA_LONGLONG as valid LA_TYPE type for systems that use "long long" to read load average data, e.g., AIX 5.1 in 32 bit mode. Note: this has to be set "by hand", it is not (yet) automatically detected. Problem noted by Burak Bilen. Use socklen_t for accept(), etc. on AIX 5.x. This should fix problems when compiling in 64 bit mode. Problem first reported by Harry Meiert of University of Bremen. New Files: include/sm/sem.h libsm/sem.c libsm/t-sem.c 8.13.3/8.13.3 2005/01/11 Enhance handling of I/O errors, especially EOF, when STARTTLS is active. Make sure a connection is not reused after it has been closed due to a 421 error. Problem found by Allan E Johannesen of Worcester Polytechnic Institute. Avoid triggering an assertion when sendmail is interrupted while closing a connection. Problem found by Allan E Johannesen of Worcester Polytechnic Institute. Regression: a change in 8.13.2 caused sendmail not to try the next MX host (or FallbackMXhost if configured) when, at connection open, the current server returns a 4xy or 5xy SMTP reply code. Problem noted by Mark Tranchant. 8.13.2/8.13.2 2004/12/15 Do not split the first header even if it exceeds the internal buffer size. Previously a part of such a header would end up in the body of the message. Problem noted by Simple Nomad of BindView. Do not complain about "cataddr: string too long" when checking headers that do not contain RFC 2822 addresses. Problem noted by Rich Graves of Brandeis University. If a server returns a 421 reply to the RSET command between message deliveries, do not attempt to deliver any more messages on that connection. This prevents bogus "Bad file number" recipient status. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Allow trailing white space in EHLO command as recommended by RFC 2821. Problem noted by Ralph Santagato of SBC Services. Deal with clients which use AUTH but negotiate a smaller buffer size for data exchanges than the value used by sendmail, e.g., Cyrus IMAP lmtp server. Based on patch by Jamie Clark. When passing ESMTP arguments for RCPT to a milter, do not cut them off at a comma. Problem noted by Krzysztof Oledzki. Add more logging to milter change header functions to complement existing logging. Based on patch from Gurusamy Sarathy of Active State. Include in include/sm/config.h when LDAPMAP is defined. Patch from Edgar Hoch of the University of Stuttgart. Fix DNS lookup if IPv6 is enabled when converting an IP address to a hostname for use with SASL. Problem noted by Ken Jones; patch from Hajimu UMEMOTO. CONFIG: For consistency enable MODIFY_MAILER_FLAGS for the prog mailer. Patch from John Beck of Sun Microsystems. LIBMILTER: It was possible that xxfi_abort() was called after xxfi_eom() for a message if some timeouts were triggered. Patch from Alexey Kravchuk. LIBMILTER: Slightly rearrange mutex use in listener.c to allow different threads to call smfi_opensocket() and smfi_main(). Patch from Jordan Ritter of Cloudmark. MAIL.LOCAL: Properly terminate MBDB before exiting. Problem noted by Nelson Fung. MAIL.LOCAL: make strip-mail.local used a wrong path to access mail.local. Problem noted by William Park. VACATION: Properly terminate MBDB before exiting. Problem noted by Nelson Fung. Portability: Add support for DragonFly BSD. New Files: cf/ostype/dragonfly.m4 devtools/OS/DragonFly include/sm/os/sm_os_dragonfly.h Deleted Files: libsm/vsscanf.c 8.13.1/8.13.1 2004/07/30 Using the default AliasFile ldap: specification would cause the objectClasses of the LDAP response to be included in the alias expansion. Problem noted by Brenden Conte of Rensselaer Polytechnic Institute. Fix support for a fallback smart host for system where DNS is (partially) available. From John Beck of Sun Microsystems. Fix SuperSafe=PostMilter behavior when a milter replaces a body but the data file is not yet stored on disk because it is smaller than the size of the memory buffer. Problem noted by David Russell. Fix certificate revocation list support; if a CRL was specified but the other side presented a cert that was signed by a different (trusted) CA than the one which issued the CRL, verification would always fail. Problem noted by Al Smith. Run mailer programs as the RunAsUser when RunAsUser is set and the F=S mailer flag is set without a U= mailer equate. Problem noted by John Gardiner Myers of Proofpoint. ${nbadrcpts} was off by one if BadRcptThrottle is zero. Patch from Sung-hoon Choi of DreamWiz Inc. CONFIG: Emit a warning if FEATURE(`access_db') is used after FEATURE(`greet_pause') because then the latter will not use the access map. Note: if no default value is given for FEATURE(`greet_pause') then it issues an error if FEATURE(`access_db') is not specified before it. Problem noted by Alexander Dalloz of University of Bielefeld. CONFIG: Invoke ruleset Local_greet_pause if FEATURE(`greet_pause') is used to give more flexibility for local changes. Portability: Fix a 64 bit problem in the socket map code. Problem noted by Geoff Adams. NetBSD 2.0F has closefrom(3). Patch from Andrew Brown. NetBSD can use sysctl(3) to get the number of CPUs in a system. Patch from Andrew Brown. Add a README file in doc/op/ to explain potential incompatibilities with various *roff related tools. Problem tracked down by Per Hedeland. New Files: doc/op/README 8.13.0/8.13.0 2004/06/20 Do not include AUTH data in a bounce to avoid leaking confidential information. See also cf/README about MSP and the section "Providing SMTP AUTH Data when sendmail acts as Client". Problem noted by Neil Rickert of Northern Illinois University. Fix compilation error in libsm/clock.c for -D_FFR_SLEEP_USE_SELECT=n and -DSM_CONF_SETITIMER=0. Problem noted by Juergen Georgi of RUS University of Stuttgart. Fix bug in conversion from 8bit to quoted-printable. Problem found by Christof Haerens, patch from Per Hedeland. Add support for LDAP recursion based on types given to attribute specifications in an LDAP map definition. This allows LDAP queries to return a new query, a DN, or an LDAP URL which will in turn be queried. See the ``LDAP Recursion'' section of doc/op/op.me for more information. Based on patch from Andrew Baucom. Extend the default LDAP specifications for AliasFile (O AliasFile=ldap:) and file classes (F{X}@LDAP) to include support for LDAP recursion via new attributes. See ``USING LDAP FOR ALIASES, MAPS, and CLASSES'' section of cf/README for more information. New option for LDAP maps: the -w option allows you to specify the LDAP API/protocol version to use. The default depends on the LDAP library. New option for LDAP maps: the -H option allows you to specify an LDAP URI instead of specifying the LDAP server via -h host and -p port. This also allows for the use of LDAP over SSL and connections via named sockets if your LDAP library supports it. New compile time flag SM_CONF_LDAP_INITIALIZE: set this if ldap_initialize(3) is available (and LDAPMAP is set). If MaxDaemonChildren is set and a command is repeated too often during a SMTP session then terminate it just like it is done for too many bad SMTP commands. Basic connection rate control support has been added: the daemon maintains the number of incoming connections per client IP address and total in the macros {client_rate} and {total_rate}, respectively. These macros can be used in the cf file to impose connection rate limits. A new option ConnectionRateWindowSize (default: 60s) determines the length of the interval for which the number of connections is stored. Based on patch from Jose Marcio Martins da Cruz, Ecole des Mines de Paris. Add optional protection from open proxies and SMTP slammers which send SMTP traffic without waiting for the SMTP greeting. If enabled by the new ruleset greet_pause (see FEATURE(`greet_pause')), sendmail will wait the specified amount of time before sending the initial 220 SMTP greeting. If any traffic is received before then, a 554 SMTP response is sent and all SMTP commands are rejected during that connection. If 32 NOOP (or unknown/bad) commands are issued by a client the SMTP server could sleep for a very long time. Fix based on patch from Tadashi Kobayashi of IIJ. Fix a potential memory leak in persistent queue runners if the number of entries in the queue exceeds the limit of jobs. Problem noted by Steve Hubert of University of Washington. Do not use 4.7.1 as enhanced status code because some broken systems misinterpret it as a permanent error. New value for SuperSafe: PostMilter which will delay fsync() until all milters accepted the mail. This can increase performance if many mails are rejected by milters due to body scans. Based on patch from David F. Skoll. New macro {msg_id} which contains the value of the Message-Id: header, whether provided by the client or generated by sendmail. New macro {client_connections} which contains the number of open connections in the SMTP server for the client IP address. Based on patch from Jose Marcio Martins da Cruz, Ecole des Mines de Paris. sendmail will now remove its pidfile when it exits. This was done to prevent confusion caused by running sendmail stop scripts two or more times, where the second and subsequent runs would report misleading error messages about sendmail's pid no longer existing. See section 1.3.15 of doc/op/op.me for a discussion of the implications of this, including how to correct broken scripts which may have depended on the old behavior. From John Beck of Sun Microsystems. Support per-daemon input filter lists which override the default filter list specified in InputMailFilters. The filters can be listed in the I= equate of DaemonPortOptions. Do not add all domain prefixes of the hostname to class 'w'. If your configuration relies on this behavior, you have to add those names to class 'w' yourself. Problem noted by Sander Eerkes. Support message quarantining in the mail queue. Quarantined messages are not run on normal queue displays or runs unless specifically requested with -qQ. Quarantined queue files are named with an hf prefix instead of a qf prefix. The -q command line option now can specify which queue to display or run. -qQ operates on quarantined queue items. -qL operates on lost queue items. Restricted mail queue runs and displays can be done based on the quarantined reason using -qQtext to run or display quarantined items if the quarantine reason contains the given text. Similarly, -q!Qtext will run or display quarantined items which do not have the given text in the quarantine reason. Items in the queue can be quarantined or unquarantined using the new -Q option. See doc/op/op.me for more information. When displaying the quarantine mailq with 'mailq -qQ', the quarantine reason is shown in a new line prefixed by "QUARANTINE:". A new error code for the $#error mailer, $@ quarantine, can be used to quarantine messages in check_* (except check_compat) and header check rulesets. The $: of the mailer triplet will be used for the quarantine reason. Add a new quarantine count to the mailstats collected. Add a new macro ${quarantine} which is the quarantine reason for a message if it is quarantined. New map type "socket" for a trivial query protocol over UNIX domain or TCP sockets (requires compile time option SOCKETMAP). See sendmail/README and doc/op/op.me for details as well as socketmapServer.pl and socketmapClient.pl in contrib. Code donated by Bastiaan Bakker of LifeLine Networks. Define new macro ${client_ptr} which holds the result of the PTR lookup for the client IP address. Note: this is the same as ${client_name} if and only if ${client_resolve} is OK. Add a new macro ${nbadrcpts} which contains the number of bad recipients received so far in a transaction. Call check_relay with the value of ${client_name} to deal with bogus DNS entries. See also FEATURE(`use_client_ptr'). Problem noted by Kai Schlichting. Treat Delivery-Receipt-To: headers the same as Return-Receipt-To: headers (turn them into DSNs). Delivery-Receipt-To: is apparently used by SIMS (Sun Internet Mail System). Enable connection caching for LPC mailers. Patch from Christophe Wolfhugel of France Telecom Oleane. Do not silently truncate long strings in address rewriting. Add support for Cyrus SASL version 2. From Kenneth Murchison of Oceana Matrix Ltd. Add a new AuthOption=m flag to require the use of mechanisms which support mutual authentication. From Kenneth Murchison of Oceana Matrix Ltd. Fix logging of TLS related problems (introduced in 8.12.11). The macros {auth_author} and {auth_authen} are stored in xtext format just like the STARTTLS related macros to avoid problems with parsing them. Problem noted by Pierangelo Masarati of SysNet s.n.c. New option AuthRealm to set the authentication realm that is passed to the Cyrus SASL library. Patch from Gary Mills of the University of Manitoba. Enable AUTH mechanism EXTERNAL if STARTTLS verification was successful, otherwise relaying would be allowed if EXTERNAL is listed in TRUST_AUTH_MECH() and STARTTLS is active. Add basic support for certificate revocation lists. Note: if a CRLFile is specified but the file is unusable, STARTTLS is disabled. Based on patch by Ralf Hornik. Enable workaround for inconsistent Cyrus SASLv1 API for mechanisms DIGEST-MD5 and LOGIN. Write pid to file also if sendmail only acts as persistent queue runner. Proposed by Gary Mills of the University of Manitoba. Keep daemon pid file(s) locked so other daemons don't try to overwrite each other's pid files. Increase maximum length of logfile fields for {cert_subject} and {cert_issuer} from 128 to 256. Requested by Christophe Wolfhugel of France Telecom. Log the TLS verification message on the STARTTLS= log line at LogLevel 12 or higher. If the MSP is invoked with the verbose option (-v) then it will try to use the SMTP command VERB to propagate this option to the MTA which in turn will show the delivery just like it was done before the default 8.12 separation of MSP and MTA. Based on patch by Per Hedeland. If a daemon is refusing connections for longer than the time specified by the new option RejectLogInterval (default: 3 hours) due to high load, log this information. Patch from John Beck of Sun Microsystems. Remove the ability for non-trusted users to raise the value of CheckpointInterval on the command line. New mailer flag 'B' to strip leading backslashes, which is a subset of the functionality of the 's' flag. New mailer flag 'W' to ignore long term host status information. Patch from Juergen Georgi of RUS University of Stuttgart. Enable generic mail filter API (milter) by default. To turn it off, add -DMILTER=0 to the compile time options. An internal SMTP session discard flag was lost after an RSET/HELO/EHLO causing subsequent messages to be sent instead of being discarded. This also caused milter callbacks to be called out of order after the SMTP session was reset. New option RequiresDirfsync to turn off the compile time flag REQUIRES_DIR_FSYNC at runtime. See sendmail/README for further information. New command line option -D logfile to send debug output to the indicated log file instead of stdout. Add Timeout.queuereturn.dsn and Timeout.queuewarn.dsn to control queue return and warning times for delivery status notifications. New queue sort order option: 'n'one for not sorting the queue entries at all. Several more return values for ruleset srv_features have been added to enable/disable certain features in the server per connection. See doc/op/op.me for details. Support for SMTP over SSL (smtps), activated by Modifier=s for DaemonPortOptions. Continue with DNS lookups on ECONNREFUSED and TRY_AGAIN when trying to canonify hostnames. Suggested by Neil Rickert of Northern Illinois University. Add support for a fallback smart host (option FallbackSmartHost) to be tried as a last resort after all other fallbacks. This is designed for sites with partial DNS (e.g., an accurate view of inside the company, but an incomplete view of outside). From John Beck of Sun Microsystems. Enable timeout for STARTTLS even if client does not start the TLS handshake. Based on patch by Andrey J. Melnikoff. Remove deprecated -v option for PH map, use -k instead. Patch from Mark Roth of the University of Illinois at Urbana-Champaign. libphclient is version 1.2.x by default, if version 1.1.x is required then compile with -DNPH_VERSION=10100. Patch from Mark Roth of the University of Illinois at Urbana-Champaign. Add Milter.macros.eom, allowing macros to be sent to milter applications for use in the xxfi_eom() callback. New macro {time} which contains the output of the time(3) function, i.e., the number of seconds since 0 hours, 0 minutes, 0 seconds, January 1, 1970, Coordinated Universal Time (UTC). If check_relay sets the reply code to "421" the SMTP server will terminate the SMTP session with a 421 error message. Get rid of dead code that tried to access the environment variable HOSTALIASES. Deprecate the use of ErrorMode=write. To enable this in 8.13 compile with -DUSE_TTYPATH=1. Header check rulesets using $>+ (do not strip comments) will get the header value passed in without balancing quotes, parentheses, and angle brackets. Based on patch from Oleg Bulyzhin. Do not complain and fix up unbalanced quotes, parentheses, and angle brackets when reading in rulesets. This allows rules to be written for header checks to catch strings that contain quotes, parentheses, and/or angle brackets. Based on patch from Oleg Bulyzhin. Do not close socket when accept(2) in the daemon encounters some temporary errors like ECONNABORTED. Added list of CA certificates that are used by members of the sendmail consortium, see CACerts. Portability: Two new compile options have been added: HASCLOSEFROM System has closefrom(3). HASFDWALK System has fdwalk(3). Based on patch from John Beck of Sun Microsystems. The Linux kernel version 2.4 series has a broken flock() so change to using fcntl() locking until they can fix it. Be sure to update other sendmail related programs to match locking techniques. New compile time option NEEDINTERRNO which should be set if does not declare errno itself. Support for UNICOS/mk and UNICOS/mp added, some changes for UNICOS. Patches contributed by Aaron Davis and Brian Ginsbach, Cray Inc., and Manu Mahonen of Center for Scientific Computing. Add support for Darwin 7.0/Mac OS X 10.3 (a.k.a. Panther). Extend support to Darwin 7.x/Mac OS X 10.3 (a.k.a. Panther). Remove path from compiler definition for Interix because Interix 3.0 and 3.5 put gcc in different locations. Also use to get the correct major()/minor() definitions. Based on feedback from Mark Funkenhauser. CONFIG: Add support for LDAP recursion to the default LDAP searches for maps via new attributes. See the ``USING LDAP FOR ALIASES, MAPS, and CLASSES'' section of cf/README and cf/sendmail.schema for more information. CONFIG: Make sure confTRUSTED_USER is valid even if confRUN_AS_USER is of the form "user:group" when used for submit.mc. Problem noted by Carsten P. Gehrke, patch from Neil Rickert of Northern Illinois University. CONFIG: Add a new access DB value of QUARANTINE:reason which instructs the check_* (except check_compat) to quarantine the message using the given reason. CONFIG: Use "dns -R A" as map type for dnsbl (just as for enhdnsbl) instead of "host" to avoid problem with looking up other DNS records than just A. CONFIG: New option confCONNECTION_RATE_WINDOW_SIZE to define the length of the interval for which the number of incoming connections is maintained. CONFIG: New FEATURE(`ratecontrol') to set the limits for connection rate control for individual hosts or nets. CONFIG: New FEATURE(`conncontrol') to set the limits for the number of open SMTP connections for individual hosts or nets. CONFIG: New FEATURE(`greet_pause') enables open proxy and SMTP slamming protection described above. The feature can take an argument specifying the milliseconds to wait and/or use the access database to look the pause time based on client hostname, domain, IP address, or subnet. CONFIG: New FEATURE(`use_client_ptr') to have check_relay use $&{client_ptr} as its first argument. This is useful for rejections based on the unverified hostname of client, which turns on the same behavior as in earlier sendmail versions when delay_checks was not in use. See also entry above about check_relay being invoked with ${client_name}. CONFIG: New option confREJECT_LOG_INTERVAL to specify the log interval when refusing connections for this long. CONFIG: Remove quotes around usage of confREJECT_MSG; in some cases this requires a change in a mc file. Requested by Ted Roberts of Electronic Data Systems. CONFIG: New option confAUTH_REALM to set the authentication realm that is passed to the Cyrus SASL library. Patch from Gary Mills of the University of Manitoba. CONFIG: Rename the (internal) classes {tls}/{src} to {Tls}/{Src} to follow the naming conventions. CONFIG: Add a third optional argument to local_lmtp to specify the A= argument. CONFIG: Remove the f flag from the default mailer flags of local_lmtp. CONFIG: New option confREQUIRES_DIR_FSYNC to turn off the compile time flag REQUIRES_DIR_FSYNC at runtime. CONFIG: New LOCAL_UUCP macro to insert rules into the generated cf file at the same place where MAILER(`uucp') inserts its rules. CONFIG: New options confTO_QUEUERETURN_DSN and confTO_QUEUEWARN_DSN to control queue return and warning times for delivery status notifications. CONFIG: New option confFALLBACK_SMARTHOST to define FallbackSmartHost. CONFIG: Add the mc file which has been used to create the cf file to the end of the cf file when using make in cf/cf/. Patch from Richard Rognlie. CONFIG: FEATURE(nodns) has been removed, it was a no-op since 8.9. Use ServiceSwitchFile to turn off DNS lookups, see doc/op/op.me. CONFIG: New option confMILTER_MACROS_EOM (sendmail Milter.macros.eom option) defines macros to be sent to milter applications for use in the xxfi_eom() callback. CONFIG: New option confCRL to specify file which contains certificate revocations lists. CONFIG: Add a new value (sendertoo) for the third argument to FEATURE(`ldap_routing') which will reject the SMTP MAIL From: command if the sender address doesn't exist in LDAP. See cf/README for more information. CONFIG: Add a fifth argument to FEATURE(`ldap_routing') which instructs the rulesets on whether or not to do a domain lookup if a full address lookup doesn't match. See cf/README for more information. CONFIG: Add a sixth argument to FEATURE(`ldap_routing') which instructs the rulesets on whether or not to queue the mail or give an SMTP temporary error if the LDAP server can't be reached. See cf/README for more information. Based on patch from Billy Ray Miller of Caterpillar. CONFIG: Experimental support for MTAMark, see cf/README for details. CONFIG: New option confMESSAGEID_HEADER to define a different Message-Id: header format. Patch from Bastiaan Bakker of LifeLine Networks. CONTRIB: New version of cidrexpand which uses Net::CIDR. From Derek J. Balling. CONTRIB: oldbind.compat.c has been removed due to security problems. Found by code inspection done by Reasoning, Inc. DEVTOOLS: Add an example file for devtools/Site/, contributed by Neil Rickert of Northern Illinois University. LIBMILTER: Add new function smfi_quarantine() which allows the filter's EOM routine to quarantine the current message. Filters which use this function must include the SMFIF_QUARANTINE flag in the registered smfiDesc structure. LIBMILTER: If a milter sets the reply code to "421", the SMTP server will terminate the SMTP session with that error. LIBMILTER: Upon filter shutdown, libmilter will not remove a named socket in the file system if it is running as root. LIBMILTER: Add new function smfi_progress() which allows the filter to notify the MTA that an EOM operation is still in progress, resetting the timeout. LIBMILTER: Add new function smfi_opensocket() which allows the filter to attempt to establish the interface socket, and detect failure to do so before calling smfi_main(). LIBMILTER: Add new function smfi_setmlreply() which allows the filter to return a multi-line SMTP reply. LIBMILTER: Deal with more temporary errors in accept() by ignoring them instead of stopping after too many occurred. Suggested by James Carlson of Sun Microsystems. LIBMILTER: Fix a descriptor leak in the sample program found in docs/sample.html. Reported by Dmitry Adamushko. LIBMILTER: The sample program also needs to use SMFIF_ADDRCPT. Reported by Carl Byington of 510 Software Group. LIBMILTER: Document smfi_stop() and smfi_setdbg(). Patches from Bryan Costales. LIBMILTER: New compile time option SM_CONF_POLL; define this if poll(2) should be used instead of select(2). LIBMILTER: New function smfi_insheader() and related protocol amendments to support header insertion operations. MAIL.LOCAL: Add support for hashed mail directories, see mail.local/README. Contributed by Chris Adams of HiWAAY Informations Services. MAILSTATS: Display quarantine message counts. MAKEMAP: Add new flag -D to specify the comment character to use instead of '#'. VACATION: Add new flag -j to auto-respond to messages regardless of whether or not the recipient is listed in the To: or Cc: headers. VACATION: Add new flag -R to specify the envelope sender address for the auto-response message. New Files: CACerts cf/feature/conncontrol.m4 cf/feature/greet_pause.m4 cf/feature/mtamark.m4 cf/feature/ratecontrol.m4 cf/feature/use_client_ptr.m4 cf/ostype/unicos.m4 cf/ostype/unicosmk.m4 cf/ostype/unicosmp.m4 contrib/socketmapClient.pl contrib/socketmapServer.pl devtools/OS/Darwin.7.0 devtools/OS/UNICOS-mk devtools/OS/UNICOS-mp devtools/Site/site.config.m4.sample include/sm/os/sm_os_unicos.h include/sm/os/sm_os_unicosmk.h include/sm/os/sm_os_unicosmp.h libmilter/docs/smfi_insheader.html libmilter/docs/smfi_progress.html libmilter/docs/smfi_quarantine.html libmilter/docs/smfi_setdbg.html libmilter/docs/smfi_setmlreply.html libmilter/docs/smfi_stop.html sendmail/ratectrl.c Deleted Files: cf/feature/nodns.m4 contrib/oldbind.compat.c devtools/OS/CRAYT3E.2.0.x devtools/OS/CRAYTS.10.0.x libsm/vsprintf.c Renamed Files: devtools/OS/Darwin.7.0 => devtools/OS/Darwin.7.x 8.12.11/8.12.11 2004/01/18 Use QueueFileMode when opening qf files. This error was a regression in 8.12.10. Problem detected and diagnosed Lech Szychowski of the Polish Power Grid Company. Properly count the number of queue runners in a work group and make sure the total limit of MaxQueueChildren is not exceeded. Based on patch from Takayuki Yoshizawa of Techfirm, Inc. Take care of systems that can generate time values where the seconds can exceed the usual range of 0 to 59. Problem noted by Randy Diffenderfer of EDS. Avoid regeneration of identical queue identifiers by processes whose process id is the same as that of the initial sendmail process that was used to start the daemon. Problem noted by Randy Diffenderfer of EDS. When a milter invokes smfi_delrcpt() compare the supplied recipient address also against the printable addresses of the current list to deal with rewritten addresses. Based on patch from Sean Hanson of The Asylum. BadRcptThrottle now also works for addresses which return the error mailer, e.g., virtusertable entries with the right hand side error:. Patch from Per Hedeland. Fix printing of 8 bit characters as octals in log messages. Based on patch by Andrey J. Melnikoff. Undo change of algorithm for MIME 7-bit base64 encoding to 8-bit text that has been introduced in 8.12.3. There are some examples where the new code fails, but the old code works. To get the 8.12.3-8.12.10 version, compile sendmail with -DMIME7TO8_OLD=0. If you have an example of improper 7 to 8 bit conversion please send it to us. Return normal error code for unknown SMTP commands instead of the one specified by check_relay or a milter for a connection. Problem noted by Andrzej Filip. Some ident responses contain data after the terminating CRLF which causes sendmail to log "POSSIBLE ATTACK...newline in string". To avoid this everything after LF is ignored. If the operating system supports O_EXLOCK and HASFLOCK is set then a possible race condition for creating qf files can be avoided. Note: the race condition does not exist within sendmail, but between sendmail and an external application that accesses qf files. Log the proper options name for TLS related mising files for the CACertPath, CACertFile, and DHParameters options. Do not split an envelope if it will be discarded, otherwise df files could be left behind. Problem found by Wolfgang Breyha. The use of the environment variables HOME and HOSTALIASES has been deprecated and will be removed in version 8.13. This only effects configuration which preserve those variable via the 'E' command in the cf file as sendmail clears out its entire environment. Portability: Add support for Darwin 7.0/Mac OS X 10.3 (a.k.a. Panther). Solaris 10 has unsetenv(), patch from Craig Mohrman of Sun Microsystems. LIBMILTER: Add extra checks in case a broken MTA sends bogus data to libmilter. Based on code review by Rob Grzywinski. SMRSH: Properly assemble commands that contain '&&' or '||'. Problem noted by Eric Lee of Talking Heads. New Files: devtools/OS/Darwin.7.0 8.12.10/8.12.10 2003/09/24 (Released: 2003/09/17) SECURITY: Fix a buffer overflow in address parsing. Problem detected by Michal Zalewski, patch from Todd C. Miller of Courtesan Consulting. Fix a potential buffer overflow in ruleset parsing. This problem is not exploitable in the default sendmail configuration; only if non-standard rulesets recipient (2), final (4), or mailer-specific envelope recipients rulesets are used then a problem may occur. Problem noted by Timo Sirainen. Accept 0 (and 0/0) as valid input for set MaxMimeHeaderLength. Problem noted by Thomas Schulz. Add several checks to avoid (theoretical) buffer over/underflows. Properly count message size when performing 7->8 or 8->7 bit MIME conversions. Problem noted by Werner Wiethege. Properly compute message priority based on size of entire message, not just header. Problem noted by Axel Holscher. Reset SevenBitInput to its configured value between SMTP transactions for broken clients which do not properly announce 8 bit data. Problem noted by Stefan Roehrich. Set {addr_type} during queue runs when processing recipients. Based on patch from Arne Jansen. Better error handling in case of (very unlikely) queue-id conflicts. Perform better error recovery for address parsing, e.g., when encountering a comment that is too long. Problem noted by Tanel Kokk, Union Bank of Estonia. Add ':' to the allowed character list for bogus HELO/EHLO checking. It is used for IPv6 domain literals. Patch from Iwaizako Takahiro of FreeBit Co., Ltd. Reset SASL connection context after a failed authentication attempt. Based on patch from Rob Siemborski of CMU. Check Berkeley DB compile time version against run time version to make sure they match. Do not attempt AAAA (IPv6) DNS lookups if IPv6 is not enabled in the kernel. When a milter adds recipients and one of them causes an error, do not ignore the other recipients. Problem noted by Bart Duchesne. CONFIG: Use specified SMTP error code in mailertable entries which lack a DSN, i.e., "error:### Text". Problem noted by Craig Hunt. CONFIG: Call Local_trust_auth with the correct argument. Patch from Jerome Borsboom. CONTRIB: Better handling of temporary filenames for doublebounce.pl and expn.pl to avoid file overwrites, etc. Patches from Richard A. Nelson of Debian and Paul Szabo. MAIL.LOCAL: Fix obscure race condition that could lead to an improper mailbox truncation if close() fails after the mailbox is fsync()'ed and a new message is delivered after the close() and before the truncate(). MAIL.LOCAL: If mail delivery fails, do not leave behind a stale lockfile (which is ignored after the lock timeout). Patch from Oleg Bulyzhin of Cronyx Plus LLC. Portability: Port for AIX 5.2. Thanks to Steve Hubert of University of Washington for providing access to a computer with AIX 5.2. setreuid(2) works on OpenBSD 3.3. Patch from Todd C. Miller of Courtesan Consulting. Allow for custom definition of SMRSH_CMDDIR and SMRSH_PATH on all operating systems. Patch from Robert Harker of Harker Systems. Use strerror(3) on Linux. If this causes a problem on your Linux distribution, compile with -DHASSTRERROR=0 and tell sendmail.org about it. Added Files: devtools/OS/AIX.5.2 8.12.9/8.12.9 2003/03/29 SECURITY: Fix a buffer overflow in address parsing due to a char to int conversion problem which is potentially remotely exploitable. Problem found by Michal Zalewski. Note: an MTA that is not patched might be vulnerable to data that it receives from untrusted sources, which includes DNS. To provide partial protection to internal, unpatched sendmail MTAs, 8.12.9 changes by default (char)0xff to (char)0x7f in headers etc. To turn off this conversion compile with -DALLOW_255 or use the command line option -d82.101. To provide partial protection for internal, unpatched MTAs that may be performing 7->8 or 8->7 bit MIME conversions, the default for MaxMimeHeaderLength has been changed to 2048/1024. Note: this does have a performance impact, and it only protects against frontal attacks from the outside. To disable the checks and return to pre-8.12.9 defaults, set MaxMimeHeaderLength to 0/0. Do not complain about -ba when submitting mail. Problem noted by Derek Wueppelmann. Fix compilation with Berkeley DB 1.85 on systems that do not have flock(2). Problem noted by Andy Harper of Kings College London. Properly initialize data structure for dns maps to avoid various errors, e.g., looping processes. Problem noted by Maurice Makaay of InterNLnet B.V. CONFIG: Prevent multiple application of rule to add smart host. Patch from Andrzej Filip. CONFIG: Fix queue group declaration in MAILER(`usenet'). CONTRIB: buildvirtuser: New option -t builds the virtusertable text file instead of the database map. Portability: Revert wrong change made in 8.12.7 and actually use the builtin getopt() version in sendmail on Linux. This can be overridden by using -DSM_CONF_GETOPT=0 in which case the OS supplied version will be used. 8.12.8/8.12.8 2003/02/11 SECURITY: Fix a remote buffer overflow in header parsing by dropping sender and recipient header comments if the comments are too long. Problem noted by Mark Dowd of ISS X-Force. Fix a potential non-exploitable buffer overflow in parsing the .cf queue settings and potential buffer underflow in parsing ident responses. Problem noted by Yichen Xie of Stanford University Compilation Group. Fix ETRN #queuegroup command: actually start a queue run for the selected queue group. Problem noted by Jos Vos. If MaxMimeHeaderLength is set and a malformed MIME header is fixed, log the fixup as "Fixed MIME header" instead of "Truncated MIME header". Problem noted by Ian J Hart. CONFIG: Fix regression bug in proto.m4 that caused a bogus error message: "FEATURE() should be before MAILER()". MAIL.LOCAL: Be more explicit in some error cases, i.e., whether a mailbox has more than one link or whether it is not a regular file. Patch from John Beck of Sun Microsystems. 8.12.7/8.12.7 2002/12/29 Properly clean up macros to avoid persistence of session data across various connections. This could cause session oriented restrictions, e.g., STARTTLS requirements, to erroneously allow a connection. Problem noted by Tim Maletic of Priority Health. Do not lookup MX records when sorting the MSP queue. The MSP only needs to relay all mail to the MTA. Problem found by Gary Mills of the University of Manitoba. Do not restrict the length of connection information to 100 characters in some logging statements. Problem noted by Erik Parker. When converting an enhanced status code to an exit status, use EX_CONFIG if the first digit is not 2, 4, or 5 or if *.1.5 is used. Reset macro $x when receiving another MAIL command. Problem noted by Vlado Potisk of Wigro s.r.o. Don't bother setting the permissions on the build area statistics file, the proper permissions will be put on the file at install time. This fixes installation over NFS for some users. Problem noted by Martin J. Dellwo of 3-Dimensional Pharmaceuticals, Inc. Fix problem of decoding SASLv2 encrypted data. Problem noted by Alex Deiter of Mobile TeleSystems, Komi Republic. Log milter socket open errors at MilterLogLevel 1 or higher instead of 11 or higher. Print early system errors to the console instead of silently exiting. Problem noted by James Jong of IBM. Do not process a queue group if Runners is set to 0, regardless of whether F=f or sendmail is run in verbose mode (-v). The use of -qGname will still force queue group "name" to be run even if Runners=0. Change the level for logging the fact that a daemon is refusing connections due to high load from LOG_INFO to LOG_NOTICE. Patch from John Beck of Sun Microsystems. Use location information for submit.cf from NetInfo (/locations/sendmail/submit.cf) if available. Re-enable ForkEachJob which was lost in 8.12.0. Problem noted by Neil Rickert of Northern Illinois University. Make behavior of /canon in debug mode consistent with usage in rulesets. Patch from Shigeno Kazutaka of IIJ. Fix a potential memory leak in envelope splitting. Problem noted by John Majikes of IBM. Do not try to share an mailbox database LDAP connection across different processes. Problem noted by Randy Kunkee. Fix logging for undelivered recipients when the SMTP connection times out during message collection. Problem noted by Neil Rickert of Northern Illinois University. Avoid problems with QueueSortOrder=random due to problems with qsort() on Solaris (and maybe some other operating systems). Problem noted by Stephan Schulz of Gruner+Jahr.. If -f "" is specified, set the sender address to "<>". Problem noted by Matthias Andree. Fix formatting problem of footnotes for plain text output on some versions of tmac. Patch from Per Hedeland. Portability: Berkeley DB 4.1 support (requires at least 4.1.25). Some getopt(3) implementations in GNU/Linux are broken and pass a NULL pointer to an option which requires an argument, hence the builtin version of sendmail is used instead. This can be overridden by using -DSM_CONF_GETOPT=0. Problem noted by Vlado Potisk of Wigro s.r.o. Support for nph-1.2.0 from Mark D. Roth of the University of Illinois at Urbana-Champaign. Support for FreeBSD 5.0's MAC labeling from Robert Watson of the TrustedBSD Project. Support for reading the number of processors on an IRIX system from Michel Bourget of SGI. Support for UnixWare 7.1 based on input from Larry Rosenman. Interix support from Nedelcho Stanev of Atlantic Sky Corporation. Update Mac OS X/Darwin portability from Wilfredo Sanchez. CONFIG: Enforce tls_client restrictions even if delay_checks is used. Problem noted by Malte Starostik. CONFIG: Deal with an empty hostname created via bogus DNS entries to get around access restrictions. Problem noted by Kai Schlichting. CONFIG: Use FEATURE(`msp', `[127.0.0.1]') in submit.mc by default to avoid problems with hostname resolution for localhost which on many systems does not resolve to 127.0.0.1 (or ::1 for IPv6). If you do not use IPv4 but only IPv6 then you need to change submit.mc accordingly, see the comment in the file itself. CONFIG: Set confDONT_INIT_GROUPS to True in submit.mc to avoid error messages from initgroups(3) on AIX 4.3 when sending mail to non-existing users. Problem noted by Mark Roth of the University of Illinois at Urbana-Champaign. CONFIG: Allow local_procmail to override local_lmtp settings. CONFIG: Always allow connections from 127.0.0.1 or IPv6:::1 to relay. CONTRIB: cidrexpand: Deal with the prefix tags that may be included in access_db. CONTRIB: New version of doublebounce.pl contributed by Leo Bicknell. LIBMILTER: On Solaris libmilter may get into an endless loop if an error in the communication from/to the MTA occurs. Patch from Gurusamy Sarathy of Active State. LIBMILTER: Ignore EINTR from sigwait(3) which may happen on Tru64. Patch from from Jose Marcio Martins da Cruz of Ecole Nationale Superieure des Mines de Paris. MAIL.LOCAL: Fix a truncation race condition if the close() on the mailbox fails. Problem noted by Tomoko Fukuzawa of Sun Microsystems. MAIL.LOCAL: Fix a potential file descriptor leak if mkstemp(3) fails. Patch from John Beck of Sun Microsystems. SMRSH: SECURITY: Only allow regular files or symbolic links to be used for a command. Problem noted by David Endler of iDEFENSE, Inc. New Files: devtools/OS/Interix include/sm/bdb.h 8.12.6/8.12.6 2002/08/26 Do not add the FallbackMXhost (or its MX records) to the list returned by the bestmx map when -z is used as option. Otherwise sendmail may act as an open relay if FallbackMXhost and FEATURE(`relay_based_on_MX') are used together. Problem noted by Alexander Ignatyev. Properly split owner- mailing list messages when SuperSafe is set to interactive. Problem noted by Todd C. Miller of Courtesan Consulting. Make sure that an envelope is queued in the selected queue group even if some recipients are deleted or invalid. Problem found by Chris Adams of HiWAAY Informations Services. Do not send a bounce message if a message is completely collected from the SMTP client. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Provide an 'install-submit-st' target for sendmail/Makefile to install the MSP statistics file using the file named in the confMSP_STFILE devtools variable. Requested by Jeff Earickson of Colby College. Queue up mail with a temporary error if setusercontext() fails during a delivery attempt. Patch from Todd C. Miller of Courtesan Consulting. Fix handling of base64 encoded client authentication data for SMTP AUTH. Patch from Elena Slobodnik of life medien GmbH. Set the OpenLDAP option LDAP_OPT_RESTART so the client libraries restart interrupted system calls. Problem noted by Luiz Henrique Duma of BSIOne. Prevent a segmentation fault if a program passed a NULL envp using execve(). Document a problem with the counting of queue runners that may cause delays if MaxQueueChildren is set too low. Problem noted by Ian Duplisse of Cable Television Laboratories, Inc. If discarding a message based on a recipient, don't try to look up the recipient in the mailbox database if F=w is set. This allows users to discard bogus recipients when dealing with spammers without tipping them off. Problem noted by Neil Rickert of Northern Illinois University. If applying a header check to a header with unstructured data, e.g., Subject:, then do not run syntax checks that are supposed for addresses on the header content. Count messages rejected/discarded via the check_data ruleset. Portability: Fix compilation on systems which do not allow simple copying of the variable argument va_list. Based on fix from Scott Walters. Fix NSD map open bug. From Michel Bourget of SGI. Add some additional IRIX shells to the default shell list. From Michel Bourget of SGI. Fix compilation issues on Mac OS X 10.2 (Darwin 6.0). NETISO support has been dropped. CONFIG: There was a seemingly minor change in 8.12.4 with respect to handling entries of IP nets/addresses with RHS REJECT. These would be rejected in check_rcpt instead of only being activated in check_relay. This change has been made to avoid potential bogus temporary rejection of relay attempts "450 4.7.1 Relaying temporarily denied. Cannot resolve PTR record for ..." if delay_checks is enabled. However, this modification causes a change of behavior if an IP net/address is listed in the access map with REJECT and a host/domain name is listed with OK or RELAY, hence it has been reversed such that the behavior of 8.12.3 is restored. The original change was made on request of Neil Rickert of Northern Illinois University, the side effect has been found by Stefaan Van Hoornick. CONFIG: Make sure delay_checks works even for sender addresses using the local hostname ($j) or domains in class {P}. Based on patch from Neil Rickert of Northern Illinois University. CONFIG: Fix temporary error handling for LDAP Routing lookups. Fix from Andrzej Filip. CONTRIB: New version of etrn.pl script and external man page (etrn.0) from John Beck of Sun Microsystems. LIBMILTER: Protect a free(3) operation from being called with a NULL pointer. Problem noted by Andrey J. Melnikoff. LIBMILTER: Protect against more interrupted select() calls. Based on patch from Jose Marcio Martins da Cruz of Ecole Nationale Superieure des Mines de Paris. New Files: contrib/etrn.0 8.12.5/8.12.5 2002/06/25 SECURITY: The DNS map can cause a buffer overflow if the user specifies a dns map using TXT records in the configuration file and a rogue DNS server is queried. None of the sendmail supplied configuration files use this option hence they are not vulnerable. Problem noted independently by Joost Pol of PINE Internet and Anton Rang of Sun Microsystems. Unprintable characters in responses from DNS servers for the DNS map type are changed to 'X' to avoid potential problems with rogue DNS servers. Require a suboption when setting the Milter option. Problem noted by Bryan Costales. Do not silently overwrite command line settings for DirectSubmissionModifiers. Problem noted by Bryan Costales. Prevent a segmentation fault when clearing the event list by turning off alarms before checking if event list is empty. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Close a potential race condition in transitioning a memory buffered file onto disk. From Janani Devarajan of Sun Microsystems. Portability: Include paths.h on Linux systems running glibc 2.0 or later to get the definition for _PATH_SENDMAIL, used by rmail and vacation. Problem noted by Kevin A. McGrail of Peregrine Hardware. NOTE: Linux appears to have broken flock() again. Unless the bug is fixed before sendmail 8.13 is shipped, 8.13 will change the default locking method to fcntl() for Linux kernel 2.4 and later. You may want to do this in 8.12 by compiling with -DHASFLOCK=0. Be sure to update other sendmail related programs to match locking techniques. 8.12.4/8.12.4 2002/06/03 SECURITY: Inherent limitations in the UNIX file locking model can leave systems open to a local denial of service attack. Be sure to read the "FILE AND MAP PERMISSIONS" section of the top level README for more information. Problem noted by lumpy. Use TempFileMode (defaults to 0600) for the permissions of PidFile instead of 0644. Change the default file permissions for new alias database files from 0644 to 0640. This can be overridden at compile time by setting the DBMMODE macro. Fix a potential core dump problem if the environment variable NAME is set. Problem noted by Beth A. Chaney of Purdue University. Expand macros before passing them to libmilter. Problem noted by Jose Marcio Martins da Cruz of Ecole Nationale Superieure des Mines de Paris. Rewind the df (message body) before truncating it when libmilter replaces the body of a message. Problem noted by Gisle Aas of Active State. Change SMTP reply code for AUTH failure from 500 to 535 and the initial zero-length response to "=" per RFC 2554. Patches from Kenneth Murchison of Oceana Matrix Ltd. Do not try to fix broken message/rfc822 MIME attachments by inserting a MIME-Version: header when MaxMimeHeaderLength is set and no 8 to 7 bit conversion is needed. Based on patch from Rehor Petr of ICZ (Czech Republic). Do not log "did not issue MAIL/EXPN/VRFY/ETRN" if the connection is rejected anyway. Noted by Chris Loelke. Mention the submission mail queue in the mailq man page. Requested by Bill Fenner of AT&T. Set ${msg_size} macro when reading a message from the command line or the queue. Detach from shared memory before dropping privileges back to user who started sendmail. If AllowBogusHELO is set to false (default) then also complain if the argument to HELO/EHLO contains white space. Suggested by Seva Gluschenko of Cronyx Plus. Allow symbolicly linked forward files in writable directory paths if both ForwardFileInUnsafeDirPath and LinkedForwardFileInWritableDir DontBlameSendmail options are set. Problem noted by Werner Spirk of Leibniz-Rechenzentrum Munich. Portability: Operating systems that lack the ftruncate() call will not be able to use Milter's body replacement feature. This only affects Altos, Maxion, and MPE/iX. Digital UNIX 5.0 has changed flock() semantics to be non-compliant. Problem noted by Martin Mokrejs of Charles University in Prague. The sparc64 port of FreeBSD 5.0 now supports shared memory. CONFIG: FEATURE(`preserve_luser_host') needs the macro map. Problem noted by Andrzej Filip. CONFIG: Using 'local:' as a mailertable value with FEATURE(`preserve_luser_host') and LUSER_RELAY caused mail to be misaddressed. Problem noted by Andrzej Filip. CONFIG: Provide a workaround for DNS based rejection lists that fail for AAAA queries. Problem noted by Chris Boyd. CONFIG: Accept the machine's hostname as resolvable when checking the sender address. This allows locally submitted mail to be accepted if the machine isn't connected to a nameserver and doesn't have an /etc/hosts entry for itself. Problem noted by Robert Watson of the TrustedBSD Project. CONFIG: Use deferred expansion for checking the ${deliveryMode} macro in case the SMTP VERB command is used. Problem noted by Bryan Costales. CONFIG: Avoid a duplicate '@domain' virtusertable lookup if no matches are found. Fix from Andrzej Filip. CONFIG: Fix wording in default dnsbl rejection message. Suggested by Lou Katz of Metron Computerware, Ltd. CONFIG: Add mailer cyrusv2 for Cyrus V2. Contributed by Kenneth Murchison of Oceana Matrix Ltd. CONTRIB: Fix wording in default dnsblaccess rejection message to match dnsbl change. DEVTOOLS: Add new option for access mode of statistics file, confSTMODE, which specifies the permissions when initially installing the sendmail statistics file. LIBMILTER: Mark the listening socket as close-on-exec in case a user's filter starts other applications. LIBSM: Allow the MBDB initialize, lookup, and/or terminate functions in SmMbdbTypes to be set to NULL. MAKEMAP: Change the default file permissions for new databases from 0644 to 0640. This can be overridden at compile time by setting the DBMMODE macro. SMRSH: Fix man page bug: replace SMRSH_CMDBIN with SMRSH_CMDDIR. Problem noted by Dave Alden of Ohio State University. VACATION: When listing the vacation database (-l), don't show bogus timestamps for excluded (-x) addresses. Problem noted by Bryan Costales. New Files: cf/mailer/cyrusv2.m4 8.12.3/8.12.3 2002/04/05 NOTICE: In general queue files should not be moved if queue groups are used. In previous versions this could cause mail not to be delivered if a queue file is repeatedly moved by an external process whenever sendmail moved it back into the right place. Some precautions have been taken to avoid moving queue files if not really necessary. sendmail may use links to refer to queue files and it may store the path of data files in queue files. Hence queue files should not be moved unless those internals are understood and the integrity of the files is not compromised. Problem noted by Anne Bennett of Concordia University. If an error mail is created, and the mail is split across different queue directories, and SuperSafe is off, then write the mail to disk before splitting it, otherwise an assertion is triggered. Problem tracked down by Henning Schmiedehausen of INTERMETA. Fix possible race condition that could cause sendmail to forget running queues. Problem noted by Jeff Wasilko of smoe.org. Handle bogus qf files better without triggering assertions. Problem noted by Guy Feltin. Protect against interrupted select() call when enforcing Milter read and write timeouts. Patch from Gurusamy Sarathy of ActiveState. Matching queue IDs with -qI should be case sensitive. Problem noted by Anne Bennett of Concordia University. If privileges have been dropped, don't try to change group ID to the RunAsUser group. Problem noted by Neil Rickert of Northern Illinois University. Fix SafeFileEnvironment path munging when the specified path contains a trailing slash. Based on patch from Dirk Meyer of Dinoex. Do not limit sendmail command line length to SM_ARG_MAX (usually 4096). Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Clear full name of sender for each new envelope to avoid bogus data if several mails are sent in one session and some of them do not have a From: header. Problem noted by Bas Haakman. Change timeout check such that cached information about a connection will be immediately invalid if ConnectionCacheTimeout is zero. Based on patch from David Burns of Portland State University. Properly count message size for mailstats during mail collection. Problem noted by Werner Wiethege. Log complete response from LMTP delivery agent on failure. Based on patch from Motonori Nakamura of Kyoto University. Provide workaround for getopt() implementations that do not catch missing arguments. Fix the message size calculation if the message body is replaced by a milter filter and buffered file I/O is being used. Problem noted by Sergey Akhapkin of Dr.Web. Do not honor SIGUSR1 requests if running with extra privileges. Problem noted by Werner Wiethege. Prevent a file descriptor leak on mail delivery if the initial connect fails and DialDelay is set. Patch from Servaas Vandenberghe of Katholieke Universiteit Leuven. Properly deal with a case where sendmail is called by root running a set-user-ID (non-root) program. Problem noted by Jon Lusky of ISS Atlanta. Avoid leaving behind stray transcript (xf) files if multiple queue directories are used and mail is sent to a mailing list which has an owner- alias. Problem noted by Anne Bennett of Concordia University. Fix class map parsing code if optional key is specified. Problem found by Mario Nigrovic. The SMTP daemon no longer tries to fix up improperly dot-stuffed incoming messages. A leading dot is always stripped by the SMTP receiver regardless of whether or not it is followed by another dot. Problem noted by Jordan Ritter of darkridge.com. Fix corruption when doing automatic MIME 7-bit quoted-printable or base64 encoding to 8-bit text. Problem noted by Mark Elvers. Correct the statistics gathered for total number of connections. Instead of being the exact same number as the total number of messages (T line in mailstats) it now represents the total number of TCP connections. Be more explicit about syntax errors in addresses, especially non-ASCII characters, and properly create DSNs if necessary. Problem noted by Leena Heino of the University of Tampere. Prevent small timeouts from being lost on slow machines if itimers are used. Problem noted by Suresh Ramasubramanian. Prevent a race condition on child cleanup for delivery to files. Problem noted by Fletcher Mattox of the University of Texas. Change the SMTP error code for temporary map failures from 421 to 451. Do not assume that realloc(NULL, size) works on all OS (this was only done in one place: queue group creation). Based on patch by Bryan Costales. Initialize Timeout.iconnect in the code to prevent randomly short timeouts. Problem noted by Bradley Watts of AT&T Canada. Do not try to send a second SMTP QUIT command if the remote responds to a MAIL command with a 421 reply or on I/O errors. By doing so, the host was marked as having a temporary problem and other mail destined for that host was queued for the next queue run. Problem noted by Fletcher Mattox of the University of Texas, Allan E Johannesen of Worcester Polytechnic Institute, Larry Greenfield of CMU, and Neil Rickert of Northern Illinois University. Ignore error replies from the SMTP QUIT command (including servers which drop the connection instead of responding to the command). Portability: Check LDAP_API_VERSION to determine if ldap_memfree() is available. Define HPUX10 when building on HP-UX 10.X. That platform now gets the proper _PATH_SENDMAIL and SMRSH_CMDDIR settings. Patch from Elias Halldor Agustsson of Skyrr. Fix dependency building on Mac OS X and Darwin. Problem noted by John Beck. Preliminary support for the sparc64 port of FreeBSD 5.0. Add /sbin/sh as an acceptable user shell on HP-UX. From Rajesh Somasund of Hewlett-Packard. CONFIG: Add FEATURE(`authinfo') to allow a separate database for SMTP AUTH information. This feature was actually added in 8.12.0 but a release note was not included. CONFIG: Do not bounce mail if FEATURE(`ldap_routing')'s bounce parameter is set and the LDAP lookup returns a temporary error. CONFIG: Honor FEATURE(`relay_hosts_only') when using FEATURE(`relay_mail_from', `domain'). Problem noted by Krzysztof Oledzki. CONFIG: FEATURE(`msp') now disables any type of alias initialization as aliases are not needed for the MSP. CONFIG: Allow users to override RELAY_MAILER_ARGS when FEATURE(`msp') is in use. Patch from Andrzej Filip. CONFIG: FEATURE(`msp') uses `[localhost]' as default instead of `localhost' and turns on MX lookups for the SMTP mailers. This will only have an effect if a parameter is specified, i.e., an MX lookup will be performed on the hostname unless it is embedded in square brackets. Problem noted by Theo Van Dinter of Collective Technologies. CONFIG: Set confTIME_ZONE to USE_TZ in submit.mc (TimeZoneSpec= in submit.cf) to use $TZ for time stamps. This is a compromise to allow for the proper time zone on systems where the default results in misleading time stamps. That is, syslog time stamps and Date headers on submitted mail will use the user's $TZ setting. Problem noted by Mark Roth of the University of Illinois at Urbana-Champaign, solution proposed by Neil Rickert of Northern Illinois University. CONFIG: Mac OS X (Darwin) ships with mail.local as non-set-user-ID binary. Adjust local mailer flags accordingly. Problem noted by John Beck. CONTRIB: Add a warning to qtool.pl to not move queue files around if queue groups are used. CONTRIB: buildvirtuser: Add -f option to force rebuild. CONTRIB: smcontrol.pl: Add -f option to specify control socket. CONTRIB: smcontrol.pl: Add support for 'memdump' command. Suggested by Bryan Costales. DEVTOOLS: Add dependency generation for test programs. LIBMILTER: Remove conversion of port number for the socket structure that is passed to xxfi_connect(). Notice: this fix requires that sendmail and libmilter both have this change; mixing versions may lead to wrong port values depending on the endianness of the involved systems. Problem noted by Gisle Aas of ActiveState. LIBMILTER: If smfi_setreply() sets a custom reply code of '4XX' but SMFI_REJECT is returned, ignore the custom reply. Do the same if '5XX' is used and SMFI_TEMPFAIL is returned. LIBMILTER: Install include files in ${INCLUDEDIR}/libmilter/ as required by mfapi.h. Problem noted by Jose Marcio Martins da Cruz of Ecole Nationale Superieure des Mines de Paris. LIBSM: Add SM_CONF_LDAP_MEMFREE as a configuration define. Set this to 1 if your LDAP client libraries include ldap_memfree(). LIBSMDB: Avoid a file creation race condition for Berkeley DB 1.X and NDBM on systems with the O_EXLOCK open(2) flag. SMRSH: Fix compilation problem on some operating systems. Problem noted by Christian Krackowizer of schuler technodat GmbH. VACATION: Allow root to operate on user vacation databases. Based on patch from Greg Couch of the University of California, San Francisco. VACATION: Don't ignore -C option. Based on patch by Bryan Costales. VACATION: Clarify option usage in the man page. Problem noted by Joe Barbish. New Files: libmilter/docs/smfi_setbacklog.html 8.12.2/8.12.2 2002/01/13 Don't complain too much if stdin, stdout, or stderr are missing at startup, only log an error message. Fix potential problem if an unknown operation mode (character following -b) has been specified. Prevent purgestat from looping even if someone changes the permissions or owner of hoststatus files. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Properly record dropped connections in persistent host status. Problem noted by Ulrich Windl of the Universitat Regensburg. Remove newlines from recipients read via sendmail -t to prevent SMTP protocol errors when sending the RCPT command. Problem noted by William D. Colburn of the New Mexico Institute of Mining and Technology. Only log milter body replacements once instead of for each body chunk sent by a filter. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. In 8.12.0 and 8.12.1, the headers were mistakenly not included in the message size calculation. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Since 8.12 no longer forks at the SMTP MAIL command, the daemon needs to collect children status to avoid zombie processes. Problem noted by Chris Adams of HiWAAY Informations Services. Shut down "nullserver" and ETRN-only connections after 25 bad commands are issued. This makes it consistent with normal SMTP connections. Avoid duplicate logging of milter rejections. Problem noted by William D. Colburn of the New Mexico Institute of Mining and Technology. Error and delay DSNs were being sent to postmaster instead of the message sender if the sender had used a deprecated RFC822 source route. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Fix FallbackMXhost behavior for temporary errors during address parsing. Problem noted by Jorg Bielak from Coastal Web Online. For systems on which stat(2) does not return a value for st_blksize that is the "optimal blocksize for I/O" three new compile time flags are available: SM_IO_MAX_BUF_FILE, SM_IO_MIN_BUF, and SM_IO_MAX_BUF, which define an upper limit for regular files, and a lower and upper limit for other file types, respectively. Fix a potential deadlock if two events are supposed to occur at exactly the same time. Problem noted by Valdis Kletnieks of Virginia Tech. Perform envelope splitting for aliases listed directly in the alias file, not just for include/.forward files. Problem noted by John Beck of Sun Microsystems. Allow selection of queue group for mailq using -qGgroup. Based on patch by John Beck of Sun Microsystems. Make sure cached LDAP connections used my multiple maps in the same process are closed. Patch from Taso N. Devetzis. If running as root, allow reading of class files in protected directories. Patch from Alexander Talos of the University of Vienna. Correct a few LDAP related memory leaks. Patch from David Powell of Sun Microsystems. Allow specification of an empty realm via the authinfo ruleset. This is necessary to interoperate as an SMTP AUTH client with servers that do not support realms when using CRAM-MD5. Problem noted by Bjoern Voigt of TU Berlin. Avoid a potential information leak if AUTH PLAIN is used and the server gets stuck while processing that command. Problem noted by Chris Adams from HiWAAY Informations Services. In addition to printing errors when parsing recipients during command line invocations log them to make it simpler to understand possible DSNs to postmaster. Do not use FallbackMXhost on mailers which have the F=0 flag set. Allow local mailers (F=l) to specify a host for TCP connections instead of forcing localhost. Obey ${DESTDIR} for installation of the client mail queue and submit.cf. Patch from Peter 'Luna' Runestig. Re-enable support for -M option which was broken in 8.12.1. Problem noted by Neil Rickert of Northern Illinois University. If a remote server violates the SMTP standard by unexpectedly dropping the connection during an SMTP transaction, stop sending commands. This prevents bogus "Bad file number" recipient status. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Do not use a size estimate of 100 for postmaster bounces, it's almost always too small; do not guess the size at all. New VENDOR_DEC for Compaq/DEC. Requested by James Seagraves of Compaq Computer Corp. Fix DaemonPortOptions IPv6 address parsing such that ::1 works properly. Problem noted by Valdis Kletnieks of Virginia Tech. Portability: Fix IPv6 network interface probing on HP-UX 11.X. Based on patch provided by HP. Mac OS X (aka Darwin) has a broken setreuid() call, but a working seteuid() call. From Daniel J. Luke. Use proper type for a 32-bit integer on SINIX. From Ganu Sachin of Siemens. Set SM_IO_MIN_BUF (4K) and SM_IO_MAX_BUF (8K) for HP-UX. Reduce optimization from +O3 to +O2 on HP-UX 11. This fixes a problem that caused additional bogus characters to be written to the qf file. Problem noted by Tapani Tarvainen. Set LDA_USE_LOCKF by default for UnixWare. Problem noted by Boyd Lynn Gerber. Add support for HP MPE/iX. See sendmail/README for port information. From Mark Bixby of Hewlett-Packard. New portability defines HASNICE, HASRRESVPORT, USE_ENVIRON, USE_DOUBLE_FORK, and NEEDLINK. See sendmail/README for more information. From Mark Bixby of Hewlett-Packard. If an OS doesn't have a method of finding free disk space (SFS_NONE), lie and say there is plenty of space. From Mark Bixby of Hewlett-Packard. Add support for AIX 5.1. From Valdis Kletnieks of Virginia Tech. Fix man page location for NeXTSTEP. From Hisanori Gogota of the NTT/InterCommunication Center. Do not assume that strerror() always returns a string. Problem noted by John Beck of Sun Microsystems. CONFIG: Add OSTYPE(freebsd5) for FreeBSD 5.X, which has removed UUCP from the base operating system. From Mark Murray of FreeBSD Services, Ltd. CONFIG: Add OSTYPE(mpeix) and a generic .mc file for HP MPE/iX systems. From Mark Bixby of Hewlett-Packard. CONFIG: Add support for selecting a queue group for all mailers. Based on proposal by Stephen L. Ulmer of the University of Florida. CONFIG: Fix error reporting for compat_check.m4. Problem noted by Altin Waldmann. CONFIG: Do not override user selections for confRUN_AS_USER and confTRUSTED_USER in FEATURE(msp). From Mark Bixby of Hewlett-Packard. LIBMILTER: Fix bug that prevented the removal of a socket after libmilter terminated. Problem reported by Andrey V. Pevnev of MSFU. LIBMILTER: Fix configuration error that required libsm for linking. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. LIBMILTER: Portability fix for OpenUNIX. Patch from Larry Rosenman. LIBMILTER: Fix a theoretical memory leak and a possible attempt to free memory twice. LIBSM: Fix a potential segmentation violation in the I/O library. Problem found and analyzed by John Beck and Tim Haley of Sun Microsystems. LIBSM: Do not clear the LDAP configuration information when terminating the mailbox database connection in the LDAP example code. Problem noted by Nikos Voutsinas of the University of Athens. New Files: cf/cf/generic-mpeix.cf cf/cf/generic-mpeix.mc cf/ostype/freebsd5.m4 cf/ostype/mpeix.m4 devtools/OS/AIX.5.1 devtools/OS/MPE-iX include/sm/os/sm_os_mpeix.h libsm/mpeix.c 8.12.1/8.12.1 2001/10/01 SECURITY: Check whether dropping group privileges actually succeeded to avoid possible compromises of the mail system by supplying bogus data. Add configuration options for different set*gid() calls to reset saved gid. Problem found by Michal Zalewski. PRIVACY: Prevent information leakage when sendmail has extra privileges by disabling debugging (command line -d flag) during queue runs and disabling ETRN when sendmail -bs is used. Suggested by Michal Zalewski. Avoid memory corruption problems resulting from bogus .cf files. Problem found by Michal Zalewski. Set the ${server_addr} macro to name of mailer when doing LMTP delivery. LMTP systems may offer SMTP Authentication or STARTTLS causing sendmail to use this macro in rulesets. If debugging is turned on (-d0.10) print not just the default values for configuration file and pid file but also the selected values. Problem noted by Brad Chapman. Continue dealing with broken nameservers by ignoring SERVFAIL errors returned on T_AAAA (IPv6) lookups at delivery time if ResolverOptions=WorkAroundBrokenAAAA is set. Previously this only applied to hostname canonification. Problem noted by Bill Fenner of AT&T Research. Ignore comments in NIS host records when trying to find the canonical name for a host. When sendmail has extra privileges, limit mail submission command line flags (i.e., -G, -h, -F, etc.) to mail submission operating modes (i.e., -bm, -bs, -bv, etc.). Idea based on suggestion from Michal Zalewski. Portability: AIX: Use `oslevel` if available to determine OS version. `uname` does not given complete information. Problem noted by Keith Neufeld of the Cessna Aircraft Company. OpenUNIX: Use lockf() for LDA delivery (affects mail.local). Problem noticed by Boyd Lynn Gerber of ZENEX. Avoid compiler warnings by not using pointers to pass integers. Problem noted by Todd C. Miller of Courtesan Consulting. CONFIG: Add restrictqrun to PrivacyOptions for the MSP to minimize problems with potential misconfigurations. CONFIG: Fix comment showing default value of MaxHopCount. Problem noted by Greg Robinson of the Defence Science and Technology Organisation of Australia. CONFIG: dnsbl: If an argument specifies an error message in case of temporary lookup failures for DNS based blacklists then use it. LIBMILTER: Install mfdef.h, required by mfapi.h. Problem noted by Richard A. Nelson of Debian. LIBMILTER: Add __P definition for OS that lack it. Problem noted by Chris Adams from HiWAAY Informations Services. LIBSMDB: Fix a lock race condition that affects makemap, praliases, and vacation. MAKEMAP: Avoid going beyond the end of an input line if it does not contain a value for a key. Based on patch from Mark Bixby from Hewlett-Packard. New Files: test/Build test/Makefile test/Makefile.m4 test/README test/t_dropgid.c test/t_setgid.c Deleted Files: include/sm/stdio.h include/sm/sysstat.h 8.12.0/8.12.0 2001/09/08 *NOTICE*: The default installation of sendmail does not use set-user-ID root anymore. You need to create a new user and a new group before installing sendmail (both called smmsp by default). The installation process tries to install /etc/mail/submit.cf and creates /var/spool/clientmqueue by default. Please see sendmail/SECURITY for details. SECURITY: Check for group and world writable forward and :include: files. These checks can be turned off if absolutely necessary using the DontBlameSendmail option and the new flags: GroupWritableForwardFile WorldWritableForwardFile GroupWritableIncludeFile WorldWritableIncludeFile Problem noted by Slawek Zak of Politechnika Warszawska, SECURITY: Drop privileges when using address test mode. Suggested by Michal Zalewski of the "Internet for Schools" project (IdS). Fixed problem of a global variable being used for a timeout jump point where the variable could become overused for more than one timeout concurrently. This erroneous behavior resulted in a corrupted stack causing a core dump. The timeout is now handled via libsm. Problem noted by Michael Shapiro, John Beck, and Carl Smith of Sun Microsystems. If sendmail is set-group-ID then that group ID is used for permission checks (group ID of RunAsUser). This allows use of a set-group-ID sendmail binary for initial message submission and no set-user-ID root sendmail is needed. For details see sendmail/SECURITY. Log a warning if a non-trusted user changes the syslog label. Based on notice from Bryan Costales of SL3D, Inc. If sendmail is called for initial delivery, try to use submit.cf with a fallback of sendmail.cf as configuration file. See sendmail/SECURITY. New configuration file option UseMSP to allow group writable queue files if the group is the same as that of a set-group-ID sendmail binary. See sendmail/SECURITY. The .cf file is chosen based on the operation mode. For -bm (default), -bs, and -t it is submit.cf if it exists for all others it is sendmail.cf (to be backward compatible). This selection can be changed by the new option -Ac or -Am (alternative .cf file: client or mta). See sendmail/SECURITY. The SMTP server no longer forks on each MAIL command. The ONEX command has been removed. Implement SMTP PIPELINING per RFC 2920. It can be turned off at compile time or per host (ruleset). New option MailboxDatabase specifies the type of mailbox database used to look up local mail recipients; the default value is "pw", which means to use getpwnam(). New mailbox database types can be added by adding custom code to libsm/mbdb.c. Queue file names are now 15 characters long, rather than 14 characters long, to accomodate envelope splitting. File systems with a 14 character file name length limit are no longer supported. Recipient list used for delivery now gets internally ordered by hostsignature (character string version of MX RR). This orders recipients for the same MX RR's together meaning smaller portions of the list need to be scanned (instead of the whole list) each delivery() pass to determine piggybacking. The significance of the change is better the larger the recipient list. Hostsignature is now created during recipient list creation rather than just before delivery. Enhancements for more opportunistic piggybacking. Previous piggybacking (called coincidental) extended to coattail piggybacking. Rather than complete MX RR matching (coincidental) piggybacking is done if just the lowest value preference matches (coattail). If sendmail receives a temporary error on a RCPT TO: command, it will try other MX hosts if available. DefaultAuthInfo can contain a list of mechanisms to be used for outgoing (client-side) SMTP Authentication. New modifier 'A' for DaemonPortOptions/ClientPortOptions to disable AUTH (overrides 'a' modifier in DaemonPortOptions). Based on patch from Lyndon Nerenberg of Messaging Direct. Enable AUTH mechanism EXTERNAL if STARTTLS is used. A new ruleset authinfo can be used to return client side authentication information for AUTH instead of DefaultAuthInfo. Therefore the DefaultAuthInfo option is deprecated and will be removed in future versions. Accept any SMTP continuation code 3xy for AUTH even though RFC 2554 requires 334. Mercury 1.48 is a known offender. Add new option AuthMaxBits to limit the overall encryption strength for the security layer in SMTP AUTH (SASL). See doc/op/op.me for details. Introduce new STARTTLS related macros {cn_issuer}, {cn_subject}, {cert_md5} which hold the CN (common name) of the CA that signed the presented certificate, the CN and the MD5 hash of the presented certificate, respectively. New ruleset try_tls to decide whether to try (as client) STARTTLS. New ruleset srv_features to enable/disable certain features in the server per connection. See doc/op/op.me for details. New ruleset tls_rcpt to decide whether to send e-mail to a particular recipient; useful to decide whether a conection is secure enough on a per recipient basis. New option TLSSrvOptions to modify some aspects of the server for STARTTLS. If no certificate has been requested, the macro {verify} has the value "NOT". New M=S modifier for ClientPortOptions/DaemonPortOptions to turn off using/offering STARTTLS when delivering/receiving e-mail. Macro expand filenames/directories for certs and keys in the .cf file. Proposed by Neil Rickert of Northern Illinois University. Generate an ephemeral RSA key for a STARTTLS connection only if really required. This change results in a noticable performance gains on most machines. Moreover, if shared memory is in use, reuse the key several times. Add queue groups which can be used to group queue directories with the same behavior together. See doc/op/op.me for details. If the new option FastSplit (defaults to one) has a value greater than zero, it suppresses the MX lookups on addresses when they are initially sorted which may result in faster envelope splitting. If the mail is submitted directly from the command line, then the value also limits the number of processes to deliver the envelopes; if more envelopes are created they are only queued up and must be taken care of by a queue run. The check for 'enough disk space' now pays attention to which file system each queue directory resides in. All queue runners can be cleanly terminated via SIGTERM to parent. New option QueueFileMode for the default permissions of queue files. Add parallel queue runner code. Allows multiple queue runners per work group (one or more queues in a multi-queue environment collected together) to process the same work list at the same time. Option MaxQueueChildren added to limit the number of concurrently active queue runner processes. New option MaxRunnersPerQueue to specify the maximum number of queue runners per queue group. Queue member selection by substring pattern matching now allows the pattern to be negated. For -qI, -qR and -qS it is permissible for -q!I, -q!R and -q!S to mean remove members of the queue that match during processing. New -qp[time] option is similar to -qtime, except that instead of periodically forking a child to process the queue, a single child is forked for each queue that sleeps between queue runs. A SIGHUP signal can be sent to restart this persistent queue runner. The SIGHUP signal now restarts a timed queue run process (i.e., a sendmail process which only runs the queue at an interval: sendmail -q15m). New option NiceQueueRun to set the priority of queue runners. Proposed by Thom O'Connor. sendmail will run the queue(s) in the background when invoked with -q unless the new -qf option or -v is used. QueueSortOrder=Random sorts the queue randomly, which is useful if several queue runners are started by hand to avoid contention. QueueSortOrder=Modification sorts the queue by the modification time of the qf file (older entries first). Support Deliver By SMTP Service Extension (RFC 2852) which allows a client to specify an amount of time within which an e-mail should be delivered. New option DeliverByMin added to set the minimum amount of time or disable the extension. Non-printable characters (ASCII: 0-31, 127) in mailbox addresses are not allowed unless escaped or quoted. Add support for a generic DNS map. Based on a patch contributed by Leif Johansson of Stockholm University, which was based on work by Assar Westerlund of Swedish Institute of Computer Science, Kista, and Johan Danielsson of Royal Institute of Technology, Stockholm, Sweden. MX records will be looked up for FallBackMXhost. To use the old behavior (no MX lookups), put the name in square brackets. Proposed by Thom O'Connor. Use shared memory to store free space of filesystems that are used for queues, if shared memory is available and if a key is set via SharedMemoryKey. This minimizes the number of system calls to check the available space. See doc/op/op.me for details. If shared memory is compiled in the option -bP can be used to print the number of entries in the queue(s). Enable generic mail filter API (milter). See libmilter/README and the usual documentation for details. Remove AutoRebuildAliases option, deprecated since 8.10. Remove '-U' (initial user submission) command line option as announced in 8.10. Remove support for non-standard SMTP command XUSR. Use an MSA instead. New macro {addr_type} which contains whether the current address is an envelope sender or recipient address. Suggested by Neil Rickert of Northern Illinois University. Two new options for host maps: -d (retransmission timeout), -r (number of retries). New option for LDAP maps: the -V allows you to specify a separator such that a lookup can return both an attribute and value separated by the given separator. Add new operators '%', '|', '&' (modulo, binary or, binary and) to map class arith. If DoubleBounceAddress expands to an empty string, ``double bounces'' (errors that occur when sending an error message) are dropped. New DontBlameSendmail options GroupReadableSASLDBFile and GroupWritableSASLDBFile to relax requirements for sasldb files. New DontBlameSendmail options GroupReadableKeyFile to relax requirements for files containing secret keys. This is necessary for the MSP if client authentification is used. Properly handle quoted filenames for class files (to allow for filenames with spaces). Honor the resolver option RES_NOALIASES when canonifying hostnames. Add macros to avoid the reuse of {if_addr} etc: {if_name_out} hostname of interface of outgoing connection. {if_addr_out} address of interface of outgoing connection. {if_family_out} family of interface of outgoing connection. The latter two are only set if the interface does not belong to the loopback net. Add macro {nrcpts} which holds the number of (validated) recipients. DialDelay option applies only to mailers with flag 'Z'. Patch from Juergen Georgi of RUS University of Stuttgart. New Timeout.lhlo,auth,starttls options to limit the time waiting for an answer to the LMTP LHLO, SMTP AUTH or STARTTLS command. New Timeout.aconnect option to limit the overall waiting time for all connections for a single delivery attempt to succeed. Limit the rate recipients in the SMTP envelope are accepted once a threshold number of recipients has been rejected (option BadRcptThrottle). From Gregory A Lundberg of the WU-FTPD Development Group. New option DelayLA to delay connections if the load averages exceeds the specified value. The default of 0 does not change the previous behavior. A value greater than 0 will cause sendmail to sleep for one second on most SMTP commands and before accepting connections if that load average is exceeded. Use a dynamic (instead of fixed-size) buffer for the list of recipients that are sent during a connection to a mailer. This also introduces a new mailer field 'r' which defines the maximum number of recipients (defaults to 100). Based on patch by Motonori Nakamura of Kyoto University. Add new F=1 mailer flag to disable sending of null characters ('\0'). Add new F=2 mailer flag to disable use of ESMTP, using SMTP instead. The deprecated [TCP] builtin mailer pathname (P=) is gone. Use [IPC] instead. IPC is no longer available as first mailer argument (A=) for [IPC] builtin mailer pathnames. Use TCP instead. PH map code updated to use the new libphclient API instead of the old libqiapi library. Contributed by Mark Roth of the University of Illinois at Urbana-Champaign. New option DirectSubmissionModifiers to define {daemon_flags} for direct (command line) submissions. New M=O modifier for DaemonPortOptions to ignore the socket in case of failures. Based on patch by Jun-ichiro itojun Hagino of the KAME Project. Add Disposition-Notification-To: (RFC 2298) to the list of headers whose content is rewritten similar to Reply-To:. Proposed by Andrzej Filip. Use STARTTLS/AUTH=server/client for logging incoming/outgoing STARTTLS/AUTH connections; log incoming connections at level 9 or higher. Use AUTH/STARTTLS instead of SASL/TLS for SMTP AUTH/STARTTLS related logfile entries. Convert unprintable characters (and backslash) into octal or C format before logging. Log recipients if no message is transferred but QUIT/RSET is given (at LogLevel 9/10 or higher). Log discarded recipients at LogLevel 10 or higher. Do not log "did not issue MAIL/EXPN/VRFY/ETRN" for connections in which most commands are rejected due to check_relay or TCP Wrappers if the host tries one of those commands anyway. Change logging format for cloned envelopes to be similar to that for DSNs ("old id: new id: clone"). Suggested by Ulrich Windl of the Universitat Regensburg. Added libsm, a C library of general purpose abstractions including assertions, tracing and debugging with named debug categories, exception handling, malloc debugging, resource pools, portability abstractions, and an extensible buffered I/O package. It will at some point replace libsmutil. See libsm/index.html for details. Fixed most memory leaks in sendmail which were previously taken care of by fork() and exit(). Use new sm_io*() functions in place of stdio calls. Allows for more consistent portablity amongst different platforms new and old (from new libsm). Common I/O pkg means just one buffering method needed instead of two ('bf_portable' and 'bf_torek' now just 'bf'). Sfio no longer needed as SASL/TLS code uses sm_io*() API's. New possible value 'interactive' for SuperSafe which can be used together with DeliveryMode=interactive is to avoid some disk synchronizations calls. Add per-recipient status information to mailq -v output. T_ANY queries are no longer used by sendmail. When compiling with "gcc -O -Wall" specify "-DSM_OMIT_BOGUS_WARNINGS" too (see include/sm/cdefs.h for more info). sendmail -d now has general support for named debug categories. See libsm/debug.html and section 3.4 of doc/op/op.me for details. Eliminate the "postmaster warning" DSNs on address parsing errors such as unbalanced angle brackets or parentheses. The DSNs generated by this condition were illegal (not RFC conform). Problem noted by Ulrich Windl of the Universitaet Regensburg. Do not issue a DSN if the ruleset localaddr resolves to the $#error mailer and the recipient has hence been rejected during the SMTP dialogue. Problem reported by Larry Greenfield of CMU. Deal with a case of multiple deliveries on misconfigured systems that do not have postmaster defined. If an email was sent from an address to which a DSN cannot be returned and in which at least one recipient address is non-deliverable, then that email had been delivered in each queue run. Problem reported by Matteo HCE Valsasna of Universita degli Studi dell'Insubria. The compilation options SMTP, DAEMON, and QUEUE have been removed, i.e., the corresponding code is always compiled in now. Log the command line in daemon/queue-run mode at LogLevel 10 and higher. Suggested by Robert Harker of Harker Systems. New ResolverOptions setting: WorkAroundBrokenAAAA. When attempting to canonify a hostname, some broken nameservers will return SERVFAIL (a temporary failure) on T_AAAA (IPv6) lookups. If you want to excuse this behavior, use this new flag. Suggested by Chris Foote of SE Network Access and Mark Roth of the University of Illinois at Urbana-Champaign. Free the memory allocated by getipnodeby{addr,name}(). Problem noted by Joy Latten of IBM. ConnectionRateThrottle limits the number of connections per second to each daemon individually, not the overall number of connections. Specifying only "ldap:" as an AliasFile specification will force sendmail to use a default alias schema as outlined in the ``USING LDAP FOR ALIASES, MAPS, and CLASSES'' section of cf/README. Add a new syntax for the 'F' (file class) sendmail.cf command. If the first character after the class name is not a '/' or a '|' and it contains an '@' (e.g., F{X}key@class:spec), the rest of the line will be parsed as a map lookup. This allows classes to be filled via a map lookup. See op.me for more syntax information. Specifically, this can be used for commands such as VIRTUSER_DOMAIN_FILE() to read the list of domains via LDAP (see the ``USING LDAP FOR ALIASES, MAPS, and CLASSES'' section of cf/README for an example). The new macro ${sendmailMTACluster} determines the LDAP cluster for the default schema used in the above two items. Unless DontBlameSendmail=RunProgramInUnsafeDirPath is set, log a warning if a program being run from a mailer or file class (e.g., F|/path/to/prog) is in an unsafe directory path. Unless DontBlameSendmail=RunWritableProgram is set, log a warning if a program being run from a mailer or file class (e.g., F|/path/to/prog) is group or world writable. Loopback interfaces (e.g., "lo0") are now probed for class {w} hostnames. Setting DontProbeInterfaces to "loopback" (without quotes) will disable this and return to the pre-8.12 behavior of only probing non-loopback interfaces. Suggested by Bryan Stansell of GNAC. In accordance with RFC 2821 section 4.1.4, accept multiple HELO/EHLO commands. Multiple ClientPortOptions settings are now allowed, one for each possible protocol family which may be used for outgoing connections. Restrictions placed on one family only affect outgoing connections on that particular family. Because of this change, the ${client_flags} macro is not set until the connection is established. Based on patch from Motonori Nakamura of Kyoto University. PrivacyOptions=restrictexpand instructs sendmail to drop privileges when the -bv option is given by users who are neither root nor the TrustedUser so users can not read private aliases, forwards, or :include: files. It also will override the -v (verbose) command line option. If the M=b modifier is set in DaemonPortOptions and the interface address can't be used for the outgoing connection, fall back to the settings in ClientPortOptions (if set). Problem noted by John Beck of Sun Microsystems. New named config file rule check_data for DATA command (input: number of recipients). Based on patch from Mark Roth of the University of Illinois at Urbana-Champaign. Add support for ETRN queue selection per RFC 1985. The queue group can be specified using the '#' option character. For example, 'ETRN #queuegroup'. If an LDAP server times out or becomes unavailable, close the current connection and reopen to get to one of the fallback servers. Patch from Paul Hilchey of the University of British Columbia. Make default error number on $#error messages 550 instead of 501 because 501 is not allowed on all commands. The .cf file option UnsafeGroupWrites is deprecated, it should be replaced with the settings GroupWritableForwardFileSafe and GroupWritableIncludeFileSafe in DontBlameSendmail if required. The deprecated ldapx map class has been removed. Use the ldap map class instead. Any IPv6 addresses used in configuration should be prefixed by the "IPv6:" tag to identify the address properly. For example, if you want to add the IPv6 address [2002:c0a8:51d2::23f4] to class {w}, you would need to add [IPv6:2002:c0a8:51d2::23f4]. Change the $&{opMode} macro if the operation mode changes while the MTA is running. For example, during a queue run. Add "use_inet6" as a new ResolverOptions flag to control the RES_USE_INET6 resolver option. Based on patch from Rick Nelson of IBM. The maximum number of commands before the MTA slows down when too many "light weight" commands have been received are now configurable during compile time. The current values and their defaults are: MAXBADCOMMANDS 25 unknown commands MAXNOOPCOMMANDS 20 NOOP, VERB, ONEX, XUSR MAXHELOCOMMANDS 3 HELO, EHLO MAXVRFYCOMMANDS 6 VRFY, EXPN MAXETRNCOMMANDS 8 ETRN Setting a value to 0 disables the check. Patch from Bryan Costales of SL3D, Inc. The header syntax H?${MyMacro}?X-My-Header: now not only checks if ${MyMacro} is defined but also that it is not empty. Properly quote usernames with special characters if they are used in headers. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Be sure to include the proper Final-Recipient: DSN header in bounce messages for messages for mailing list expanded addresses which are not delivered on the initial attempt. Do not treat errors as sticky when doing delivery via LMTP after the final dot has been sent to avoid affecting future deliveries. Problem reported by Larry Greenfield of CMU. New compile time flag REQUIRES_DIR_FSYNC which turns on support for file systems that require to call fsync() for a directory if the meta-data in it has been changed. This should be set at least for ReiserFS; it is enabled by default for Linux. See sendmail/README for further information. Avoid file locking deadlock when updating the statistics file if sendmail is signaled to terminate. Problem noted by Christophe Wolfhugel of France Telecom. Set the $c macro (hop count) as it is being set instead of when the envelope is initialized. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Properly count recipients for DeliveryMode defer and queue. Fix from Peter A. Friend of EarthLink. Treat invalid hesiod lookups as permanent errors instead of temporary errors. Problem noted by Russell McOrmond of flora.ca. Portability: Remove support for AIX 2, which supports only 14 character filenames and is outdated anyway. Suggested by Valdis Kletnieks of Virginia Tech. Change several settings for Irix 6: remove confSBINDIR, i.e., use default /usr/sbin, change owner/group of man pages and user-executable to root/sys, set optimization limit to 0 (unlimited). Based on patch from Ayamura Kikuchi, M.D, and proposal from Kari Hurtta of the Finnish Meteorological Institute. Do not assume LDAP support is installed by default under Solaris 8 and later. Add support for OpenUNIX. CONFIG: Increment version number of config file to 10. CONFIG: Add an install target and a README file in cf/cf. CONFIG: Don't accept addresses of the form a@b@, a@b@c, a@[b]c, etc. CONFIG: Reject empty recipient addresses (in check_rcpt). CONFIG: The access map uses an option of -T to deal with temporary lookup failures. CONFIG: New value for access map: SKIP, which causes the default action to be taken by aborting the search for domain names or IP nets. CONFIG: check_rcpt can deal with TEMPFAIL for either recipient or relay address as long as the other part allows the email to get through. CONFIG: Entries for virtusertable can make use of a third parameter "%3" which contains "+detail" of a wildcard match, i.e., an entry like user+*@domain. This allows handling of details by using %1%3 as the RHS. Additionally, a "+" wildcard has been introduced to match only non-empty details of addresses. CONFIG: Numbers for rulesets used by MAILERs have been removed and hence there is no required order within the MAILER section anymore except for MAILER(`uucp') which must come after MAILER(`smtp') if uucp-dom and uucp-uudom are used. CONFIG: Hosts listed in the generics domain class {G} (GENERICS_DOMAIN() and GENERICS_DOMAIN_FILE()) are treated as canonical. Suggested by Per Hedeland of Ericsson. CONFIG: If FEATURE(`delay_checks') is used, make sure that a lookup in the access map which returns OK or RELAY actually terminates check_* ruleset checking. CONFIG: New tag TLS_Rcpt: for access map to be used by ruleset tls_rcpt, see cf/README for details. CONFIG: Change format of Received: header line which reveals whether STARTTLS has been used to "(version=${tls_version} cipher=${cipher} bits=${cipher_bits} verify=${verify})". CONFIG: Use "Spam:" as tag for lookups for FEATURE(`delay_checks') options friends/haters instead of "To:" and enable specification of whole domains instead of just users. Notice: this change is not backward compatible. Suggested by Chris Adams from HiWAAY Informations Services. CONFIG: Allow for local extensions for most new rulesets, see cf/README for details. CONFIG: New FEATURE(`lookupdotdomain') to lookup also .domain in the access map. Proposed by Randall Winchester of the University of Maryland. CONFIG: New FEATURE(`local_no_masquerade') to avoid masquerading for the local mailer. Proposed by Ingo Brueckl of Wupper Online. CONFIG: confRELAY_MSG/confREJECT_MSG can override the default messages for an unauthorized relaying attempt/for access map entries with RHS REJECT, respectively. CONFIG: FEATURE(`always_add_domain') takes an optional argument to specify another domain to be added instead of the local one. Suggested by Richard H. Gumpertz of Computer Problem Solving. CONFIG: confAUTH_OPTIONS allows setting of Cyrus-SASL specific options, see doc/op/op.me for details. CONFIG: confAUTH_MAX_BITS sets the maximum encryption strength for the security layer in SMTP AUTH (SASL). CONFIG: If Local_localaddr resolves to $#ok, localaddr is terminated immediately. CONFIG: FEATURE(`enhdnsbl') is an enhanced version of dnsbl which allows checking of the return values of the DNS lookups. See cf/README for details. CONFIG: FEATURE(`dnsbl') allows now to specify the behavior for temporary lookup failures. CONFIG: New option confDELIVER_BY_MIN to specify minimum time for Deliver By (RFC 2852) or to turn off the extension. CONFIG: New option confSHARED_MEMORY_KEY to set the key for shared memory use. CONFIG: New FEATURE(`compat_check') to look up a key consisting of the sender and the recipient address delimited by the string "<@>", e.g., sender@sdomain<@>recipient@rdomain, in the access map. Based on code contributed by Mathias Koerber of Singapore Telecommunications Ltd. CONFIG: Add EXPOSED_USER_FILE() command to allow an exposed user file. Suggested by John Beck of Sun Microsystems. CONFIG: Don't use MAILER-DAEMON for error messages delivered via LMTP. Problem reported by Larry Greenfield of CMU. CONFIG: New FEATURE(`preserve_luser_host') to preserve the name of the recipient host if LUSER_RELAY is used. CONFIG: New FEATURE(`preserve_local_plus_detail') to preserve the +detail portion of the address when passing address to local delivery agent. Disables alias and .forward +detail stripping. Only use if LDA supports this. CONFIG: Removed deprecated FEATURE(`rbl'). CONFIG: Add LDAPROUTE_EQUIVALENT() and LDAPROUTE_EQUIVALENT_FILE() which allow you to specify 'equivalent' hosts for LDAP Routing lookups. Equivalent hostnames are replaced by the masquerade domain name for lookups. See cf/README for additional details. CONFIG: Add a fourth argument to FEATURE(`ldap_routing') which instructs the rulesets on what to do if the address being looked up has +detail information. See cf/README for more information. CONFIG: When chosing a new destination via LDAP Routing, also look up the new routing address/host in the mailertable. Based on patch from Don Badrak of the United States Census Bureau. CONFIG: Do not reject the SMTP Mail from: command if LDAP Routing is in use and the bounce option is enabled. Only reject recipients as user unknown. CONFIG: Provide LDAP support for the remaining database map features. See the ``USING LDAP FOR ALIASES AND MAPS'' section of cf/README for more information. CONFIG: Add confLDAP_CLUSTER which defines the ${sendmailMTACluster} macro used for LDAP searches as described above in ``USING LDAP FOR ALIASES, MAPS, AND CLASSES''. CONFIG: confCLIENT_OPTIONS has been replaced by CLIENT_OPTIONS(), which takes the options as argument and can be used multiple times; see cf/README for details. CONFIG: Add configuration macros for new options: confBAD_RCPT_THROTTLE BadRcptThrottle confDIRECT_SUBMISSION_MODIFIERS DirectSubmissionModifiers confMAILBOX_DATABASE MailboxDatabase confMAX_QUEUE_CHILDREN MaxQueueChildren confMAX_RUNNERS_PER_QUEUE MaxRunnersPerQueue confNICE_QUEUE_RUN NiceQueueRun confQUEUE_FILE_MODE QueueFileMode confFAST_SPLIT FastSplit confTLS_SRV_OPTIONS TLSSrvOptions See above (and related documentation) for further information. CONFIG: Add configuration variables for new timeout options: confTO_ACONNECT Timeout.aconnect confTO_AUTH Timeout.auth confTO_LHLO Timeout.lhlo confTO_STARTTLS Timeout.starttls CONFIG: Add configuration macros for mail filter API: confINPUT_MAIL_FILTERS InputMailFilters confMILTER_LOG_LEVEL Milter.LogLevel confMILTER_MACROS_CONNECT Milter.macros.connect confMILTER_MACROS_HELO Milter.macros.helo confMILTER_MACROS_ENVFROM Milter.macros.envfrom confMILTER_MACROS_ENVRCPT Milter.macros.envrcpt Mail filters can be defined via INPUT_MAIL_FILTER() and MAIL_FILTER(). See libmilter/README, cf/README, and doc/op/op.me for details. CONFIG: Add support for accepting temporarily unresolvable domains. See cf/README for details. Based on patch by Motonori Nakamura of Kyoto University. CONFIG: confDEQUOTE_OPTS can be used to specify options for the dequote map. CONFIG: New macro QUEUE_GROUP() to define queue groups. CONFIG: New FEATURE(`queuegroup') to select a queue group based on the full e-mail address or the domain of the recipient. CONFIG: Any IPv6 addresses used in configuration should be prefixed by the "IPv6:" tag to identify the address properly. For example, if you want to use the IPv6 address 2002:c0a8:51d2::23f4 in the access database, you would need to use IPv6:2002:c0a8:51d2::23f4 on the left hand side. This affects the access database as well as the relay-domains and local-host-names files. CONFIG: OSTYPE(aux) has been renamed to OSTYPE(a-ux). CONFIG: Avoid expansion of m4 keywords in SMART_HOST. CONFIG: Add MASQUERADE_EXCEPTION_FILE() for reading masquerading exceptions from a file. Suggested by Trey Breckenridge of Mississippi State University. CONFIG: Add LOCAL_USER_FILE() for reading local users (LOCAL_USER() -- $={L}) entries from a file. CONTRIB: dnsblaccess.m4 is a further enhanced version of enhdnsbl.m4 which allows to lookup error codes in the access map. Contributed by Neil Rickert of Northern Illinois University. DEVTOOLS: Add new options for installation of include and library files: confINCGRP, confINCMODE, confINCOWN, confLIBGRP, confLIBMODE, confLIBOWN. DEVTOOLS: Add new option confDONT_INSTALL_CATMAN to turn off installation of the the formatted man pages on operating systems which don't include cat directories. EDITMAP: New program for editing maps as supplement to makemap. MAIL.LOCAL: Mail.local now uses the libsm mbdb package to look up local mail recipients. New option -D mbdb specifies the mailbox database type. MAIL.LOCAL: New option "-h filename" which instructs mail.local to deliver the mail to the named file in the user's home directory instead of the system mail spool area. Based on patch from Doug Hardie of the Los Angeles Free-Net. MAILSTATS: New command line option -P which acts the same as -p but doesn't truncate the statistics file. MAKEMAP: Add new option -t to specify a different delimiter instead of white space. RMAIL: Invoke sendmail with '-G' to indicate this is a gateway submission. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. SMRSH: Use the vendor supplied directory on FreeBSD 3.3 and later. VACATION: Change Auto-Submitted: header value from auto-generated to auto-replied. From Kenneth Murchison of Oceana Matrix Ltd. VACATION: New option -d to send error/debug messages to stdout instead of syslog. VACATION: New option -U which prevents the attempt to lookup login in the password file. The -f and -m options must be used to specify the database and message file since there is no home directory for the default settings for these options. VACATION: Vacation now uses the libsm mbdb package to look up local mail recipients; it reads the MailboxDatabase option from the sendmail.cf file. New option -C cffile which specifies the path of the sendmail.cf file. New Directories: libmilter/docs New Files: cf/cf/README cf/cf/submit.cf cf/cf/submit.mc cf/feature/authinfo.m4 cf/feature/compat_check.m4 cf/feature/enhdnsbl.m4 cf/feature/msp.m4 cf/feature/local_no_masquerade.m4 cf/feature/lookupdotdomain.m4 cf/feature/preserve_luser_host.m4 cf/feature/preserve_local_plus_detail.m4 cf/feature/queuegroup.m4 cf/sendmail.schema contrib/dnsblaccess.m4 devtools/M4/UNIX/sm-test.m4 devtools/OS/OpenUNIX.5.i386 editmap/* include/sm/* libsm/* libsmutil/cf.c libsmutil/err.c sendmail/SECURITY sendmail/TUNING sendmail/bf.c sendmail/bf.h sendmail/sasl.c sendmail/sm_resolve.c sendmail/sm_resolve.h sendmail/tls.c Deleted Files: cf/feature/rbl.m4 cf/ostype/aix2.m4 devtools/OS/AIX.2 include/sendmail/cdefs.h include/sendmail/errstring.h include/sendmail/useful.h libsmutil/errstring.c sendmail/bf_portable.c sendmail/bf_portable.h sendmail/bf_torek.c sendmail/bf_torek.h sendmail/clock.c Renamed Files: cf/cf/generic-solaris2.mc => cf/cf/generic-solaris.mc cf/cf/generic-solaris2.cf => cf/cf/generic-solaris.cf cf/ostype/aux.m4 => cf/ostype/a-ux.m4 8.11.7/8.11.7 2003/03/29 SECURITY: Fix a remote buffer overflow in header parsing by dropping sender and recipient header comments if the comments are too long. Problem noted by Mark Dowd of ISS X-Force. SECURITY: Fix a buffer overflow in address parsing due to a char to int conversion problem which is potentially remotely exploitable. Problem found by Michal Zalewski. Note: an MTA that is not patched might be vulnerable to data that it receives from untrusted sources, which includes DNS. To provide partial protection to internal, unpatched sendmail MTAs, 8.11.7 changes by default (char)0xff to (char)0x7f in headers etc. To turn off this conversion compile with -DALLOW_255 or use the command line option -d82.101. To provide partial protection for internal, unpatched MTAs that may be performing 7->8 or 8->7 bit MIME conversions, the default for MaxMimeHeaderLength has been changed to 2048/1024. Note: this does have a performance impact, and it only protects against frontal attacks from the outside. To disable the checks and return to pre-8.11.7 defaults, set MaxMimeHeaderLength to 0/0. Properly clean up macros to avoid persistence of session data across various connections. This could cause session oriented restrictions, e.g., STARTTLS requirements, to erroneously allow a connection. Problem noted by Tim Maletic of Priority Health. Ignore comments in NIS host records when trying to find the canonical name for a host. Fix a memory leak when closing Hesiod maps. Set ${msg_size} macro when reading a message from the command line or the queue. Prevent a segmentation fault when clearing the event list by turning off alarms before checking if event list is empty. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Fix a potential core dump problem if the environment variable NAME is set. Problem noted by Beth A. Chaney of Purdue University. Prevent a race condition on child cleanup for delivery to files. Problem noted by Fletcher Mattox of the University of Texas. CONFIG: Do not bounce mail if FEATURE(`ldap_routing')'s bounce parameter is set and the LDAP lookup returns a temporary error. CONFIG: Fix a syntax error in the try_tls ruleset if FEATURE(`access_db') is not enabled. LIBSMDB: Fix a lock race condition that affects makemap, praliases, and vacation. LIBSMDB: Avoid a file creation race condition for Berkeley DB 1.X and NDBM on systems with the O_EXLOCK open(2) flag. MAKEMAP: Avoid going beyond the end of an input line if it does not contain a value for a key. Based on patch from Mark Bixby from Hewlett-Packard. MAIL.LOCAL: Fix a truncation race condition if the close() on the mailbox fails. Problem noted by Tomoko Fukuzawa of Sun Microsystems. SMRSH: SECURITY: Only allow regular files or symbolic links to be used for a command. Problem noted by David Endler of iDEFENSE, Inc. 8.11.6/8.11.6 2001/08/20 SECURITY: Fix a possible memory access violation when specifying out-of-bounds debug parameters. Problem detected by Cade Cairns of SecurityFocus. Avoid leaking recipient information in unrelated DSNs. This could happen if a connection is aborted, several mails had been scheduled for delivery via that connection, and the timeout is reached such that several DSNs are sent next. Problem noted by Dileepan Moorkanat of Hewlett-Packard. Fix a possible segmentation violation when specifying too many wildcard operators in a rule. Problem detected by Werner Wiethege. Avoid a segmentation fault on non-matching Hesiod lookups. Problem noted by Russell McOrmond of flora.ca 8.11.5/8.11.5 2001/07/31 Fix a possible race condition when sending a HUP signal to restart the daemon. This could terminate the current process without starting a new daemon. Problem reported by Wolfgang Breyha of SE Netway Communications. Only apply MaxHeadersLength when receiving a message via SMTP or the command line. Problem noted by Andrey J. Melnikoff. When finding the system's local hostname on an IPv6-enabled system which doesn't have any IPv6 interface addresses, fall back to looking up only IPv4 addresses. Problem noted by Tim Bosserman of EarthLink. When commands were being rejected due to check_relay or TCP Wrappers, the ETRN command was not giving a response. Incoming IPv4 connections on a Family=inet6 daemon (using IPv4-mapped addresses) were incorrectly labeled as "may be forged". Problem noted by Per Steinar Iversen of Oslo University College. Shutdown address test mode cleanly on SIGTERM. Problem noted by Greg King of the OAO Corporation. Restore the original real uid (changed in main() to prevent out of band signals) before invoking a delivery agent. Some delivery agents use this for the "From " envelope "header". Problem noted by Leslie Carroll of the University at Albany. Mark closed file descriptors properly to avoid reuse. Problem noted by Jeff Bronson of J.D. Bronson, Inc. Setting Timeout options on the command line will also override their sub-suboptions in the .cf file, e.g., -O Timeout.queuereturn=2d will set all queuereturn timeouts to 2 days. Problem noted by Roger B.A. Klorese. Portability: BSD/OS has a broken setreuid() implementation. Problem noted by Vernon Schryver of Rhyolite Software. BSD/OS has /dev/urandom(4) (as of version 4.1/199910 ?). Noted by Vernon Schryver of Rhyolite Software. BSD/OS has fchown(2). Noted by Dave Yadallee of Netline 2000 Internet Solutions Inc. Solaris 2.X and later have strerror(3). From Sebastian Hagedorn of Cologne University. CONFIG: Fix parsing for IPv6 domain literals in addresses (user@[IPv6:address]). Problem noted by Liyuan Zhou. 8.11.4/8.11.4 2001/05/28 Clean up signal handling routines to reduce the chances of heap corruption and other potential race conditions. Terminating and restarting the daemon may not be instantaneous due to this change. Also, non-root users can no longer send out-of-band signals. Problem reported by Michal Zalewski of BindView. If LogLevel is greater than 9 and SASL fails to negotiate an encryption layer, avoid core dump logging the encryption strength. Problem noted by Miroslav Zubcic of Crol. If a server offers "AUTH=" and "AUTH " and the list of mechanisms is different in those two lines, sendmail might not have recognized (and used) all of the offered mechanisms. Fix an IP address lookup problem on Solaris 2.0 - 2.3. Patch from Kenji Miyake. This time, really don't use the .. directory when expanding QueueDirectory wildcards. If a process is interrupted while closing a map, don't try to close the same map again while exiting. Allow local mailers (F=l) to contact remote hosts (e.g., via LMTP). Problem noted by Norbert Klasen of the University of Tuebingen. If Timeout.QueueReturn was set to a value less the time it took to write a new queue file (e.g., 0 seconds), the bounce message would be lost. Problem noted by Lorraine L Goff of Oklahoma State University. Pass map argument vector into map rewriting engine for the regex and prog map types. Problem noted by Stephen Gildea of InTouch Systems, Inc. When closing an LDAP map due to a temporary error, close all of the other LDAP maps which share the original map's connection to the LDAP server. Patch from Victor Duchovni of Morgan Stanley. To detect changes of NDBM aliases files check the timestamp of the .pag file instead of the .dir file. Problem noted by Neil Rickert of Northern Illinois University. Don't treat temporary hesiod lookup failures as permanent. Patch from Werner Wiethege. If ClientPortOptions is set, make sure to create the outgoing socket with the family set in that option. Patch from Sean Farley. Avoid a segmentation fault trying to dereference a NULL pointer when logging a MaxHopCount exceeded error with an empty recipient list. Problem noted by Chris Adams of HiWAAY Internet Services. Fix DSN for "Too many hops" bounces. Problem noticed by Ulrich Windl of the Universitaet Regensburg. Fix DSN for "mail loops back to me" bounces. Problem noticed by Kari Hurtta of the Finnish Meteorological Institute. Portability: OpenBSD has a broken setreuid() implementation. CONFIG: Undo change from 8.11.1: change 501 SMTP reply code back to 553 since it is allowed by DRUMS. CONFIG: Add OSTYPE(freebsd4) for FreeBSD 4.X. DEVTOOLS: install.sh did not properly handle paths in the source file name argument. Noted by Kari Hurtta of the Finnish Meteorological Institute. DEVTOOLS: Add FAST_PID_RECYCLE to compile time options for OpenBSD since it generates random process ids. PRALIASES: Add back adaptive algorithm to deal with different endings of entries in the database (with/without trailing '\0'). Patch from John Beck of Sun Microsystems. New Files: cf/ostype/freebsd4.m4 8.11.3/8.11.3 2001/02/27 Prevent a segmentation fault when a bogus value was used in the LDAPDefaultSpec option's -r, -s, or -M flags and if a bogus option was used. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Prevent "token too long" message by shortening {currHeader} which could be too long if the last copied character was a quote. Problem detected by Jan Krueger of digitalanswers communications consulting gmbh. Additional IPv6 check for unspecified addresses. Patch from Jun-ichiro itojun Hagino of the KAME Project. Do not ignore the ClientPortOptions setting if DaemonPortOptions Modifier=b (bind to same interface) is set and the connection came in from the command line. Do not bind to the loopback address if DaemonPortOptions Modifier=b (bind to same interface) is set. Patch from John Beck of Sun Microsystems. Properly deal with open failures on non-optional maps used in check_* rulesets by returning a temporary failure. Buffered file I/O files were not being properly fsync'ed to disk when they were committed. Properly encode '=' for the AUTH= parameter of the MAIL command. Problem noted by Hadmut Danisch. Under certain circumstances the macro {server_name} could be set to the wrong hostname (of a previous connection), which may cause some rulesets to return wrong results. This would usually cause mail to be queued up and delivered later on. Ignore F=z (LMTP) mailer flag if $u is given in the mailer A= equate. Problem noted by Motonori Nakamura of Kyoto University. Work around broken accept() implementations which only partially fill in the peer address if the socket is closed before accept() completes. Return an SMTP "421" temporary failure if the data file can't be opened where the "354" reply would normally be given. Prevent a CPU loop in trying to expand a macro which doesn't exist in a queue run. Problem noted by Gordon Lack of Glaxo Wellcome. If delivering via a program and that program exits with EX_TEMPFAIL, note that fact for the mailq display instead of just showing "Deferred". Problem noted by Motonori Nakamura of Kyoto University. If doing canonification via /etc/hosts, try both the fully qualified hostname as well as the first portion of the hostname. Problem noted by David Bremner of the University of New Brunswick. Portability: Fix a compilation problem for mail.local and rmail if SFIO is in use. Problem noted by Auteria Wally Winzer Jr. of Champion Nutrition. IPv6 changes for platforms using KAME. Patch from Jun-ichiro itojun Hagino of the KAME Project. OpenBSD 2.7 and higher has srandomdev(3). OpenBSD 2.8 and higher has BSDI-style login classes. Patch from Todd C. Miller of Courtesan Consulting. Unixware 7.1.1 doesn't allow h_errno to be set directly if sendmail is being compiled with -kthread. Problem noted by Orion Poplawski of CQG, Inc. CONTRIB: buildvirtuser: Substitute current domain for $DOMAIN and current left hand side for $LHS in virtuser files. DEVTOOLS: Do not pass make targets to recursive Build invocations. Problem noted by Jeff Bronson of J.D. Bronson, Inc. MAIL.LOCAL: In LMTP mode, do not return errors regarding problems storing the temporary message file until after the remote side has sent the final DATA termination dot. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. MAIL.LOCAL: If LMTP mode is set, give a temporary error if users are also specified on the command line. Patch from Motonori Nakamura of Kyoto University. PRALIASES: Skip over AliasFile specifications which aren't based on database files (i.e., only show dbm, hash, and btree). Renamed Files: devtools/OS/OSF1.V5.0 => devtools/OS/OSF1.V5.x 8.11.2/8.11.2 2000/12/29 Prevent a segmentation fault when trying to set a class in address test mode due to a negative array index. Audit other array indexing. This bug is not believed to be exploitable. Noted by Michal Zalewski of the "Internet for Schools" project (IdS). Add an FFR (for future release) to drop privileges when using address test mode. This will be turned on in 8.12. It can be enabled by compiling with: APPENDDEF(`conf_sendmail_ENVDEF', `-D_FFR_TESTMODE_DROP_PRIVS') in your devtools/Site/site.config.m4 file. Suggested by Michal Zalewski of the "Internet for Schools" project (IdS). Fix potential problem with Cyrus-SASL security layer which may have caused I/O errors, especially for mechanism DIGEST-MD5. When QueueSortOrder was set to host, sendmail might not read enough of the queue file to determine the host, making the sort sub-optimal. Problem noted by Jeff Earickson of Colby College. Don't issue DSNs for addresses which use the NOTIFY parameter (per RFC 1891) but don't have FAILURE as value. Initialize Cyrus-SASL library before the SMTP daemon is started. This implies that every change to SASL related files requires a restart of the daemon, e.g., Sendmail.conf, new SASL mechanisms (in form of shared libraries). Properly set the STARTTLS related macros during a queue run for a cached connection. Bug reported by Michael Kellen of NxNetworks, Inc. Log the server name in relay= for ruleset tls_server instead of the client name. Include original length of bad field/header when reporting MaxMimeHeaderLength problems. Requested by Ulrich Windl of the Universitat Regensburg. Fix delivery to set-user-ID files that are expanded from aliases in DeliveryMode queue. Problem noted by Ric Anderson of the University of Arizona. Fix LDAP map -m (match only) flag. Problem noted by Jeff Giuliano of Collective Technologies. Avoid using a negative argument for sleep() calls when delaying answers to EXPN/VRFY commands on systems which respond very slowly. Problem noted by Mikolaj J. Habryn of Optus Internet Engineering. Make sure the F=u flag is set in the default prog mailer definition. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Fix IPv6 check for unspecified addresses. Patch from Jun-ichiro itojun Hagino of the KAME Project. Fix return values for IRIX nsd map. From Kari Hurtta of the Finnish Meteorological Institute. Fix parsing of DaemonPortOptions and ClientPortOptions. Read all of the parameters to find Family= setting before trying to interpret Addr= and Port=. Problem noted by Valdis Kletnieks of Virginia Tech. When delivering to a file directly from an alias, do not call initgroups(); instead use the DefaultUser group information. Problem noted by Marc Schaefer of ALPHANET NF. RunAsUser now overrides the ownership of the control socket, if created. Otherwise, sendmail can not remove it upon close. Problem noted by Werner Wiethege. Fix ConnectionRateThrottle counting as the option is the number of overall connections, not the number of connections per socket. A future version may change this to per socket counting. Portability: Clean up libsmdb so it functions properly on platforms where sizeof(u_int32_t) != sizeof(size_t). Problem noted by Rein Tollevik of Basefarm AS. Fix man page formatting for compatibility with Solaris' whatis. From Stephen Gildea of InTouch Systems, Inc. UnixWare 7 includes snprintf() support. From Larry Rosenman. IPv6 changes for platforms using KAME. Patch from Jun-ichiro itojun Hagino of the KAME Project. Avoid a typedef compile conflict with Berkeley DB 3.X and Solaris 2.5 or earlier. Problem noted by Bob Hughes of Pacific Access. Add preliminary support for AIX 5. Contributed by Valdis Kletnieks of Virginia Tech. Solaris 9 load average support from Andrew Tucker of Sun Microsystems. CONFIG: Reject addresses of the form a!b if FEATURE(`nouucp', `r') is used. Problem noted by Phil Homewood of Asia Online, patch from Neil Rickert of Northern Illinois University. CONFIG: Change the default DNS based blacklist server for FEATURE(`dnsbl') to blackholes.mail-abuse.org. CONFIG: Deal correctly with the 'C' flag in {daemon_flags}, i.e., implicitly assume canonical host names. CONFIG: Deal with "::" in IPv6 addresses for access_db. Based on patch by Motonori Nakamura of Kyoto University. CONFIG: New OSTYPE(`aix5') contributed by Valdis Kletnieks of Virginia Tech. CONFIG: Pass the illegal header form through untouched instead of making it worse. Problem noted by Motonori Nakamura of Kyoto University. CONTRIB: Added buildvirtuser (see `perldoc contrib/buildvirtuser`). CONTRIB: qtool.pl: An empty queue is not an error. Problem noted by Jan Krueger of digitalanswers communications consulting gmbh. CONTRIB: domainmap.m4: Handle domains with '-' in them. From Mark Roth of the University of Illinois at Urbana-Champaign. DEVTOOLS: Change the internal devtools OS, REL, and ARCH m4 variables into bldOS, bldREL, and bldARCH to prevent namespace collisions. Problem noted by Motonori Nakamura of Kyoto University. RMAIL: Undo the 8.11.1 change to use -G when calling sendmail. It causes some changes in behavior and may break rmail for installations where sendmail is actually a wrapper to another MTA. The change will re-appear in a future version. SMRSH: Use the vendor supplied directory on HPUX 10.X, HPUX 11.X, and SunOS 5.8. Requested by Jeff A. Earickson of Colby College and John Beck of Sun Microsystems. VACATION: Fix pattern matching for addresses to ignore. VACATION: Don't reply to addresses of the form owner-* or *-owner. New Files: cf/ostype/aix5.m4 contrib/buildvirtuser devtools/OS/AIX.5.0 8.11.1/8.11.1 2000/09/27 Fix SMTP EXPN command output if the address expands to a single name. Fix from John Beck of Sun Microsystems. Don't try STARTTLS in the client if the PRNG has not been properly seeded. This problem only occurs on systems without /dev/urandom. Problem detected by Jan Krueger of digitalanswers communications consulting gmbh and Neil Rickert of Northern Illinois University. Don't use the . and .. directories when expanding QueueDirectory wildcards. Do not try to cache LDAP connections across processes as a parent process may close the connection before the child process has completed. Problem noted by Lai Yiu Fai of the Hong Kong University of Science and Technology and Wolfgang Hottgenroth of UUNET. Use Timeout.fileopen to limit the amount of time spent trying to read the LDAP secret from a file. Prevent SIGTERM from removing a command line submitted item after the user submits the message and before the first delivery attempt completes. Problem noted by Max France of AlphaNet. Fix from Neil Rickert of Northern Illinois University. Deal correctly with MaxMessageSize restriction if message size is greater than 2^31. Problem noted by Tim "Darth Dice" Bosserman of EarthLink. Turn off queue checkpointing if CheckpointInterval is set to zero. Treat an empty home directory (from getpw*() or $HOME) as non-existent instead of treating it as /. Problem noted by Todd C. Miller of Courtesan Consulting. Don't drop duplicate headers when reading a queued item. Problem noted by Motonori Nakamura of Kyoto University. Avoid bogus error text when logging the savemail panic "cannot save rejected email anywhere". Problem noted by Marc G. Fournier of Acadia University. If an LDAP search fails because the LDAP server went down, close the map so subsequent searches reopen the map. If there are multiple LDAP servers, the down server will be skipped and one of the others may be able to take over. Set the ${load_avg} macro to the current load average, not the previous load average query result. If a non-optional map used in a check_* ruleset can't be opened, return a temporary failure to the remote SMTP client instead of ignoring the map. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Avoid a race condition when queuing up split envelopes by saving the split envelopes before the original envelope. Fix a bug in the PH_MAP code which caused mail to bounce instead of defer if the PH server could not be contacted. From Mark Roth of the University of Illinois at Urbana-Champaign. Prevent QueueSortOrder=Filename from interfering with -qR, -qS, and ETRN. Problem noted by Erik R. Leo of SoVerNet. Change error code for unrecognized parameters to the SMTP MAIL and RCPT commands from 501 to 555 per RFC 1869. Problem reported to Postfix by Robert Norris of Monash University. Prevent overwriting the argument of -B on certain OS. Problem noted by Matteo Gelosa of I.NET S.p.A. Use the proper routine for freeing memory with Netscape's LDAP client libraries. Patch from Paul Hilchey of the University of British Columbia. Portability: Move the NETINET6 define to devtools/OS/SunOS.5.{8,9} instead of defining it in conf.h so users can override the setting. Suggested by Henrik Nordstrom of Ericsson. On HP-UX 10.X and 11.X, use /usr/sbin/sendmail instead of /usr/lib/sendmail for rmail and vacation. From Jeff A. Earickson of Colby College. On HP-UX 11.X, use /usr/sbin instead of /usr/libexec (which does not exist). From Jeff A. Earickson of Colby College. Avoid using the UCB subsystem on NCR MP-RAS 3.x. From Tom Moore of NCR. NeXT 3.X and 4.X installs man pages in /usr/man. From Hisanori Gogota of NTT/InterCommunicationCenter. Solaris 8 and later include /var/run. The default PID file location is now /var/run/sendmail.pid. From John Beck of Sun Microsystems. SFIO includes snprintf() for those operating systems which do not. From Todd C. Miller of Courtesan Consulting. CONFIG: Use the result of _CERT_REGEX_SUBJECT_ not {cert_subject}. Problem noted by Kaspar Brand of futureLab AG. CONFIG: Change 553 SMTP reply code to 501 to avoid problems with errors in the MAIL address. CONFIG: Fix FEATURE(nouucp) usage in example .mc files. Problem noted by Ron Jarrell of Virginia Tech. CONFIG: Add support for Solaris 8 (and later) as OSTYPE(solaris8). Contributed by John Beck of Sun Microsystems. CONFIG: Set confFROM_HEADER such that the mail hub can possibly add GECOS information for an address. This more closely matches pre-8.10 nullclient behavior. From Per Hedeland of Ericsson. CONFIG: Fix MODIFY_MAILER_FLAGS(): apply the flag modifications for SMTP to all *smtp* mailers and those for RELAY to the relay mailer as described in cf/README. MAIL.LOCAL: Open the mailbox as the recipient not root so quotas are obeyed. Problem noted by Damian Kuczynski of NIK. MAKEMAP: Do not change a map's owner to the TrustedUser if using makemap to 'unmake' the map. RMAIL: Avoid overflowing the list of recipients being passed to sendmail. RMAIL: Invoke sendmail with '-G' to indicate this is a gateway submission. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. VACATION: Read the complete message to avoid "broken pipe" signals. VACATION: Do not cut off vacation.msg files which have a single dot as the only character on the line. New Files: cf/ostype/solaris8.m4 8.11.0/8.11.0 2000/07/19 SECURITY: If sendmail is installed as a non-root set-user-ID binary (not the normal case), some operating systems will still keep a saved-uid of the effective-uid when sendmail tries to drop all of its privileges. If sendmail needs to drop these privileges and the operating system doesn't set the saved-uid as well, exit with an error. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. SECURITY: sendmail depends on snprintf() NUL terminating the string it populates. It is possible that some broken implementations of snprintf() exist that do not do this. Systems in this category should compile with -DSNPRINTF_IS_BROKEN=1. Use test/t_snprintf.c to test your system and report broken implementations to sendmail-bugs@sendmail.org and your OS vendor. Problem noted by Slawomir Piotrowski of TELSAT GP. Support SMTP Service Extension for Secure SMTP (RFC 2487) (STARTTLS). Implementation influenced by the example programs of OpenSSL and the work of Lutz Jaenicke of TU Cottbus. Add new STARTTLS related options CACERTPath, CACERTFile, ClientCertFile, ClientKeyFile, DHParameters, RandFile, ServerCertFile, and ServerKeyFile. These are documented in cf/README and doc/op/op.*. New STARTTLS related macros: ${cert_issuer}, ${cert_subject}, ${tls_version}, ${cipher}, ${cipher_bits}, ${verify}, ${server_name}, and ${server_addr}. These are documented in cf/README and doc/op/op.*. Add support for the Entropy Gathering Daemon (EGD) for better random data. New DontBlameSendmail option InsufficientEntropy for systems which don't properly seed the PRNG for OpenSSL but want to try to use STARTTLS despite the security problems. Support the security layer in SMTP AUTH for mechanisms which support encryption. Based on code contributed by Tim Martin of CMU. Add new macro ${auth_ssf} to reflect the SMTP AUTH security strength factor. LDAP's -1 (single match only) flag was not honored if the -z (delimiter) flag was not given. Problem noted by ST Wong of the Chinese University of Hong Kong. Fix from Mark Adamson of CMU. Add more protection from accidentally tripping OpenLDAP 1.X's ld_errno == LDAP_DECODING_ERROR hack on ldap_next_attribute(). Suggested by Kurt Zeilenga of OpenLDAP. Fix the default family selection for DaemonPortOptions. As documented, unless a family is specified in a DaemonPortOptions option, "inet" is the default. It is also the default if no DaemonPortOptions value is set. Therefore, IPv6 users should configure additional sockets by adding DaemonPortOptions settings with Family=inet6 if they wish to also listen on IPv6 interfaces. Problem noted by Jun-ichiro itojun Hagino of the KAME Project. Set ${if_family} when setting ${if_addr} and ${if_name} to reflect the interface information for an outgoing connection. Not doing so was creating a mismatch between the socket family and address used in subsequent connections if the M=b modifier was set in DaemonPortOptions. Problem noted by John Beck of Sun Microsystems. If DaemonPortOptions modifier M=b is used, determine the socket family based on the IP address. ${if_family} is no longer persistent (i.e., saved in qf files). Patch from John Beck of Sun Microsystems. sendmail 8.10 and 8.11 reused the ${if_addr} and ${if_family} macros for both the incoming interface address/family and the outgoing interface address/family. In order for M=b modifier in DaemonPortOptions to work properly, preserve the incoming information in the queue file for later delivery attempts. Use SMTP error code and enhanced status code from check_relay in responses to commands. Problem noted by Jeff Wasilko of smoe.org. Add more vigilance in checking for putc() errors on output streams to protect from a bug in Solaris 2.6's putc(). Problem noted by Graeme Hewson of Oracle. The LDAP map -n option (return attribute names only) wasn't working. Problem noted by Ajay Matia. Under certain circumstances, an address could be listed as deferred but would be bounced back to the sender as failed to be delivered when it really should have been queued. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Prevent a segmentation fault in a child SMTP process from getting the SMTP transaction out of sync. Problem noted by Per Hedeland of Ericsson. Turn off RES_DEBUG if SFIO is defined unless SFIO_STDIO_COMPAT is defined to avoid a core dump due to incompatibilities between sfio and stdio. Problem noted by Neil Rickert of Northern Illinois University. Don't log useless envelope ID on initial connection log. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Convert the free disk space shown in a control socket status query to kilobyte units. If TryNullMXList is True and there is a temporary DNS failure looking up the hostname, requeue the message for a later attempt. Problem noted by Ari Heikkinen of Pohjois-Savo Polytechnic. Under the proper circumstances, failed connections would be recorded as "Bad file number" instead of "Connection failed" in the queue file and persistent host status. Problem noted by Graeme Hewson of Oracle. Avoid getting into an endless loop if a non-hoststat directory exists within the hoststatus directory (e.g., lost+found). Patch from Valdis Kletnieks of Virginia Tech. Make sure Timeout.queuereturn=now returns a bounce message to the sender. Problem noted by Per Hedeland of Ericsson. If a message data file can't be opened at delivery time, panic and abort the attempt instead of delivering a message that states "<<< No Message Collected >>>". Fixup the GID checking code from 8.10.2 as it was overly restrictive. Problem noted by Mark G. Thomas of Mark G. Thomas Consulting. Preserve source port number instead of replacing it with the ident port number (113). Document the queue status characters in the mailq man page. Suggested by Ulrich Windl of the Universitat Regensburg. Process queued items in which none of the recipient addresses have host portions (or there are no recipients). Problem noted by Valdis Kletnieks of Virginia Tech. If a cached LDAP connection is used for multiple maps, make sure only the first to open the connection is allowed to close it so a later map close doesn't break the connection for other maps. Problem noted by Wolfgang Hottgenroth of UUNET. Netscape's LDAP libraries do not support Kerberos V4 authentication. Patch from Rainer Schoepf of the University of Mainz. Provide workaround for inconsistent handling of data passed via callbacks to Cyrus SASL prior to version 1.5.23. Mention ENHANCEDSTATUSCODES in the SMTP HELP helpfile. Omission noted by Ulrich Windl of the Universitat Regensburg. Portability: Add the ability to read IPv6 interface addresses into class 'w' under FreeBSD (and possibly others). From Jun Kuriyama of IMG SRC, Inc. and the FreeBSD Project. Replace code for finding the number of CPUs on HPUX. NCRUNIX MP-RAS 3.02 SO_REUSEADDR socket option does not work properly causing problems if the accept() fails and the socket needs to be reopened. Patch from Tom Moore of NCR. NetBSD uses a .0 extension of formatted man pages. From Andrew Brown of Crossbar Security. Return to using the IPv6 AI_DEFAULT flag instead of AI_V4MAPPED for calls to getipnodebyname(). The Linux implementation is broken so AI_ADDRCONFIG is stripped under Linux. From John Beck of Sun Microsystems and John Kennedy of Cal State University, Chico. CONFIG: Catch invalid addresses containing a ',' at the wrong place. Patch from Neil Rickert of Northern Illinois University. CONFIG: New variables for the new sendmail options: confCACERT_PATH CACERTPath confCACERT CACERTFile confCLIENT_CERT ClientCertFile confCLIENT_KEY ClientKeyFile confDH_PARAMETERS DHParameters confRAND_FILE RandFile confSERVER_CERT ServerCertFile confSERVER_KEY ServerKeyFile CONFIG: Provide basic rulesets for TLS policy control and add new tags to the access database to support these policies. See cf/README for more information. CONFIG: Add TLS information to the Received: header. CONFIG: Call tls_client ruleset from check_mail in case it wasn't called due to a STARTTLS command. CONFIG: If TLS_PERM_ERR is defined, TLS related errors are permanent instead of temporary. CONFIG: FEATURE(`relay_hosts_only') didn't work in combination with the access map and relaying to a domain without using a To: tag. Problem noted by Mark G. Thomas of Mark G. Thomas Consulting. CONFIG: Set confEBINDIR to /usr/sbin to match the devtools entry in OSTYPE(`linux') and OSTYPE(`mklinux'). From Tim Pierce of RootsWeb.com. CONFIG: Make sure FEATURE(`nullclient') doesn't use aliasing and forwarding to make it as close to the old behavior as possible. Problem noted by George W. Baltz of the University of Maryland. CONFIG: Added OSTYPE(`darwin') for Mac OS X and Darwin users. From Wilfredo Sanchez of Apple Computer, Inc. CONFIG: Changed the map names used by FEATURE(`ldap_routing') from ldap_mailhost and ldap_mailroutingaddress to ldapmh and ldapmra as underscores in map names cause problems if underscore is in OperatorChars. Problem noted by Bob Zeitz of the University of Alberta. CONFIG: Apply blacklist_recipients also to hosts in class {w}. Patch from Michael Tratz of Esosoft Corporation. CONFIG: Use A=TCP ... instead of A=IPC ... in SMTP mailers. CONTRIB: Add link_hash.sh to create symbolic links to the hash of X.509 certificates. CONTRIB: passwd-to-alias.pl: More protection from special characters; treat special shells as root aliases; skip entries where the GECOS full name and username match. From Ulrich Windl of the Universitat Regensburg. CONTRIB: qtool.pl: Add missing last_modified_time method and fix a typo. Patch from Graeme Hewson of Oracle. CONTRIB: re-mqueue.pl: Improve handling of a race between re-mqueue and sendmail. Patch from Graeme Hewson of Oracle. CONTRIB: re-mqueue.pl: Don't exit(0) at end so can be called as subroutine Patch from Graeme Hewson of Oracle. CONTRIB: Add movemail.pl (move old mail messages between queues by calling re-mqueue.pl) and movemail.conf (configuration script for movemail.pl). From Graeme Hewson of Oracle. CONTRIB: Add cidrexpand (expands CIDR blocks as a preprocessor to makemap). From Derek J. Balling of Yahoo,Inc. DEVTOOLS: INSTALL_RAWMAN installation option mistakenly applied any extension modifications (e.g., MAN8EXT) to the installation target. Patch from James Ralston of Carnegie Mellon University. DEVTOOLS: Add support for SunOS 5.9. DEVTOOLS: New option confLN contains the command used to create links. LIBSMDB: Berkeley DB 2.X and 3.X errors might be lost and not reported. MAIL.LOCAL: DG/UX portability. Problem noted by Tim Boyer of Denman Tire Corporation. MAIL.LOCAL: Prevent a possible DoS attack when compiled with -DCONTENTLENGTH. Based on patch from 3APA3A@SECURITY.NNOV.RU. MAILSTATS: Fix usage statement (-p and -o are optional). MAKEMAP: Change man page layout as workaround for problem with nroff and -man on Solaris 7. Patch from Larry Williamson. RMAIL: AIX 4.3 has snprintf(). Problem noted by David Hayes of Black Diamond Equipment, Limited. RMAIL: Prevent a segmentation fault if the incoming message does not have a From line. VACATION: Read all of the headers before deciding whether or not to respond instead of stopping after finding recipient. Added Files: cf/ostype/darwin.m4 contrib/cidrexpand contrib/link_hash.sh contrib/movemail.conf contrib/movemail.pl devtools/OS/SunOS.5.9 test/t_snprintf.c 8.10.2/8.10.2 2000/06/07 SECURITY: Work around broken Linux setuid() implementation. On Linux, a normal user process has the ability to subvert the setuid() call such that it is impossible for a root process to drop its privileges. Problem noted by Wojciech Purczynski of elzabsoft.pl. SECURITY: Add more vigilance around set*uid(), setgid(), setgroups(), initgroups(), and chroot() calls. Added Files: test/t_setuid.c 8.10.1/8.10.1 2000/04/06 SECURITY: Limit the choice of outgoing (client-side) SMTP Authentication mechanisms to those specified in AuthMechanisms to prevent information leakage. We do not recommend use of PLAIN for outgoing mail as it sends the password in clear text to possibly untrusted servers. See cf/README's DefaultAuthInfo section for additional information. Copy the ident argument for openlog() to avoid problems on some OSs. Based on patch from Rob Bajorek from Webhelp.com. Avoid bogus error message when reporting an alias line as too long. Avoid bogus socket error message if sendmail.cf version level is greater than sendmail binary supported version. Patch from John Beck of Sun Microsystems. Prevent a malformed ruleset (missing right hand side) from causing a segmentation fault when using address test mode. Based on patch from John Beck of Sun Microsystems. Prevent memory leak from use of NIS maps and yp_match(3). Problem noted by Gil Kloepfer of the University of Texas at Austin. Fix queue file permission checks to allow for TrustedUser ownership. Change logging of errors from the trust_auth ruleset to LogLevel 10 or higher. Avoid simple password cracking attacks against SMTP AUTH by using exponential delay after too many tries within one connection. Encode an initial empty AUTH challenge as '=', not as empty string. Avoid segmentation fault on EX_SOFTWARE internal error logs. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Ensure that a header check which resolves to $#discard actually discards the message. Emit missing value warnings for aliases with no right hand side when newaliases is run instead of only when delivery is attempted to the alias. Remove AuthOptions missing value warning for consistency with other flag options. Portability: SECURITY: Specify a run-time shared library search path for AIX 4.X instead of using the dangerous AIX 4.X linker semantics. AIX 4.X users should consult sendmail/README for further information. Problem noted by Valdis Kletnieks of Virginia Tech. Avoid use of strerror(3) call. Problem noted by Charles Levert of Ecole Polytechnique de Montreal. DGUX requires -lsocket -lnsl and has a non-standard install program. From Tim Boyer of Denman Tire Corporation. HPUX 11.0 has a broken res_search() function. Updates to devtools/OS/NeXT.3.X, NeXT.4.X, and NEXTSTEP.4.X from J. P. McCann of E I A. Digital UNIX/Compaq Tru64 5.0 now includes snprintf(3). Problem noted by Michael Long of Info Avenue Internet Services, LLC. Modern (post-199912) OpenBSD versions include working strlc{at,py}(3) functions. From Todd C. Miller of Courtesan Consulting. SINIX doesn't have random(3). From Gerald Rinske of Siemens Business Services. CONFIG: Change error message about unresolvable sender domain to include the sender address. Proposed by Wolfgang Rupprecht of WSRCC. CONFIG: Fix usenet mailer calls. CONFIG: If RELAY_MAILER_FLAGS is not defined, use SMTP_MAILER_FLAGS to be backward compatible with 8.9. CONFIG: Change handling of default case @domain for virtusertable to allow for +*@domain to deal with +detail. CONTRIB: Remove converting.sun.configs -- it is obsolete. DEVTOOLS: confUBINMODE was being ignored. Fix from KITAZIMA, Tuneki of NEC. DEVTOOLS: Add to NCR platform list and include the architecture (i486). From Tom J. Moore of NCR. DEVTOOLS: SECURITY: Change method of linking with sendmail utility libraries to work around the AIX 4.X and SunOS 4.X linker's overloaded -L option. Problem noted by Valdis Kletnieks of Virginia Tech. DEVTOOLS: configure.sh was overriding the user's choice for confNROFF. Problem noted by Glenn A. Malling of Syracuse University. DEVTOOLS: New variables conf_prog_LIB_POST and confBLDVARIANT added for other internal projects but included in the open source release. LIBSMDB: Check for ".db" instead of simply "db" at the end of the map name to determine whether or not to add the extension. This fixes makemap when building the userdb file. Problem noted by Andrew J Cole of the University of Leeds. LIBSMDB: Allow a database to be opened for updating and created if it doesn't already exist. Problem noted by Rand Wacker of Sendmail. LIBSMDB: If type is SMDB_TYPE_DEFAULT and both NEWDB and NDBM are available, fall back to NDBM if NEWDB open fails. This fixes praliases. Patch from John Beck of Sun Microsystems. LIBSMUTIL: safefile()'s SFF_NOTEXCL check was being misinterpreted as SFF_NOWRFILES. OP.ME: Clarify some issues regarding mailer flags. Suggested by Martin Mokrejs of The Charles University and Neil Rickert of Northern Illinois University. PRALIASES: Restore 8.9.X functionality of being able to search for particular keys in a database by specifying the keys on the command line. Man page updated accordingly. Patch from John Beck of Sun Microsystems. VACATION: SunOS 4.X portability from Charles Levert of Ecole Polytechnique de Montreal. VACATION: Fix -t option which is ignored but available for compatibility with Sun's version, based on patch from Volker Dobler of Infratest Burke. Added Files: devtools/M4/UNIX/smlib.m4 devtools/OS/OSF1.V5.0 Deleted Files: contrib/converting.sun.configs Deleted Directories (already done in 8.10.0 but not listed): doc/intro doc/usenix doc/changes 8.10.0/8.10.0 2000/03/01 ************************************************************* * The engineering department at Sendmail, Inc. has suffered * * the tragic loss of a key member of our engineering team. * * Julie Van Bourg was the Vice President of Engineering * * at Sendmail, Inc. during the development and deployment * * of this release. It was her vision, dedication, and * * support that has made this release a success. Julie died * * on October 26, 1999 of cancer. We have lost a leader, a * * coach, and a friend. * * * * This release is dedicated to her memory and to the joy, * * strength, ideals, and hope that she brought to all of us. * * Julie, we miss you! * ************************************************************* SECURITY: The safe file checks now back track through symbolic links to make sure the files can't be compromised due to poor permissions on the parent directories of the symbolic link target. SECURITY: Only root, TrustedUser, and users in class t can rebuild the alias map. Problem noted by Michal Zalewski of the "Internet for Schools" project (IdS). SECURITY: There is a potential for a denial of service attack if the AutoRebuildAliases option is set as a user can kill the sendmail process while it is rebuilding the aliases file (leaving it in an inconsistent state). This option and its use is deprecated and will be removed from a future version of sendmail. SECURITY: Make sure all file descriptors (besides stdin, stdout, and stderr) are closed before restarting sendmail. Problem noted by Michal Zalewski of the "Internet for Schools" project (IdS). Begin using /etc/mail/ for sendmail related files. This affects a large number of files. See cf/README for more details. The directory structure of the distribution has changed slightly for easier code sharing among the programs. Support SMTP AUTH (see RFC 2554). New macros for this purpose are ${auth_authen}, ${auth_type}, and ${auth_author} which hold the client's authentication credentials, the mechanism used for authentication, and the authorization identity (i.e., the AUTH= parameter if supplied). Based on code contributed by Tim Martin of CMU. On systems which use the Torek stdio library (all of the BSD distributions), use memory-buffered files to reduce file system overhead by not creating temporary files on disk. Contributed by Exactis.com, Inc. New option DataFileBufferSize to control the maximum size of a memory-buffered data (df) file before a disk-based file is used. Contributed by Exactis.com, Inc. New option XscriptFileBufferSize to control the maximum size of a memory-buffered transcript (xf) file before a disk-based file is used. Contributed by Exactis.com, Inc. sendmail implements RFC 2476 (Message Submission), e.g., it can now listen on several different ports. Use: O DaemonPortOptions=Name=MSA, Port=587, M=E to run a Message Submission Agent (MSA); this is turned on by default in m4-generated .cf files; it can be turned off with FEATURE(`no_default_msa'). The 'XUSR' SMTP command is deprecated. Mail user agents should begin using RFC 2476 Message Submission for initial user message submission. XUSR may disappear from a future release. The new '-G' (relay (gateway) submission) command line option indicates that the message being submitted from the command line is for relaying, not initial submission. This means the message will be rejected if the addresses are not fully qualified and no canonicalization will be done. Future releases may even reject improperly formed messages. The '-U' (initial user submission) command line option is deprecated and may be removed from a future release. Mail user agents should begin using '-G' to indicate that this is a relay submission (the inverse of -U). The next release of sendmail will assume that any message submitted from the command line is an initial user submission and act accordingly. If sendmail doesn't have enough privileges to run a .forward program or deliver to file as the owner of that file, the address is marked as unsafe. This means if RunAsUser is set, users won't be able to use programs or delivery to files in their .forward files. Administrators can override this by setting the DontBlameSendmail option to the new setting NonRootSafeAddr. Allow group or world writable directories if the sticky bit is set on the directory and DontBlameSendmail is set to TrustStickyBit. Based on patch from Chris Metcalf of InCert Software. Prevent logging of unsafe directory paths for non-existent forward files if the new DontWarnForwardFileInUnsafeDirPath bit is set in the DontBlameSendmail option. Requested by many. New Timeout.control option to limit the total time spent satisfying a control socket request. New Timeout.resolver options for controlling BIND resolver settings: Timeout.resolver.retrans Sets the resolver's retransmission time interval (in seconds). Sets both Timeout.resolver.retrans.first and Timeout.resolver.retrans.normal. Timeout.resolver.retrans.first Sets the resolver's retransmission time interval (in seconds) for the first attempt to deliver a message. Timeout.resolver.retrans.normal Sets the resolver's retransmission time interval (in seconds) for all resolver lookups except the first delivery attempt. Timeout.resolver.retry Sets the number of times to retransmit a resolver query. Sets both Timeout.resolver.retry.first and Timeout.resolver.retry.normal. Timeout.resolver.retry.first Sets the number of times to retransmit a resolver query for the first attempt to deliver a message. Timeout.resolver.retry.normal Sets the number of times to retransmit a resolver query for all resolver lookups except the first delivery attempt. Contributed by Exactis.com, Inc. Support multiple queue directories. To use multiple queues, supply a QueueDirectory option value ending with an asterisk. For example, /var/spool/mqueue/q* will use all of the directories or symbolic links to directories beginning with 'q' in /var/spool/mqueue as queue directories. Keep in mind, the queue directory structure should not be changed while sendmail is running. Queue runs create a separate process for running each queue unless the verbose flag is given on a non-daemon queue run. New items are randomly assigned to a queue. Contributed by Exactis.com, Inc. Support different directories for qf, df, and xf queue files; if subdirectories or symbolic links to directories of those names exist in the queue directories, they are used for the corresponding queue files. Keep in mind, the queue directory structure should not be changed while sendmail is running. Proposed by Mathias Koerber of Singapore Telecommunications Ltd. New queue file naming system which uses a filename guaranteed to be unique for 60 years. This allows queue IDs to be assigned without fancy file system locking. Queued items can be moved between queues easily. Contributed by Exactis.com, Inc. Messages which are undeliverable due to temporary address failures (e.g., DNS failure) will now go to the FallBackMX host, if set. Contributed by Exactis.com, Inc. New command line option '-L tag' which sets the identifier used for syslog. Contributed by Exactis.com, Inc. QueueSortOrder=Filename will sort the queue by filename. This avoids opening and reading each queue file when preparing to run the queue. Contributed by Exactis.com, Inc. Shared memory counters and microtimers functionality has been donated by Exactis.com, Inc. The SCCS ID tags have been replaced with RCS ID tags. Allow trusted users (those on a T line or in $=t) to set the QueueDirectory (Q) option without an X-Authentication-Warning: being added. Suggested by Michael K. Sanders. IPv6 support based on patches from John Kennedy of Cal State University, Chico, Motonori Nakamura of Kyoto University, and John Beck of Sun Microsystems. In low-disk space situations, where sendmail would previously refuse connections, still accept them, but only allow ETRN commands. Suggested by Mathias Koerber of Singapore Telecommunications Ltd. The [IPC] builtin mailer now allows delivery to a UNIX domain socket on systems which support them. This can be used with LMTP local delivery agents which listen on a named socket. An example mailer might be: Mexecmail, P=[IPC], F=lsDFMmnqSXzA5@/:|, E=\r\n, S=10, R=20/40, T=DNS/RFC822/X-Unix, A=FILE /var/run/lmtpd Code contributed by Lyndon Nerenberg of Messaging Direct. The [TCP] builtin mailer name is now deprecated. Use [IPC] instead. The first mailer argument in the [IPC] mailer is now checked for a legitimate value. Possible values are TCP (for TCP/IP connections), IPC (which will be deprecated in a future version), and FILE (for UNIX domain socket delivery). PrivacyOptions=goaway no longer includes the noetrn and the noreceipts flags. PrivacyOptions=nobodyreturn instructs sendmail not to include the body of the original message on delivery status notifications. Don't announce DSN if PrivacyOptions=noreceipts is set. Problem noted by Dan Bernstein, fix from Robert Harker of Harker Systems. Accept the SMTP RSET command even when rejecting commands due to TCP Wrappers or the check_relay ruleset. Problem noted by Steve Schweinhart of America Online. Warn if OperatorChars is set multiple times. OperatorChars should not be set after rulesets are defined. Suggested by Mitchell Blank Jr of Exec-PC. Do not report temporary failure on delivery to files. In interactive delivery mode, this would result in two SMTP responses after the DATA command. Problem noted by Nik Conwell of Boston University. Check file close when mailing to files. Problem noted by Nik Conwell of Boston University. Avoid a segmentation fault when using the LDAP map. Patch from Curtis W. Hillegas of Princeton University. Always bind to the LDAP server regardless of whether you are using ldap_open() or ldap_init(). Fix from Raj Kunjithapadam of @Home Network. New ruleset trust_auth to determine whether a given AUTH= parameter of the MAIL command should be trusted. See SMTP AUTH, cf/README, and doc/op/op.ps. Allow new named config file rules check_vrfy, check_expn, and check_etrn for VRFY, EXPN, and ETRN commands, respectively, similar to check_rcpt etc. Introduce new macros ${rcpt_mailer}, ${rcpt_host}, ${rcpt_addr}, ${mail_mailer}, ${mail_host}, ${mail_addr} that hold the results of parsing the RCPT and MAIL arguments, i.e. the resolved triplet from $#mailer $@host $:addr. From Kari Hurtta of the Finnish Meteorological Institute. New macro ${client_resolve} which holds the result of the resolve call for ${client_name}: OK, FAIL, FORGED, TEMP. Proposed by Kari Hurtta of the Finnish Meteorological Institute. New macros ${dsn_notify}, ${dsn_envid}, and ${dsn_ret} that hold the corresponding DSN parameter values. Proposed by Mathias Herberts. New macro ${msg_size} which holds the value of the SIZE= parameter, i.e., usually the size of the message (in an ESMTP dialogue), before the message has been collected, thereafter it holds the message size as computed by sendmail (and can be used in check_compat). The macro ${deliveryMode} now specifies the current delivery mode sendmail is using instead of the value of the DeliveryMode option. New macro ${ntries} holds the number of delivery attempts. Drop explicit From: if same as what would be generated only if it is a local address. From Motonori Nakamura of Kyoto University. Write pid to file also if sendmail only processes the queue. Proposed by Roy J. Mongiovi of Georgia Tech. Log "low on disk space" only when necessary. New macro ${load_avg} can be used to check the current load average. Suggested by Scott Gifford of The Internet Ramp. Return-Receipt-To: header implies DSN request if option RrtImpliesDsn is set. Flag -S for maps to specify the character which is substituted for spaces (instead of the default given by O BlankSub). Flag -D for maps: perform no lookup in deferred delivery mode. This flag is set by default for the host map. Based on a proposal from Ian MacPhedran of the University of Saskatchewan. Open maps only on demand, not at startup. Log warning about unsupported IP address families. New option MaxHeadersLength allows to specify a maximum length of the sum of all headers. This can be used to prevent a denial-of-service attack. New option MaxMimeHeaderLength which limits the size of MIME headers and parameters within those headers. This option is intended to protect mail user agents from buffer overflow attacks. Added option MaxAliasRecursion to specify the maximum depth of alias recursion. New flag F=6 for mailers to strip headers to seven bit. Map type syslog to log the key via syslogd. Entries in the alias file can be continued by putting a backslash directly before the newline. New option DeadLetterDrop to define the location of the system-wide dead.letter file, formerly hardcoded to /usr/tmp/dead.letter. If this option is not set (the default), sendmail will not attempt to save to a system-wide dead.letter file if it can not bounce the mail to the user nor postmaster. Instead, it will rename the qf file as it has in the past when the dead.letter file could not be opened. New option PidFile to define the location of the pid file. The value of this option is macro expanded. New option ProcessTitlePrefix specifies a prefix string for the process title shown in 'ps' listings. New macros for use with the PidFile and ProcessTitlePrefix options (along with the already existing macros): ${daemon_info} Daemon information, e.g. SMTP+queueing@00:30:00 ${daemon_addr} Daemon address, e.g., 0.0.0.0 ${daemon_family} Daemon family, e.g., inet, inet6, etc. ${daemon_name} Daemon name, e.g., MSA. ${daemon_port} Daemon port, e.g., 25 ${queue_interval} Queue run interval, e.g., 00:30:00 New macros especially for virtual hosting: ${if_name} hostname of interface of incoming connection. ${if_addr} address of interface of incoming connection. The latter is only set if the interface does not belong to the loopback net. If a message being accepted via a method other than SMTP and would be rejected by a header check, do not send the message. Suggested by Phil Homewood of Mincom Pty Ltd. Don't strip comments for header checks if $>+ is used instead of $>. Provide header value as quoted string in the macro ${currHeader} (possibly truncated to MAXNAME). Suggested by Jan Krueger of Unix-AG of University of Hannover. The length of the header value is stored in ${hdrlen}. H*: allows to specify a default ruleset for header checks. This ruleset will only be called if the individual header does not have its own ruleset assigned. Suggested by Jan Krueger of Unix-AG of University of Hannover. The name of the header field stored in ${hdr_name}. Comments (i.e., text within parentheses) in rulesets are not removed if the config file version is greater than or equal to 9. For example, "R$+ ( 1 ) $@ 1" matches the input "token (1)" but does not match "token". Avoid removing the Content-Transfer-Encoding MIME header on MIME messages. Problem noted by Sigurbjorn B. Larusson of Multimedia Consumer Services. Fix from Per Hedeland of Ericsson. Avoid duplicate Content-Transfer-Encoding MIME header on messages with 8-bit text in headers. Problem noted by Per Steinar Iversen of Oslo College. Fix from Per Hedeland of Ericsson. Avoid keeping maps locked longer than necessary when re-opening a modified database map file. Problem noted by Chris Adams of Renaissance Internet Services. Resolving to the $#error mailer with a temporary failure code (e.g., $#error $@ tempfail $: "400 Temporary failure") will now queue up the message instead of bouncing it. Be more liberal in acceptable responses to an SMTP RSET command as standard does not provide any indication of what to do when something other than 250 is received. Based on a patch from Steve Schweinhart of America Online. New option TrustedUser allows to specify a user who can own important files instead of root. This requires HASFCHOWN. Fix USERDB conditional so compiling with NEWDB or HESIOD and setting USERDB=0 works. Fix from Jorg Zanger of Schock. Fix another instance (similar to one in 8.9.3) of a network failure being mis-logged as "Illegal Seek" instead of whatever really went wrong. From John Beck of Sun Microsystems. $? tests also whether the macro is non-null. Print an error message if a mailer definition contains an invalid equate name. New mailer equate /= to specify a directory to chroot() into before executing the mailer program. Suggested by Igor Vinokurov. New mailer equate W= to specify the maximum time to wait for the mailer to return after sending all data to it. Only free memory from the process list when adding a new process into a previously filled slot. Previously, the memory was freed at removal time. Since removal can happen in a signal handler, this may leave the memory map in an inconsistent state. Problem noted by Jeff A. Earickson and David Cooley of Colby College. When using the UserDB @hostname catch-all, do not try to lookup local users in the passwd file. The UserDB code has already decided the message will be passed to another host for processing. Fix from Tony Landells of Burdett Buckeridge Young Limited. Support LDAP authorization via either a file containing the password or Kerberos V4 using the new map options '-ddistinguished_name', '-Mmethod', and '-Pfilename'. The distinguished_name is who to login as. The method can be one of LDAP_AUTH_NONE, LDAP_AUTH_SIMPLE, or LDAP_AUTH_KRBV4. The filename is the file containing the secret key for LDAP_AUTH_SIMPLE or the name of the Kerberos ticket file for LDAP_AUTH_KRBV4. Patch from Booker Bense of Stanford University. The ldapx map has been renamed to ldap. The use of ldapx is deprecated and will be removed in a future version. If the result of an LDAP search returns a multi-valued attribute and the map has the column delimiter set, it turns that response into a delimiter separated string. The LDAP map will traverse multiple entries as well. LDAP alias maps automatically set the column delimiter to the comma. Based on patch from Booker Bense of Stanford University and idea from Philip A. Prindeville of Mirapoint, Inc. Support return of multiple values for a single LDAP lookup. The values to be returned should be in a comma separated string. For example, `-v "email,emailother"'. Patch from Curtis W. Hillegas of Princeton University. Allow the use of LDAP for alias maps. If no LDAP attributes are specified in an LDAP map declaration, all attributes found in the match will be returned. Prevent commas in quoted strings in the AliasFile value from breaking up a single entry into multiple entries. This is needed for LDAP alias file specifications to allow for comma separated key and value strings. Keep connections to LDAP server open instead of opening and closing for each lookup. To reduce overhead, sendmail will cache connections such that multiple maps which use the same host, port, bind DN, and authentication will only result in a single connection to that host. Put timeout in the proper place for USE_LDAP_INIT. Be more careful about checking for errors and freeing memory on LDAP lookups. Use asynchronous LDAP searches to save memory and network resources. Do not copy LDAP query results if the map's match only flag is set. Increase portability to the Netscape LDAP libraries. Change the parsing of the LDAP filter specification. '%s' is still replaced with the literal contents of the map lookup key -- note that this means a lookup can be done using the LDAP special characters. The new '%0' token can be used instead of '%s' to encode the key buffer according to RFC 2254. For example, if the LDAP map specification contains '-k "(user=%s)"' and a lookup is done on "*", this would be equivalent to '-k "(user=*)"' -- matching ANY record with a user attribute. Instead, if the LDAP map specification contains '-k "(user=%0)"' and a lookup is done on "*", this would be equivalent to '-k "(user=\2A)"' -- matching a user with the name "*". New LDAP map flags: "-1" requires a single match to be returned, if more than one is returned, it is equivalent to no records being found; "-r never|always|search|find" sets the LDAP alias dereference option; "-Z size" limits the number of matches to return. New option LDAPDefaultSpec allows a default map specification for LDAP maps. The value should only contain LDAP specific settings such as "-h host -p port -d bindDN", etc. The settings will be used for all LDAP maps unless they are specified in the individual map specification ('K' command). This option should be set before any LDAP maps are defined. Prevent an NDBM alias file opening loop when the NDBM open continually fails. Fix from Roy J. Mongiovi of Georgia Tech. Reduce memory utilization for smaller symbol table entries. In particular, class entries get much smaller, which can be important if you have large classes. On network-related temporary failures, record the hostname which gave error in the queued status message. Requested by Ulrich Windl of the Universitat Regensburg. Add new F=% mailer flag to allow for a store and forward configuration. Mailers which have this flag will not attempt delivery on initial receipt of a message or on queue runs unless the queued message is selected using one of the -qI/-qR/-qS queue run modifiers or an ETRN request. Code provided by Philip Guenther of Gustavus Adolphus College. New option ControlSocketName which, when set, creates a daemon control socket. This socket allows an external program to control and query status from the running sendmail daemon via a named socket, similar to the ctlinnd interface to the INN news server. Access to this interface is controlled by the UNIX file permissions on the named socket on most UNIX systems (see sendmail/README for more information). An example control program is provided as contrib/smcontrol.pl. Change the default values of QueueLA from 8 to (8 * numproc) and RefuseLA from 12 to (12 * numproc) where numproc is the number of processors online on the system (if that can be determined). For single processor machines, this change has no effect. Don't return body of message to postmaster on "Too many hops" bounces. Based on fix from Motonori Nakamura of Kyoto University. Give more detailed DSN descriptions for some cases. Patch from Motonori Nakamura of Kyoto University. Logging of alias, forward file, and UserDB expansion now happens at LogLevel 11 or higher instead of 10 or higher. Logging of an envelope's complete delivery (the "done" message) now happens at LogLevel 10 or higher instead of 11 or higher. Logging of TCP/IP or UNIX standard input connections now happens at LogLevel 10 or higher. Previously, only TCP/IP connections were logged, and on at LogLevel 12 or higher. Setting LogLevel to 10 will now assist users in tracking frequent connection-based denial of service attacks. Log basic information about authenticated connections at LogLevel 10 or higher. Log SMTP Authentication mechanism and author when logging the sender information (from= syslog line). Log the DSN code for each recipient if one is available as a new equate (dsn=). Macro expand PostmasterCopy and DoubleBounceAddress options. New "ph" map for performing ph queries in rulesets, see sendmail/README for details. Contributed by Mark Roth of the University of Illinois at Urbana-Champaign. Detect temporary lookup failures in the host map if looking up a bracketed IP address. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Do not report a Remote-MTA on local deliveries. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. When a forward file points to an alias which runs a program, run the program as the default user and the default group, not the forward file user. This change also assures the :include: directives in aliases are also processed using the default user and group. Problem noted by Sergiu Popovici of DNT Romania. Prevent attempts to save a dead.letter file for a user with no home directory (/no/such/directory). Problem noted by Michael Brown of Finnigan FT/MS. Include message delay and number of tries when logging that a message has been completely delivered (LogLevel of 10 or above). Suggested by Nick Hilliard of Ireland Online. Log the sender of a message even if none of the recipients were accepted. If some of the recipients were rejected, it is helpful to know the sender of the message. Check the root directory (/) when checking a path for safety. Problem noted by John Beck of Sun Microsystems. Prevent multiple responses to the DATA command if DeliveryMode is interactive and delivering to an alias which resolves to multiple files. Macros in the helpfile are expanded if the helpfile version is 2 or greater (see below); the help function doesn't print the version of sendmail any longer, instead it is placed in the helpfile ($v). Suggested by Chuck Foster of UUNET PIPEX. Additionally, comment lines (starting with #) are skipped and a version line (#vers) is introduced. The helpfile version for 8.10.0 is 2, if no version or an older version is found, a warning is logged. The '#vers' directive should be placed at the top of the help file. Use fsync() when delivering to a file to guarantee the delivery to disk succeeded. Suggested by Nick Christenson. If delivery to a file is unsuccessful, truncate the file back to its length before the attempt. If a forward points to a filename for delivery, change to the user's uid before checking permissions on the file. This allows delivery to files on NFS mounted directories where root is remapped to nobody. Problem noted by Harald Daeubler of Universitaet Ulm. purgestat and sendmail -bH purge only expired (Timeout.hoststatus) host status files, not all files. Any macros stored in the class $={persistentMacros} will be saved in the queue file for the message and set when delivery is attempted on the queued item. Suggested by Kyle Jones of Wonderworks Inc. Add support for storing information between rulesets using the new macro map class. This can be used to store information between queue runs as well using $={persistentMacros}. Based on an idea from Jan Krueger of Unix-AG of University of Hannover. New map class arith to allow for computations in rules. The operation (+, -, *, /, l (for less than), and =) is given as key. The two operands are specified as arguments; the lookup returns the result of the computation. For example, "$(arith l $@ 4 $@ 2 $)" will return "FALSE" and "$(arith + $@ 4 $@ 2 $)" will return "6". Add new syntax for header declarations which decide whether to include the header based on a macro rather than a mailer flag: H?${MyMacro}?X-My-Header: ${MyMacro} This should be used along with $={persistentMacros}. It can be used for adding headers to a message based on the results of check_* and header check rulesets. Allow new named config file rule check_eoh which is called after all of the headers have been collected. The input to the ruleset the number of headers and the size of all of the headers in bytes separated by $|. This ruleset along with the macro storage map can be used to correlate information gathered between headers and to check for missing headers. See cf/README or doc/op/op.ps for an example. Change the default for the MeToo option to True to correspond to the clarification in the DRUMS SMTP Update spec. This option is deprecated and will be removed from a future version. Change the sendmail binary default for SendMimeErrors to True. Change the sendmail binary default for SuperSafe to True. Display ruleset names in debug and address test mode output if referencing a named ruleset. New mailer equate m= which will limit the number of messages delivered per connection on an SMTP or LMTP mailer. Improve QueueSortOrder=Host by reversing the hostname before using it to sort. Now all the same domains are really run through the queue together. If they have the same MX host, then they will have a much better opportunity to use the connection cache if available. This should be a reasonable performance improvement. Patch from Randall Winchester of the University of Maryland. If a message is rejected by a header check ruleset, log who would have received the message if it had not been rejected. New "now" value for Timeout.queuereturn to bounce entries from the queue immediately. No delivery attempt is made. Increase sleeping time exponentially after too many "bad" commands up to 4 minutes delay (compare MAX{BAD,NOOP,HELO,VRFY,ETRN}- COMMANDS). New option ClientPortOptions similar to DaemonPortOptions but for outgoing connections. New suboptions for DaemonPortOptions: Name (a name used for error messages and logging) and Modifiers, i.e. a require authentication b bind to interface through which mail has been received c perform hostname canonification f require fully qualified hostname h use name of interface for outgoing HELO command C don't perform hostname canonification E disallow ETRN (see RFC 2476) New suboption for ClientPortOptions: Modifiers, i.e. h use name of interface for HELO command The version number for queue files (qf) has been incremented to 4. Log unacceptable HELO/EHLO domain name attempts if LogLevel is set to 10 or higher. Suggested by Rick Troxel of the National Institutes of Health. If a mailer dies, print the status in decimal instead of octal format. Suggested by Michael Shapiro of Sun Microsystems. Limit the length of all MX records considered for delivery to 8k. Move message priority from sender to recipient logging. Suggested by Ulrich Windl of the Universitat Regensburg. Add support for Berkeley DB 3.X. Add fix for Berkeley DB 2.X fcntl() locking race condition. Requires a post-2.7.5 version of Berkeley DB. Support writing traffic log (sendmail -X option) to a FIFO. Patch submitted by Rick Heaton of Network Associates, Inc. Do not ignore Timeout settings in the .cf file when a Timeout sub-options is set on the command line. Problem noted by Graeme Hewson of Oracle. Randomize equal preference MX records each time delivery is attempted via a new connection to a host instead of once per session. Suggested by Scott Salvidio of Compaq. Implement enhanced status codes as defined by RFC 2034. Add [hostname] to class w for the names of all interfaces unless DontProbeInterfaces is set. This is useful for sending mails to hosts which have dynamically assigned names. If a message is bounced due to bad MIME conformance, avoid bouncing the bounce for the same reason. If the body is not 8-bit clean, and EightBitMode isn't set to pass8, the body will not be included in the bounce. Problem noted by Valdis Kletnieks of Virginia Tech. The timeout for sending a message via SMTP has been changed from '${msgsize} / 16 + (${nrcpts} * 300)' to a timeout which simply checks for progress on sending data every 5 minutes. This will detect the inability to send information quicker and reduce the number of processes simply waiting to timeout. Prevent a segmentation fault on systems which give a partial filled interface address structure when loading the system network interface addresses. Fix from Reinier Bezuidenhout of Nanoteq. Add a compile-time configuration macro, MAXINTERFACES, which indicates the number of interfaces to read when probing for hostnames and IP addresses for class w ($=w). The default value is 512. Based on idea from Reinier Bezuidenhout of Nanoteq. If the RefuseLA option is set to 0, do not reject connections based on load average. Allow ruleset 0 to have a name. Problem noted by Neil Rickert of Northern Illinois University. Expand the Return-Path: header at delivery time, after "owner-" envelope splitting has occurred. Don't try to sort the queue if there are no entries. Patch from Luke Mewburn from RMIT University. Add a "/quit" command to address test mode. Include the proper sender in the UNIX "From " line and Return-Path: header when undeliverable mail is saved to ~/dead.letter. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. The contents of a class can now be copied to another class using the syntax: "C{Dest} $={Source}". This would copy all of the items in class $={Source} into the class $={Dest}. Include original envelope's error transcript in bounces created for split (owner-) envelopes to see the original errors when the recipients were added. Based on fix from Motonori Nakamura of Kyoto University. Show reason for permanent delivery errors directly after the addresses. From Motonori Nakamura of Kyoto University. Prevent a segmentation fault when bouncing a split-envelope message. Patch from Motonori Nakamura of Kyoto University. If the specification for the queue run interval (-q###) has a syntax error, consider the error fatal and exit. Pay attention to CheckpointInterval during LMTP delivery. Problem noted by Motonori Nakamura of Kyoto University. On operating systems which have setlogin(2), use it to set the login name to the RunAsUserName when starting as a daemon. This is for delivery to programs which use getlogin(). Based on fix from Motonori Nakamura of Kyoto University. Differentiate between "command not implemented" and "command unrecognized" in the SMTP dialogue. Strip returns from forward and include files. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. Prevent a core dump when using 'sendmail -bv' on an address which resolves to the $#error mailer with a temporary failure. Based on fix from Neil Rickert of Northern Illinois University. Prevent multiple deliveries of a message with a "non-local alias" pointing to a local user, if canonicalization fails the message was requeued *and* delivered to the alias. If an invalid ruleset is declared, the ruleset name could be ignored and its rules added to S0. Instead, ignore the ruleset lines as well. Avoid incorrect Final-Recipient, Action, and X-Actual-Recipient success DSN fields as well as duplicate entries for a single address due to S5 and UserDB processing. Problems noted by Kari Hurtta of the Finnish Meteorological Institute. Turn off timeouts when exiting sendmail due to an interrupt signal to prevent the timeout from firing during the exit process. Problem noted by Michael Shapiro of Sun Microsystems. Do not append @MyHostName to non-RFC822 addresses output by the EXPN command or on Final-Recipient: and X-Actual-Recipient: DSN headers. Non-RFC822 addresses include deliveries to programs, file, DECnet, etc. Fix logic for determining if a local user is using -f or -bs to spoof their return address. Based on idea from Neil Rickert of Northern Illinois University and patch from Per Hedeland of Ericsson. Report the proper UID in the bounce message if an :include: file is owned by a uid that doesn't map to a username and the :include: file contains delivery to a file or program. Problem noted by John Beck of Sun Microsystems. Avoid the attempt of trying to send a second SMTP QUIT command if the remote server responds to the first QUIT with a 4xx response code and drops the connection. This behavior was noted by Ulrich Windl of the Universitat Regensburg when sendmail was talking to the Mercury 1.43 MTA. If a hostname lookup times out and ServiceSwitchFile is set but the file is not present, the lookup failure would be marked as a permanent failure instead of a temporary failure. Fix from Russell King of the ARM Linux Project. Handle aliases or forwards which deliver to programs using tabs instead of spaces between arguments. Problem noted by Randy Wormser. Fix from Neil Rickert of Northern Illinois University. Allow MaxRecipientsPerMessage option to be set on the command line by normal users (e.g., sendmail won't drop its root privileges) to allow overrides for message submission via 'sendmail -bs'. Set the names for help file and statistics file to "helpfile" and "statistics", respectively, if no parameters are given for them in the .cf file. Avoid bogus 'errbody: I/O Error -7' log messages when sending success DSN messages for messages relayed to non-DSN aware systems. Problem noted by Juergen Georgi of RUS University of Stuttgart and Kyle Tucker of Parexel International. Prevent +detail information from interfering with local delivery to multiple users in the same transaction (F=m). Add H_FORCE flag for the X-Authentication-Warning: header, so it will be added even if one already exists. Problem noted by Michal Zalewski of Marchew Industries. Stop processing SMTP commands if the SMTP connection is dropped. This prevents a remote system from flooding the connection with commands and then disconnecting. Previously, the server would process all of the buffered commands. Problem noted by Michal Zalewski of Marchew Industries. Properly process user-supplied headers beginning with '?'. Problem noted by Michal Zalewski of Marchew Industries. If multiple header checks resolve to the $#error mailer, use the last permanent (5XX) failure if any exist. Otherwise, use the last temporary (4XX) failure. RFC 1891 requires "hexchar" in a "xtext" to be upper case. Patch from Ronald F. Guilmette of Infinite Monkeys & Co. Timeout.ident now defaults to 5 seconds instead of 30 seconds to prevent the now common delays associated with mailing to a site which drops IDENT packets. Suggested by many. Persistent host status data is not reloaded disk when current data is available in the in-memory cache. Problem noted by Per Hedeland of Ericsson. mailq displays unprintable characters in addresses as their octal representation and a leading backslash. This avoids problems with "unprintable" characters. Problem noted by Michal Zalewski of the "Internet for Schools" project (IdS). The mail line length limit (L= equate) was adding the '!' indicator one character past the limit. This would cause subsequent hops to break the line again. The '!' is now placed in the last column of the limit if the line needs to be broken. Problem noted by Joe Pruett of Q7 Enterprises. Based on fix from Per Hedeland of Ericsson. If a resolver ANY query is larger than the UDP packet size, the resolver will fall back to TCP. However, some misconfigured firewalls black 53/TCP so the ANY lookup fails whereas an MX or A record might succeed. Therefore, don't fail on ANY queries. If an SMTP recipient is rejected due to syntax errors in the address, do not send an empty postmaster notification DSN to the postmaster. Problem noted by Neil Rickert of Northern Illinois University. Allow '_' and '.' in map names when parsing a sequence map specification. Patch from William Setzer of North Carolina State University. Fix hostname in logging of read timeouts for the QUIT command on cached connections. Problem noted by Neil Rickert of Northern Illinois University. Use a more descriptive entry to log "null" connections, i.e., "host did not issue MAIL/EXPN/VRFY/ETRN during connection". Fix a file descriptor leak in ONEX mode. Portability: Reverse signal handling logic such that sigaction(2) with the SA_RESTART flag is the preferred method and the other signal methods are only tried if SA_RESTART is not available. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. AIX 4.x supports the sa_len member of struct sockaddr. This allows network interface probing to work properly. Fix from David Bronder of the University of Iowa. AIX 4.3 has snprintf() support. Use "PPC" as the architecture name when building under AIX. This will be reflected in the obj.* directory name. Apple Darwin support based on Apple Rhapsody port. Fixed AIX 'make depend' method from Valdis Kletnieks of Virginia Tech. Digital UNIX has uname(2). GNU Hurd updates from Mark Kettenis of the University of Amsterdam. Improved HPUX 11.0 portability. Properly determine the number of CPUs on FreeBSD 2.X, FreeBSD 3.X, HP/UX 10.X and HP/UX 11.X. Remove special IRIX ABI cases from Build script and the OS files. Use the standard 'cc' options used by SGI in building the operating system. Users can override the defaults by setting confCC and confLIBSEARCHPATH appropriately. IRIX nsd map support from Bob Mende of SGI. Minor devtools fixes for IRIX from Bob Mende of SGI. Linux patch for IP_SRCROUTE support from Joerg Dorchain of MW EDV & ELECTRONIC. Linux now uses /usr/sbin for confEBINDIR in the build system. From MATSUURA Takanori of Osaka University. Remove special treatment for Linux PPC in the build system. From MATSUURA Takanori of Osaka University. Motorolla UNIX SYSTEM V/88 Release 4.0 support from Sergey Rusanov of the Republic of Udmurtia. NCR MP-RAS 3.x includes regular expression support. From Tom J. Moore of NCR. NEC EWS-UX/V series settings for _PATH_VENDOR_CF and _PATH_SENDMAILPID from Oota Toshiya of NEC Computers Group Planning Division. Minor NetBSD owner/group tweaks from Ayamura Kikuchi, M.D. NEWS-OS 6.X listed SYSLOG_BUFSIZE as 256 in confENVDEF and 1024 in conf.h. Since confENVDEF would be used, use that value in conf.h. Use NeXT's NETINFO to get domain name. From Gerd Knops of BITart Consulting. Use NeXT's NETINFO for alias and hostname resolution if AUTO_NETINFO_ALIASES and AUTO_NETINFO_HOSTS are defined. Patch from Wilfredo Sanchez of Apple Computer, Inc. NeXT portability tweaks. Problems reported by Dragan Milicic of the University of Utah and J. P. McCann of E I A. New compile flag FAST_PID_RECYCLE: set this if your system can reuse the same PID in the same second. New compile flag HASFCHOWN: set this if your OS has fchown(2). New compile flag HASRANDOM: set this to 0 if your OS does not have random(3). rand() will be used instead. New compile flag HASSRANDOMDEV: set this if your OS has srandomdev(3). New compile flag HASSETLOGIN: set this if your OS has setlogin(2). Replace SINIX and ReliantUNIX support with version specific SINIX files. From Gerald Rinske of Siemens Business Services. Use the 60-second load average instead of the 5 second load average on Compaq Tru64 UNIX (formerly Digital UNIX). From Chris Teakle of the University of Qld. Use ANSI C by default for Compaq Tru64 UNIX. Suggested by Randall Winchester of Swales Aerospace. Correct setgroups() prototype for Compaq Tru64 UNIX. Problem noted by Randall Winchester of Swales Aerospace. Hitachi 3050R/3050RX and 3500 Workstations running HI-UX/WE2 4.02, 6.10 and 7.10 from Motonori NAKAMURA of Kyoto University. New compile flag NO_GETSERVBYNAME: set this to disable use of getservbyname() on systems which can not lookup a service by name over NIS, such as HI-UX. Patch from Motonori NAKAMURA of Kyoto University. Use devtools/bin/install.sh on SCO 5.x. Problem noted by Sun Wenbing of the China Engineering and Technology Information Network. make depend didn't work properly on UNIXWARE 4.2. Problem noted by Ariel Malik of Netology, Ltd. Use /usr/lbin as confEBINDIR for Compaq Tru64 (Digital UNIX). Set confSTDIO_TYPE to torek for BSD-OS, FreeBSD, NetBSD, and OpenBSD. A recent Compaq Ultrix 4.5 Y2K patch has broken detection of local_hostname_length(). See sendmail/README for more details. Problem noted by Allan E Johannesen of Worcester Polytechnic Institute. CONFIG: Begin using /etc/mail/ for sendmail related files. This affects a large number of files. See cf/README for more details. CONFIG: New macro MAIL_SETTINGS_DIR contains the path (including trailing slash) for the mail settings directory. CONFIG: Increment version number of config file to 9. CONFIG: OSTYPE(`bsdi1.0') and OSTYPE(`bsdi2.0') have been deprecated and may be removed from a future release. BSD/OS users should begin using OSTYPE(`bsdi'). CONFIG: OpenBSD 2.4 installs mail.local non-set-user-ID root. This requires a new OSTYPE(`openbsd'). From Todd C. Miller of Courtesan Consulting. CONFIG: New OSTYPE(`hpux11') for HP/UX 11.X. CONFIG: A syntax error in check_mail would cause fake top-level domains (.BITNET, .DECNET, .FAX, .USENET, and .UUCP) to be improperly rejected as unresolvable. CONFIG: New FEATURE(`dnsbl') takes up to two arguments (name of DNS server, rejection message) and can be included multiple times. CONFIG: New FEATURE(`relay_mail_from') allows relaying if the mail sender is listed as RELAY in the access map (and tagged with From:). CONFIG: Optional tagging of LHS in the access map (Connect:, From:, To:) to enable finer control. CONFIG: New FEATURE(`ldap_routing') implements LDAP address routing. See cf/README for a complete description of the new functionality. CONFIG: New variables for the new sendmail options: confAUTH_MECHANISMS AuthMechanisms confAUTH_OPTIONS AuthOptions confCLIENT_OPTIONS ClientPortOptions confCONTROL_SOCKET_NAME ControlSocketName confDEAD_LETTER_DROP DeadLetterDrop confDEF_AUTH_INFO DefaultAuthInfo confDF_BUFFER_SIZE DataFileBufferSize confLDAP_DEFAULT_SPEC LDAPDefaultSpec confMAX_ALIAS_RECURSION MaxAliasRecursion confMAX_HEADERS_LENGTH MaxHeadersLength confMAX_MIME_HEADER_LENGTH MaxMimeHeaderLength confPID_FILE PidFile confPROCESS_TITLE_PREFIX ProcessTitlePrefix confRRT_IMPLIES_DSN RrtImpliesDsn confTO_CONTROL Timeout.control confTO_RESOLVER_RETRANS Timeout.resolver.retrans confTO_RESOLVER_RETRANS_FIRST Timeout.resolver.retrans.first confTO_RESOLVER_RETRANS_NORMAL Timeout.resolver.retrans.normal confTO_RESOLVER_RETRY Timeout.resolver.retry confTO_RESOLVER_RETRY_FIRST Timeout.resolver.retry.first confTO_RESOLVER_RETRY_NORMAL Timeout.resolver.retry.normal confTRUSTED_USER TrustedUser confXF_BUFFER_SIZE XscriptFileBufferSize CONFIG: confDAEMON_OPTIONS has been replaced by DAEMON_OPTIONS(), which takes the options as argument and can be used multiple times; see cf/README for details. CONFIG: Add a fifth mailer definition to MAILER(`smtp') called "dsmtp". This mail provides on-demand delivery using the F=% mailer flag described above. The "dsmtp" mailer definition uses the new DSMTP_MAILER_ARGS which defaults to "IPC $h". CONFIG: New variables LOCAL_MAILER_MAXMSGS, SMTP_MAILER_MAXMSGS, and RELAY_MAILER_MAXMSGS for setting the m= equate for the local, smtp, and relay mailers respectively. CONFIG: New variable LOCAL_MAILER_DSN_DIAGNOSTIC_CODE for setting the DSN Diagnostic-Code type for the local mailer. The value should be changed with care. CONFIG: FEATURE(`local_lmtp') now sets the DSN Diagnostic-Code type for the local mailer to the proper value of "SMTP". CONFIG: All included maps are no longer optional by default; if there there is a problem with a map, sendmail will complain. CONFIG: Removed root from class E; use EXPOSED_USER(`root') to get the old behavior. Suggested by Joe Pruett of Q7 Enterprises. CONFIG: MASQUERADE_EXCEPTION() defines hosts/subdomains which will not be masqueraded. Proposed by Arne Wichmann of MPI Saarbruecken, Griff Miller of PGS Tensor, Jayme Cox of Broderbund Software Inc. CONFIG: A list of exceptions for FEATURE(`nocanonify') can be specified by CANONIFY_DOMAIN or CANONIFY_DOMAIN_FILE, i.e., a list of domains which are passed to $[ ... $] for canonification. Based on an idea from Neil Rickert of Northern Illinois University. CONFIG: If `canonify_hosts' is specified as parameter for FEATURE(`nocanonify') then addresses which have only a hostname, e.g., , will be canonified. CONFIG: If FEATURE(`nocanonify') is turned on, a trailing dot is nevertheless added to addresses with more than one component in it. CONFIG: Canonification is no longer attempted for any host or domain in class 'P' ($=P). CONFIG: New class for matching virtusertable entries $={VirtHost} that can be populated by VIRTUSER_DOMAIN or VIRTUSER_DOMAIN_FILE. FEATURE(`virtuser_entire_domain') can be used to apply this class also to entire subdomains. Hosts in this class are treated as canonical in SCanonify2, i.e., a trailing dot is added. CONFIG: If VIRTUSER_DOMAIN() or VIRTUSER_DOMAIN_FILE() are used, include $={VirtHost} in $=R (hosts allowed to relay). CONFIG: FEATURE(`generics_entire_domain') can be used to apply the genericstable also to subdomains of $=G. CONFIG: Pass "+detail" as %2 for virtusertable lookups. Patch from Noam Freedman from University of Chicago. CONFIG: Pass "+detail" as %1 for genericstable lookups. Suggested by Raymond S Brand of rsbx.net. CONFIG: Allow @domain in genericstable to override masquerading. Suggested by Owen Duffy from Owen Duffy & Associates. CONFIG: LOCAL_DOMAIN() adds entries to class w. Suggested by Steve Hubert of University of Washington. CONFIG: OSTYPE(`gnuhurd') has been replaced by OSTYPE(`gnu') as GNU is now the canonical system name. From Mark Kettenis of the University of Amsterdam. CONFIG: OSTYPE(`unixware7') updates from Larry Rosenman. CONFIG: Do not include '=' in option expansion if there is no value associated with the option. From Andrew Brown of Graffiti World Wide, Inc. CONFIG: Add MAILER(`qpage') to define a new pager mailer. Contributed by Philip A. Prindeville of Enteka Enterprise Technology Services. CONFIG: MAILER(`cyrus') was not preserving case for mail folder names. Problem noted by Randall Winchester of Swales Aerospace. CONFIG: RELAY_MAILER_FLAGS can be used to define additional flags for the relay mailer. Suggested by Doug Hughes of Auburn University and Brian Candler. CONFIG: LOCAL_MAILER_FLAGS now includes 'P' (Add Return-Path: header) by default. Suggested by Per Hedeland of Ericsson. CONFIG: Use SMART_HOST for bracketed addresses, e.g., user@[host]. Suggested by Kari Hurtta of the Finnish Meteorological Institute. CONFIG: New macro MODIFY_MAILER_FLAGS to tweak *_MAILER_FLAGS; i.e., to set, add, or delete flags. CONFIG: If SMTP AUTH is used then relaying is allowed for any user who authenticated via a "trusted" mechanism, i.e., one that is defined via TRUST_AUTH_MECH(`list of mechanisms'). CONFIG: FEATURE(`delay_checks') delays check_mail and check_relay after check_rcpt and allows for exceptions from the checks. CONFIG: Map declarations have been moved into their associated feature files to allow greater flexibility in use of sequence maps. Suggested by Per Hedeland of Ericsson. CONFIG: New macro LOCAL_MAILER_EOL to override the default end of line string for the local mailer. Requested by Il Oh of Willamette Industries, Inc. CONFIG: Route addresses are stripped, i.e., <@a,@b,@c:user@d> is converted to CONFIG: Reject bogus return address of <@@hostname>, generated by Sun's older, broken configuration files. CONFIG: FEATURE(`nullclient') now provides the full rulesets of a normal configuration, allowing anti-spam checks to be performed. CONFIG: Don't return a permanent error (Relaying denied) if ${client_name} can't be resolved just temporarily. Suggested by Kari Hurtta of the Finnish Meteorological Institute. CONFIG: Change numbered rulesets into named (which still can be accessed by their numbers). CONFIG: FEATURE(`nouucp') takes one parameter: reject or nospecial which describes whether to disallow "!" in the local part of an address. CONFIG: Call Local_localaddr from localaddr (S5) which can be used to rewrite an address from a mailer which has the F=5 flag set. If the ruleset returns a mailer, the appropriate action is taken, otherwise the returned tokens are ignored. CONFIG: cf/ostype/solaris.m4 has been renamed to solaris2.pre5.m4 and cf/ostype/solaris2.m4 is now a copy of solaris2.ml.m4. The latter is kept around for backward compatibility. CONFIG: Allow ":D.S.N:" for mailer/virtusertable "error:" entries, where "D.S.N" is an RFC 1893 compliant error code. CONFIG: Use /usr/lbin as confEBINDIR for Compaq Tru64 (Digital UNIX). CONFIG: Remove second space between username and date in UNIX From_ line. Noted by Allan E Johannesen of Worcester Polytechnic Institute. CONFIG: Make sure all of the mailers have complete T= equates. CONFIG: Extend FEATURE(`local_procmail') so it can now take arguments overriding the mailer program, arguments, and mailer definition flags. This makes it possible to use other programs such as maildrop for local delivery. CONFIG: Emit warning if FEATURE(`local_lmtp') or FEATURE(`local_procmail') is given after MAILER(`local'). Patch from Richard A. Nelson of IBM. CONFIG: Add SMTP Authentication information to Received: header default value (confRECEIVED_HEADER). CONFIG: Remove `l' flag from USENET_MAILER_FLAGS as it is not a local mailer. Problem noted by Per Hedeland of Ericsson. CONTRIB: Added bounce-resender.pl from Brian R. Gaeke of the University of California at Berkeley. CONTRIB: Added domainmap.m4 from Mark D. Roth of the University of Illinois at Urbana-Champaign. CONTRIB: etrn.pl now recognizes bogus host names. Patch from Bruce Barnett of GE's R&D Lab. CONTRIB: Patches for re-mqueue.pl by Graeme Hewson of Oracle Corporation UK. CONTRIB: Added qtool.pl to assist in managing the queues. DEVTOOLS: Prevent user environment variables from interfering with the Build scripts. Problem noted by Ezequiel H. Panepucci of Yale University. DEVTOOLS: 'Build -M' will display the obj.* directory which will be used for building. DEVTOOLS: 'Build -A' will display the architecture that would be used for a fresh build. DEVTOOLS: New variable confRANLIB, set automatically by configure.sh. DEVTOOLS: New variable confRANLIBOPTS for the options to send to ranlib. DEVTOOLS: 'Build -O ' will have the object files build in /obj.*. Suggested by Bryan Costales of Exactis. DEVTOOLS: New variable confNO_MAN_BUILD which will prevent the building of the man pages when defined. Suggested by Bryan Costales. DEVTOOLS: New variables confNO_HELPFILE_INSTALL and confNO_STATISTICS_INSTALL which will prevent the installation of the sendmail helpfile and statistics file respectively. Suggested by Bryan Costales. DEVTOOLS: Recognize ReliantUNIX as SINIX. Patch from Gerald Rinske of Siemens Business Services. DEVTOOLS: New variable confSTDIO_TYPE which defines the type of stdio library. The new buffered file I/O depends on the Torek stdio library. This option can be either portable or torek. DEVTOOLS: New variables confSRCADD and confSMSRCADD which correspond to confOBJADD and confSMOBJADD respectively. They should contain the C source files for the object files listed in confOBJADD and confSMOBJADD. These file names will be passed to the 'make depend' stage of compilation. DEVTOOLS: New program specific variables for each of the programs in the sendmail distribution. Each has the form `conf_prog_ENVDEF', for example, `conf_sendmail_ENVDEF'. The new variables are conf_prog_ENVDEF, conf_prog_LIBS, conf_prog_SRCADD, and conf_prog_OBJADD. DEVTOOLS: Build system redesign. This should have little affect on building the distribution, but documentation on the changes are in devtools/README. DEVTOOLS: Don't allow 'Build -f file' if an object directory already exists. Suggested by Valdis Kletnieks of Virginia Tech. DEVTOOLS: Rename confSRCDIR to confSMSRCDIR since it only identifies the path to the sendmail source directory. confSRCDIR is a new variable which identifies the root of the source directories for all of the programs in the distribution. DEVTOOLS: confSRCDIR and confSMSRCDIR are now determined at Build time. They can both still be overridden by setting the m4 macro. DEVTOOLS: confSBINGRP now defaults to bin instead of kmem. DEVTOOLS: 'Build -Q prefix' uses devtools/Site/prefix.*.m4 for build configurations, and places objects in obj.prefix.*/. Complains as 'Build -f file' does for existing object directories. Suggested by Tom Smith of Digital Equipment Corporation. DEVTOOLS: Setting confINSTALL_RAWMAN will install unformatted manual pages in the directory tree specified by confMANROOTMAN. DEVTOOLS: If formatting the manual pages fails, copy in the preformatted pages from the distribution. The new variable confCOPY specifies the copying program. DEVTOOLS: Defining confFORCE_RMAIL will install rmail without question. Suggested by Terry Lambert of Whistle Communications. DEVTOOLS: confSTFILE and confHFFILE can be used to change the names of the installed statistics and help files, respectively. DEVTOOLS: Remove spaces in `uname -r` output when determining operating system identity. Problem noted by Erik Wachtenheim of Dartmouth College. DEVTOOLS: New variable confLIBSEARCHPATH to specify the paths that will be search for the libraries specified in confLIBSEARCH. Defaults to "/lib /usr/lib /usr/shlib". DEVTOOLS: New variables confSTRIP and confSTRIPOPTS for specifying how to strip binaries. These are used by the new install-strip target. DEVTOOLS: New config file site.post.m4 which is included after the others (if it exists). DEVTOOLS: Change order of LIBS: first product specific libraries then the default ones. MAIL.LOCAL: Will not be installed set-user-ID root. To use mail.local as local delivery agent without LMTP mode, use MODIFY_MAILER_FLAGS(`LOCAL', `+S') to set the S flag. MAIL.LOCAL: Do not reject addresses which would otherwise be accepted by sendmail. Suggested by Neil Rickert of Northern Illinois University. MAIL.LOCAL: New -7 option which causes LMTP mode not to advertise 8BITMIME in the LHLO response. Suggested by Kari Hurtta of the Finnish Meteorological Institute. MAIL.LOCAL: Add support for the maillock() routines by defining MAILLOCK when compiling. Also requires linking with -lmail. Patch from Neil Rickert of Northern Illinois University. MAIL.LOCAL: Create a Content-Length: header if CONTENTLENGTH is defined when compiling. Automatically set for Solaris 2.3 and later. Patch from Neil Rickert of Northern Illinois University. MAIL.LOCAL: Move the initialization of the 'notifybiff' address structure to the beginning of the program. This ensures that the getservbyname() is done before any seteuid to a possibly unauthenticated user. If you are using NIS+ and secure RPC on a Solaris system, this avoids syslog messages such as, "authdes_refresh: keyserv(1m) is unable to encrypt session key." Patch from Neil Rickert of Northern Illinois University. MAIL.LOCAL: Support group writable mail spool files when MAILGID is set to the gid to use (-DMAILGID=6) when compiling. Patch from Neil Rickert of Northern Illinois University. MAIL.LOCAL: When a mail message included lines longer than 2046 characters (in LMTP mode), mail.local split the incoming line up into 2046-character output lines (excluding the newline). If an input line was 2047 characters long (excluding CR-LF) and the last character was a '.', mail.local saw it as the end of input, transfered it to the user mailbox and tried to write an `ok' back to sendmail. If the message was much longer, both sendmail and mail.local would deadlock waiting for each other to read what they have written. Problem noted by Peter Jeremy of Alcatel Australia Limited. MAIL.LOCAL: New option -b to return a permanent error instead of a temporary error if a mailbox exceeds quota. Suggested by Neil Rickert of Northern Illinois University. MAIL.LOCAL: The creation of a lockfile is subject to a global timeout to avoid starvation. MAIL.LOCAL: Properly parse addresses with multiple quoted local-parts. Problem noted by Ronald F. Guilmette of Infinite Monkeys & Co. MAIL.LOCAL: NCR MP/RAS 3.X portability from Tom J. Moore of NCR. MAILSTATS: New -p option to invoke program mode in which stats are printed in a machine readable fashion and the stats file is reset. Patch from Kevin Hildebrand of the University of Maryland. MAKEMAP: If running as root, automatically change the ownership of generated maps to the TrustedUser as specified in the sendmail configuration file. MAKEMAP: New -C option to accept an alternate sendmail configuration file to use for finding the TrustedUser option. MAKEMAP: New -u option to dump (unmap) a database. Based on code contributed by Roy Mongiovi of Georgia Tech. MAKEMAP: New -e option to allow empty values. Suggested by Philip A. Prindeville of Enteka Enterprise Technology Services. MAKEMAP: Compile cleanly on 64-bit operating systems. Problem noted by Gerald Rinske of Siemens Business Services. OP.ME: Correctly document interaction between F=S and U= mailer equates. Problem noted by Bob Halley of Internet Engines. OP.ME: Fixup Timeout documentation. From Graeme Hewson of Oracle Corporation UK. OP.ME: The Timeout [r] option was incorrectly listed as "safe" (e.g., sendmail would not drop root privileges if the option was specified on the command line). Problem noted by Todd C. Miller of Courtesan Consulting. PRALIASES: Handle the hash and btree map specifications for Berkeley DB. Patch from Brian J. Coan of the Institute for Global Communications. PRALIASES: Read the sendmail.cf file for the location(s) of the alias file(s) if the -f option is not used. Patch from John Beck of Sun Microsystems. PRALIASES: New -C option to specify an alternate sendmail configuration file to use for finding alias file(s). Patch from John Beck of Sun Microsystems. SMRSH: allow shell commands echo, exec, and exit. Allow command lists using || and &&. Based on patch from Brian J. Coan of the Institute for Global Communications. SMRSH: Update README for the new Build system. From Tim Pierce of RootsWeb Genealogical Data Cooperative. VACATION: Added vacation auto-responder to sendmail distribution. LIBSMDB: Added abstracted database library. Works with Berkeley DB 1.85, Berkeley DB 2.X, Berkeley DB 3.X, and NDBM. Changed Files: The Build script in the various program subdirectories are no longer symbolic links. They are now scripts which execute the actual Build script in devtools/bin. All the manual pages are now written against -man and not -mandoc as they were previously. Add a simple Makefile to every directory so make instead of Build will work (unless parameters are required for Build). New Directories: devtools/M4/UNIX include libmilter libsmdb libsmutil vacation Renamed Directories: BuildTools => devtools src => sendmail Deleted Files: cf/m4/nullrelay.m4 devtools/OS/Linux.ppc devtools/OS/ReliantUNIX devtools/OS/SINIX sendmail/ldap_map.h New Files: INSTALL PGPKEYS cf/cf/generic-linux.cf cf/cf/generic-linux.mc cf/feature/delay_checks.m4 cf/feature/dnsbl.m4 cf/feature/generics_entire_domain.m4 cf/feature/no_default_msa.m4 cf/feature/relay_mail_from.m4 cf/feature/virtuser_entire_domain.m4 cf/mailer/qpage.m4 cf/ostype/bsdi.m4 cf/ostype/hpux11.m4 cf/ostype/openbsd.m4 contrib/bounce-resender.pl contrib/domainmap.m4 contrib/qtool.8 contrib/qtool.pl devtools/M4/depend/AIX.m4 devtools/M4/list.m4 devtools/M4/string.m4 devtools/M4/subst_ext.m4 devtools/M4/switch.m4 devtools/OS/Darwin devtools/OS/GNU devtools/OS/SINIX.5.43 devtools/OS/SINIX.5.44 devtools/OS/m88k devtools/bin/find_in_path.sh mail.local/Makefile mailstats/Makefile makemap/Makefile praliases/Makefile rmail/Makefile sendmail/Makefile sendmail/bf.h sendmail/bf_portable.c sendmail/bf_portable.h sendmail/bf_torek.c sendmail/bf_torek.h sendmail/shmticklib.c sendmail/statusd_shm.h sendmail/timers.c sendmail/timers.h smrsh/Makefile vacation/Makefile Renamed Files: cf/ostype/gnuhurd.m4 => cf/ostype/gnu.m4 sendmail/cdefs.h => include/sendmail/cdefs.h sendmail/sendmail.hf => sendmail/helpfile sendmail/mailstats.h => include/sendmail/mailstats.h sendmail/pathnames.h => include/sendmail/pathnames.h sendmail/safefile.c => libsmutil/safefile.c sendmail/snprintf.c => libsmutil/snprintf.c sendmail/useful.h => include/sendmail/useful.h cf/ostype/solaris2.m4 => cf/ostype/solaris2.pre5.m4 Copied Files: cf/ostype/solaris2.ml.m4 => cf/ostype/solaris2.m4 8.9.3/8.9.3 1999/02/04 SECURITY: Limit message headers to a maximum of 32K bytes (total of all headers in a single message) to prevent a denial of service attack. This limit will be configurable in 8.10. Problem noted by Michal Zalewski of the "Internet for Schools" project (IdS). Prevent segmentation fault on an LDAP lookup if the LDAP map was closed due to an earlier failure. Problem noted by Jeff Wasilko of smoe.org. Fix from Booker Bense of Stanford University and Per Hedeland of Ericsson. Preserve the order of the MIME headers in multipart messages when performing the MIME header length check. This will allow PGP signatures to function properly. Problem noted by Lars Hecking of University College, Cork, Ireland. If ruleset 5 rewrote the local address to an :include: directive, the delivery would fail with an "aliasing/forwarding loop broken" error. Problem noted by Eric C Hagberg of Morgan Stanley. Fix from Per Hedeland of Ericsson. Allow -T to work for bestmx maps. Fix from Aaron Schrab of ExecPC Internet Systems. During the transfer of a message in an SMTP transaction, if a TCP timeout occurs, the message would be properly queued for later retry but the failure would be logged as "Illegal Seek" instead of a timeout. Problem noted by Piotr Kucharski of the Warsaw School of Economics (SGH) and Carles Xavier Munyoz Baldo of CTV Internet. Prevent multiple deliveries on a self-referencing alias if the F=w mailer flag is not set. Problem noted by Murray S. Kucherawy of Concentric Network Corporation and Per Hedeland of Ericsson. Do not strip empty headers but if there is no value and a default is defined in sendmail.cf, use the default. Problem noted by Philip Guenther of Gustavus Adolphus College and Christopher McCrory of Netus, Inc. Don't inherit information about the sender (notably the full name) in SMTP (-bs) mode, since this might be called from inetd. Accept any 3xx reply code in response to DATA command instead of requiring 354. This change will match the wording to be published in the updated SMTP specification from the DRUMS group of the IETF. Portability: AIX 4.2.0 or 4.2.1 may become updated by the fileset bos.rte.net level 4.2.0.2. This introduces the softlink /usr/lib/libbind.a which should not be used. It conflicts with the resolver built into libc.a. "bind" has been removed from the confLIBSEARCH BuildTools variable. Users who have installed BIND 8.X will have to add it back in their site.config.m4 file. Problem noted by Ole Holm Nielsen of the Technical University of Denmark. CRAY TS 10.0.x from Sven Nielsen of San Diego Supercomputer Center. Improved LDAP version 3 integration based on input from Kurt D. Zeilenga of the OpenLDAP Foundation, John Beck of Sun Microsystems, and Booker Bense of Stanford University. Linux doesn't have a standard way to get the timezone between different releases. Back out the change in 8.9.2 and don't attempt to derive a timezone. Problem reported by Igor S. Livshits of the University of Illinois at Urbana-Champaign and Michael Dickens of Tetranet Communications. Reliant UNIX, the new name for SINIX, from Gert-Jan Looy of Siemens/SNI. SunOS 5.8 from John Beck of Sun Microsystems. CONFIG: SCO UnixWare 2.1 and 7.0 need TZ to get the proper timezone. Problem noted by Petr Lampa of Technical University of Brno. CONFIG: Handle <@bestmx-host:user@otherhost> addressing properly when using FEATURE(bestmx_is_local). Patch from Neil W. Rickert of Northern Illinois University. CONFIG: Properly handle source routed and %-hack addresses on hosts which the mailertable remaps to local:. Patch from Neil W. Rickert of Northern Illinois University. CONFIG: Internal fixup of mailertable local: map value. Patch from Larry Parmelee of Cornell University. CONFIG: Only add back +detail from host portion of mailer triplet on local mailer triplets if it was originally +detail. Patch from Neil W. Rickert of Northern Illinois University. CONFIG: The bestmx_is_local checking done in check_rcpt would cause later checks to fail. Patch from Paul J Murphy of MIDS Europe. New Files: BuildTools/OS/CRAYTS.10.0.x BuildTools/OS/ReliantUNIX BuildTools/OS/SunOS.5.8 8.9.2/8.9.2 1998/12/30 SECURITY: Remove five second sleep on accepting daemon connections due to an accept() failure. This sleep could be used for a denial of service attack. Do not silently ignore queue files with names which are too long. Patch from Bryan Costales of InfoBeat, Inc. Do not store failures closing an SMTP session in persistent host status. Reported by Graeme Hewson of Oracle Corporation UK. Allow symbolic link forward files if they are in safe directories. Problem noted by Andreas Schott of the Max Planck Society. Missing columns in a text map could cause a segmentation fault. Fix from David Lee of the University of Durham. Note that for 8.9.X, PrivacyOptions=goaway also includes the noetrn flag. This is scheduled to change in a future version of sendmail. Problem noted by Theo Van Dinter of Chrysalis Symbolic Designa and Alan Brown of Manawatu Internet Services. When trying to do host canonification in a Wildcard MX environment, try an MX lookup of the hostname without the default domain appended. Problem noted by Olaf Seibert of Polderland Language & Speech Technology. Reject SMTP RCPT To: commands with only comments (i.e. 'RCPT TO: (comment)'. Problem noted by Earle Ake of Hassler Communication Systems Technology, Inc. Handle any number of %s in the LDAP filter spec. Patch from Per Hedeland of Ericsson. Clear ldapx open timeouts even if the map open failed to prevent a segmentation fault. Patch from Wayne Knowles of the National Institute of Water & Atmospheric Research Ltd. Do not syslog envelope clone messages when using address verification (-bv). Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Continue to perform queue runs while in daemon mode even if the daemon is rejecting connections due to a disk full condition. Problem noted by JR Oldroyd of TerraNet Internet Services. Include full filename on installation of the sendmail.hf file in case the $HFDIR directory does not exist. Problem noted by Josef Svitak of Montana State University. Close all maps when exiting the process with one exception. Berkeley DB can use internal shared memory locking for its memory pool. Closing a map opened by another process will interfere with the shared memory and locks of the parent process leaving things in a bad state. For Berkeley DB, only close the map if the current process is also the one that opened the map, otherwise only close the map file descriptor. Thanks to Yoseff Francus of Collective Technologies for volunteering his system for extended testing. Avoid null pointer dereference on XDEBUG output for SMTP reply failures. Problem noted by Carlos Canau of EUnet Portugal. On mailq and hoststat listings being piped to another program, such as more, if the pipe closes (i.e., the user quits more), stop sending output and exit. Patch from Allan E Johannesen of Worcester Polytechnic Institute. In accordance with the documentation, LDAP map lookup failures are now considered temporary failures instead of permanent failures unless the -t flag is used in the map definition. Problem noted by Booker Bense of Stanford University and Eric C. Hagberg of Morgan Stanley. Fix by one error reporting on long alias names. Problem noted by H. Paul Hammann of the Missouri Research and Education Network. Fix DontBlameSendmail=IncludeFileInUnsafeDirPath behavior. Problem noted by Barry S. Finkel of Argonne National Laboratory. When automatically converting from 8 bit to quoted printable MIME, be careful not to miss a multi-part boundary if that boundary is preceded by a boundary-like line. Problem noted by Andreas Raschle of Ansid Inc. Fix from Kari Hurtta of the Finnish Meteorological Institute. Avoid bogus reporting of "LMTP tobuf overflow" when the buffer has enough space for the additional address. Problem noted by Steve Cliffe of the University of Wollongong. Fix DontBlameSendmail=FileDeliveryToSymlink behavior. Problem noted by Alex Vorobiev of Swarthmore College. If the check_compat ruleset resolves to the $#discard mailer, discard the current recipient. Unlike check_relay, check_mail, and check_rcpt, the entire envelope is not discarded. Problem noted by RZ D. Rahlfs. Fix from Claus Assmann of Christian-Albrechts-University of Kiel. Avoid segmentation fault when reading ServiceSwitchFile files with bogus formatting. Patch from Kari Hurtta of the Finnish Meteorological Institute. Support Berkeley DB 2.6.4 API change. OP.ME: Pages weren't properly output on duplexed printers. Fix from Matthew Black of CSU Long Beach. Portability: Apple Rhapsody from Wilfredo Sanchez of Apple Computer, Inc. Avoid a clash with IRIX 6.2 getopt.h and the UserDatabase option structure. Problem noted by Ashley M. Kirchner of Photo Craft Laboratories, Inc. Break out IP address to hostname translation for reading network interface addresses into class 'w'. Patch from John Kennedy of Cal State University, Chico. AIX 4.x use -qstrict with -O3 to prevent the optimized from changing the semantics of the compiled program. From Simon Travaglia of the University of Waikato, New Zealand. FreeBSD 2.2.2 and later support setusercontext(). From Peter Wemm of DIALix. FreeBSD 3.x fix from Peter Wemm of DIALix. IRIX 5.x has a syslog buffer size of 512 bytes. From Nao NINOMIYA of Utsunomiya University. IRIX 6.5 64-bit Build support. LDAP Version 3 support from John Beck and Ravi Iyer of Sun Microsystems. Linux does not implement seteuid() properly. From John Kennedy of Cal State University, Chico. Linux timezone type was set improperly. From Takeshi Itoh of Bits Co., Ltd. NCR MP-RAS 3.x needs -lresolv for confLIBS. From Tom J. Moore of NCR. NeXT 4.x correction to man page path. From J. P. McCann of E I A. System V Rel 5.x (a.k.a UnixWare7 w/o BSD-Compatibility Libs) from Paul Gampe of the Asia Pacific Network Information Center. ULTRIX now requires an optimization limit of 970 from Allan E Johannesen of Worcester Polytechnic Institute. Fix extern declaration for sm_dopr(). Fix from Henk van Oers of Algemeen Nederlands Persbureau. CONFIG: Catch @hostname,user@anotherhost.domain as relaying. Problem noted by Mark Rogov of AirMedia, Inc. Fix from Claus Assmann of Christian-Albrechts-University of Kiel. CONFIG: Do not refer to http://maps.vix.com/ on RBL rejections as there are multiple RBL's available and the MAPS RBL may not be the one in use. Suggested by Alan Brown of Manawatu Internet Services. CONFIG: Properly strip route addresses (i.e., @host1:user@host2) when stripping down a recipient address to check for relaying. Patch from Claus Assmann of Christian-Albrechts-University of Kiel and Neil W Rickert of Northern Illinois University. CONFIG: Allow the access database to override RBL lookups. Patch from Claus Assmann of Christian-Albrechts-University of Kiel. CONFIG: UnixWare 7 support from Phillip P. Porch of The Porch Dot Com. CONFIG: Fixed check for deferred delivery mode warning. Patch from Claus Assmann of Christian-Albrechts-University of Kiel and Per Hedeland of Ericsson. CONFIG: If a recipient using % addressing is used, e.g. user%site@othersite, and othersite's MX records are now checked for local hosts if FEATURE(relay_based_on_MX) is used. Problem noted by Alexander Litvin of Lucky Net Ltd. Patch from Alexander Litvin of Lucky Net Ltd and Claus Assmann of Christian-Albrechts-University of Kiel. MAIL.LOCAL: Prevent warning messages from appearing in the LMTP stream. Do not allow more than one response per recipient. MAIL.LOCAL: Handle routed addresses properly when using LMTP. Fix from John Beck of Sun Microsystems. MAIL.LOCAL: Properly check for CRLF when using LMTP. Fix from John Beck of Sun Microsystems. MAIL.LOCAL: Substitute MAILER-DAEMON for the LMTP empty sender in the envelope From header. MAIL.LOCAL: Accept underscores in hostnames in LMTP mode. Problem noted by Glenn A. Malling of Syracuse University. MAILSTATS: Document msgsrej and msgsdis fields in the man page. Problem noted by Richard Wong of Princeton University. MAKEMAP: Build group list so group writable files are allowed with the -s flag. Problem noted by Curt Sampson of Internet Portal Services, Inc. PRALIASES: Automatically handle alias files created without the NULL byte at the end of the key. Patch from John Beck of Sun Microsystems. PRALIASES: Support Berkeley DB 2.6.4 API change. New Files: BuildTools/OS/IRIX64.6.5 BuildTools/OS/UnixWare.5.i386 cf/ostype/unixware7.m4 contrib/smcontrol.pl src/control.c 8.9.1/8.9.1 1998/07/02 If both an OS specific site configuration file and a generic site.config.m4 file existed, only the latter was used instead of both. Problem noted by Geir Johannessen of the Norwegian University of Science and Technology. Fix segmentation fault while converting 8 bit to 7 bit MIME multipart messages by trying to write to an unopened file descriptor. Fix from Kari Hurtta of the Finnish Meteorological Institute. Do not assume Message: and Text: headers indicate the end of the header area when parsing MIME headers. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Setting the confMAN#SRC Build variable would only effect the installation commands. The man pages would still be built with .0 extensions. Problem noted by Bryan Costales of InfoBeat, Inc. Installation of manual pages didn't honor the DESTDIR environment variable. Problem noted by Bryan Costales of InfoBeat, Inc. If the check_relay ruleset resolved to the discard mailer, messages were still delivered. Problem noted by Mirek Luc of NASK. Mail delivery to files would fail with an Operating System Error if sendmail was not running as root, i.e., RunAsUser was set. Problem noted by Leonard N. Zubkoff of Dandelion Digital. Prevent MinQueueAge from interfering from queued items created in the future, i.e., if the system clock was set ahead and then back. Problem noted by Michael Miller of the University of Natal, Pietermaritzburg. Do not advertise ETRN support in ESTMP EHLO reply if noetrn is set in the PrivacyOptions option. Fix from Ted Rule of Flextech TV. Log invalid persistent host status file lines instead of bouncing the message. Problem noted by David Lindes of DaveLtd Enterprises. Move creation of empty sendmail.st file from installation to compilation. Installation may be done from a read-only mount. Fix from Bryan Costales of InfoBeat, Inc. and Ric Anderson of the Oasis Research Center, Inc. Enforce the maximum number of User Database entries limit. Problem noted by Gary Buchanan of Credence Systems Inc. Allow dead.letter files in root's home directory. Problem noted by Anna Ullman of Sun Microsystems. Program deliveries in forward files could be marked unsafe if any directory listed in the ForwardPath option did not exist. Problem noted by Jorg Bielak of Coastal Web Online. Do not trust the length of the address structure returned by gethostbyname(). Problem noted by Chris Evans of Oxford University. If the SIZE= MAIL From: ESMTP parameter is too large, use the 5.3.4 DSN status code instead of 5.2.2. Similarly, for non-local deliveries, if the message is larger than the mailer maximum message size, use 5.3.4 instead of 5.2.3. Suggested by Antony Bowesman of Fujitsu/TeaWARE Mail/MIME System. Portability: Fix the check for an IP address reverse lookup for use in $&{client_name} on 64 bit platforms. From Gilles Gallot of Institut for Development and Resources in Intensive Scientific computing. BSD-OS uses .0 for man page extensions. From Jeff Polk of BSDI. DomainOS detection for Build. Also, version 10.4 and later ship a unistd.h. Fixes from Takanobu Ishimura of PICT Inc. NeXT 4.x uses /usr/lib/man/cat for its man pages. From J. P. McCann of E I A. SCO 4.X and 5.X include NDBM support. From Vlado Potisk of TEMPEST, Ltd. CONFIG: Do not pass spoofed PTR results through resolver for qualification. Problem noted by Michiel Boland of Digital Valley Internet Professionals; fix from Kari Hurtta of the Finnish Meteorological Institute. CONFIG: Do not try to resolve non-DNS hostnames such as UUCP, BITNET, and DECNET addresses for resolvable senders. Problem noted by Alexander Litvin of Lucky Net Ltd. CONFIG: Work around Sun's broken configuration which sends bounce messages as coming from @@hostname instead of <>. LMTP would not accept @@hostname. OP.ME: Corrections to complex sendmail startup script from Rick Troxel of the National Institutes of Health. RMAIL: Do not install rmail by default, require 'make force-install' as this rmail isn't the same as others. Suggested by Kari Hurtta of the Finnish Meteorological Institute. New Files: BuildTools/OS/DomainOS.10.4 8.9.0/8.9.0 1998/05/19 SECURITY: To prevent users from reading files not normally readable, sendmail will no longer open forward, :include:, class, ErrorHeader, or HelpFile files located in unsafe (i.e., group or world writable) directory paths. Sites which need the ability to override security can use the DontBlameSendmail option. See the README file for more information. SECURITY: Problems can occur on poorly managed systems, specifically, if maps or alias files are in world writable directories. This fixes the change added to 8.8.6 to prevent links in these world writable directories. SECURITY: Make sure ServiceSwitchFile option file is not a link if it is in a world writable directory. SECURITY: Never pass a tty to a mailer -- if a mailer can get at the tty it may be able to push bytes back to the senders input. Unfortunately this breaks -v mode. Problem noted by Wietse Venema of the Global Security Analysis Lab at IBM T.J. Watson Research. SECURITY: Empty group list if DontInitGroups is set to true to prevent program deliveries from picking up extra group privileges. Problem reported by Wolfgang Ley of DFN-CERT. SECURITY: The default value for DefaultUser is now set to the uid and gid of the first existing user mailnull, sendmail, or daemon that has a non-zero uid. If none of these exist, sendmail reverts back to the old behavior of using uid 1 and gid 1. This is a security problem for Linux which has chosen that uid and gid for user bin instead of daemon. If DefaultUser is set in the configuration file, that value overrides this default. SECURITY: Since 8.8.7, the check for non-set-user-ID binaries interfered with setting an alternate group id for the RunAsUser option. Problem noted by Randall Winchester of the University of Maryland. Add support for Berkeley DB 2.X. Based on patch from John Kennedy of Cal State University, Chico. Remove support for OLD_NEWDB (pre-1.5 version of Berkeley DB). Users which previously defined OLD_NEWDB=1 must now upgrade to the current version of Berkeley DB. Added support for regular expressions using the new map class regex. From Jan Krueger of Unix-AG of University of Hannover. Support for BIND 8.1.1's hesiod for hesiod maps and hesiod UserDatabases from Randall Winchester of the University of Maryland. Allow any shell for user shell on program deliveries on V1 configurations for backwards compatibility on machines which do not have getusershell(). Fix from John Beck of Sun Microsystems. On operating systems which change the process title by reusing the argument vector memory, sendmail could corrupt memory if the last argument was either "-q" or "-d". Problem noted by Frank Langbein of the University of Stuttgart. Support Local Mail Transfer Protocol (LMTP) between sendmail and mail.local on the F=z flag. Macro-expand the contents of the ErrMsgFile. Previously this was only done if you had magic characters (0x81) to indicate macro expansion. Now $x will be expanded. This means that real dollar signs have to be backslash escaped. TCP Wrappers expects "unknown" in the hostname argument if the reverse DNS lookup for the incoming connection fails. Problem noted by Randy Grimshaw of Syracuse University and Wietse Venema of the Global Security Analysis Lab at IBM T.J. Watson Research. DSN success bounces generated from an invocation of sendmail -t would be sent to both the sender and MAILER-DAEMON. Problem noted by Claus Assmann of Christian-Albrechts-University of Kiel. Avoid "Error 0" messages on delivery mailers which exit with a valid exit value such as EX_NOPERM. Fix from Andreas Luik of ISA Informationssysteme GmbH. Tokenize $&x expansions on right hand side of rules. This eliminates the need to use tricks like $(dequote "" $&{client_name} $) to cause the ${client_name} macro to be properly tokenized. Add the MaxRecipientsPerMessage option: this limits the number of recipients that will be accepted in a single SMTP transaction. After this number is reached, sendmail starts returning "452 Too many recipients" to all RCPT commands. This can be used to limit the number of recipients per envelope (in particular, to discourage use of the server for spamming). Note: a better approach is to restrict relaying entirely. Fixed pointer initialization for LDAP lmap struct, fixed -s option to ldapx map and added timeout for ldap_open call to avoid hanging sendmail in the event of hung LDAP servers. Patch from Booker Bense of Stanford University. Allow multiple -qI, -qR, or -qS queue run limiters. For example, '-qRfoo -qRbar' would deliver mail to recipients with foo or bar in their address. Patch from Allan E Johannesen of Worcester Polytechnic Institute. The bestmx map will now return a list of the MX servers for a host if passed a column delimiter via the -z map flag. This can be used to check if the server is an MX server for the recipient of a message. This can be used to help prevent relaying. Patch from Mitchell Blank Jr of Exec-PC. Mark failures for the *file* mailer and return bounce messages to the sender for those failures. Prevent bogus syslog timestamps on errors in sendmail.cf by preserving the TZ environment variable until TimeZoneSpec has been determined. Problem noted by Ralf Hildebrandt of Technical University of Braunschweig. Patch from Per Hedeland of Ericsson. Print test input in address test mode when input is not from the tty when the -v flag is given (i.e., sendmail -bt -v) to make output easier to decipher. Problem noted by Aidan Nichol of Procter & Gamble. The LDAP map -s flag was not properly parsed and the error message given included the remainder of the arguments instead of solely the argument in error. Problem noted by Aidan Nichol of Procter & Gamble. New DontBlameSendmail option. This option allows administrators to bypass some of sendmail's file security checks at the expense of system security. This should only be used if you are absolutely sure you know the consequences. The available DontBlameSendmail options are: Safe AssumeSafeChown ClassFileInUnsafeDirPath ErrorHeaderInUnsafeDirPath GroupWritableDirPathSafe GroupWritableForwardFileSafe GroupWritableIncludeFileSafe GroupWritableAliasFile HelpFileinUnsafeDirPath WorldWritableAliasFile ForwardFileInGroupWritableDirPath IncludeFileInGroupWritableDirPath ForwardFileInUnsafeDirPath IncludeFileInUnsafeDirPath ForwardFileInUnsafeDirPathSafe IncludeFileInUnsafeDirPathSafe MapInUnsafeDirPath LinkedAliasFileInWritableDir LinkedClassFileInWritableDir LinkedForwardFileInWritableDir LinkedIncludeFileInWritableDir LinkedMapInWritableDir LinkedServiceSwitchFileInWritableDir FileDeliveryToHardLink FileDeliveryToSymLink WriteMapToHardLink WriteMapToSymLink WriteStatsToHardLink WriteStatsToSymLink RunProgramInUnsafeDirPath RunWritableProgram New DontProbeInterfaces option to turn off the inclusion of all the interface names in $=w on startup. In particular, if you have lots of virtual interfaces, this option will speed up startup. However, unless you make other arrangements, mail sent to those addresses will be bounced. Automatically create alias databases if they don't exist and AutoRebuildAliases is set. Add PrivacyOptions=noetrn flag to disable the SMTP ETRN command. Suggested by Christophe Wolfhugel of the Institut Pasteur. Add PrivacyOptions=noverb flag to disable the SMTP VERB command. When determining the client host name ($&{client_name} macro), do a forward (A) DNS lookup on the result of the PTR lookup and compare results. If they differ or if the PTR lookup fails, &{client_name} will contain the IP address surrounded by square brackets (e.g., [127.0.0.1]). New map flag: -Tx appends "x" to lookups that return temporary failure (i.e, it is like -ax for the temporary failure case, in contrast to the success case). New syntax to do limited checking of header syntax. A config line of the form: HHeader: $>Ruleset causes the indicated Ruleset to be invoked on the Header when read. This ruleset works like the check_* rulesets -- that is, it can reject mail on the basis of the contents. Limit the size of the HELO/EHLO parameter to prevent spammers from hiding their connection information in Received: headers. When SingleThreadDelivery is active, deliveries to locked hosts are skipped. This will cause the delivering process to try the next MX host or queue the message if no other MX hosts are available. Suggested by Alexander Litvin. The [FILE] mailer type now delivers to the file specified in the A= equate of the mailer definition instead of $u. It also obeys all of the F= mailer flags such as the MIME 7/8 bit conversion flags. This is useful for defining a mailer which delivers to the same file regardless of the recipient (e.g., 'A=FILE /dev/null' to discard unwanted mail). Do not assume the identity of a remote connection is root@localhost if the remote connection closes the socket before the remote identity can be queried. Change semantics of the F=S mailer flag back to 8.7.5 behavior. Some mailers, including procmail, require that the real uid is left unchanged by sendmail. Problem noted by Per Hedeland of Ericsson. No longer is the src/obj*/Makefile selected from a large list -- it is now generated using the information in BuildTools/OS/ -- some of the details are determined dynamically via BuildTools/bin/configure.sh. The other programs in the sendmail distribution -- mail.local, mailstats, makemap, praliases, rmail, and smrsh -- now use the new Build method which creates an operating system specific Makefile using the information in BuildTools. Make 4xx reply codes to the SMTP MAIL command be non-sticky (i.e., a failure on one message won't affect future messages to the same host). This is necessary if the remote host sends a 451 error if the domain of the sender does not resolve as is common in anti-spam configurations. Problem noted by Mitchell Blank Jr of Exec-PC. New "discard" mailer for check_* rulesets and header checking rulesets. If one of the above rulesets resolves to the $#discard mailer, the commands will be accepted but the message will be completely discarded after it is accepting. This means that even if only one of the recipients resolves to the $#discard mailer, none of the recipients will receive the mail. Suggested by Brian Kantor. All but the last cloned envelope of a split envelope were queued instead of being delivered. Problem noted by John Caruso of CNET: The Computer Network. Fix deadlock situation in persistent host status file locking. Syslog an error if a user forward file could not be read due to an error. Patch from John Beck of Sun Microsystems. Use the first name returned on machine lookups when canonifying a hostname via NetInfo. Patch from Timm Wetzel of GWDG. Clear the $&{client_addr}, $&{client_name}, and $&{client_port} macros when delivering a bounce message to prevent rejection by a check_compat ruleset which uses these macros. Problem noted by Jens Hamisch of AgiX Internetservices GmbH. If the check_relay ruleset resolves to the the error mailer, the error in the $: portion of the resolved triplet is used in the rejection message given to the remote machine. Suggested by Scott Gifford of The Internet Ramp. Set the $&{client_addr}, $&{client_name}, and $&{client_port} macros before calling the check_relay ruleset. Suggested by Scott Gifford of The Internet Ramp. Sendmail would get a segmentation fault if a mailer exited with an exit code of 79. Problem noted by Aaron Schrab of ExecPC Internet. Fix from Christophe Wolfhugel of the Pasteur Institute. Separate snprintf/vsnprintf routines into separate file for use by mail.local. Allow multiple map lookups on right hand side, e.g., R$* $( host $1 $) $| $( passwd $1 $). Patch from Christophe Wolfhugel of the Pasteur Institute. Properly generate success DSN messages if requested for aliases which have owner- aliases. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Properly display delayed-expansion macros ($&{macroname}) in address test mode (-bt). Problem noted by Bryan Costales of InfoBeat, Inc. -qR could sometimes match names incorrectly. Problem noted by Lutz Euler of Lavielle EDV Systemberatung GmbH & Co. Include a magic number and version in the StatusFile for the mailstats command. Record the number of rejected and discarded messages in the StatusFile for display by the mailstats command. Patch from Randall Winchester of the University of Maryland. IDENT returns where the OSTYPE field equals "OTHER" now list the user portion as IDENT:username@site instead of username@site to differentiate the two. Suggested by Kari Hurtta of the Finnish Meteorological Institute. Enforce timeout for LDAP queries. Patch from Per Hedeland of Ericsson. Change persistent host status filename substitution so '/' is replaced by ':' instead of '|' to avoid clashes. Also avoid clashes with hostnames with leading dots. Fix from Mitchell Blank Jr. of Exec-PC. If the system lock table is full, only attempt to create a new queue entry five times before giving up. Previously, it was attempted indefinitely which could cause the partition to run out of inodes. Problem noted by Suzie Weigand of Stratus Computer, Inc. In verbose mode, warn if the sendmail.cf version is less than the currently supported version. Sorting for QueueSortOrder=host is now case insensitive. Patch from Randall S. Winchester of the University of Maryland. Properly quote a full name passed via the -F command line option, the Full-Name: header, or the NAME environment variable if it contains characters which must be quoted. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. Avoid possible race condition that unlocked a mail job before releasing the transcript file on systems that use flock(2). In some cases, this might result in a "Transcript Unavailable" message in error bounces. Accept SMTP replies which contain only a reply code and no accompanying text. Problem noted by Fernando Fraticelli of Digital Equipment Corporation. Portability: AIX 4.1 uses int for SOCKADDR_LEN_T from Motonori Nakamura of Kyoto University. AIX 4.2 requires before . Patch from Randall S. Winchester of the University of Maryland. AIX 4.3 from Valdis Kletnieks of Virginia Tech CNS. CRAY T3E from Manu Mahonen of Center for Scientific Computing in Finland. Digital UNIX now uses statvfs for determining free disk space. Patch from Randall S. Winchester of the University of Maryland. HP-UX 11.x from Richard Allen of Opin Kerfi HF and Regis McEwen of Progress Software Corporation. IRIX 64 bit fixes from Kari Hurtta of the Finnish Meteorological Institute. IRIX 6.2 configuration fix for mail.local from Michael Kyle of CIC/Advanced Computing Laboratory. IRIX 6.5 from Thomas H Jones II of SGI. IRIX 6.X load average code from Bob Mende of SGI. QNX from Glen McCready . SCO 4.2 and 5.x use /usr/bin instead of /usr/ucb for links to sendmail. Install with group bin instead of kmem as kmem does not exist. From Guillermo Freige of Gobernacion de la Pcia de Buenos Aires and Paul Fischer of BTG, Inc. SunOS 4.X does not include memmove(). Patch from Per Hedeland of Ericsson. SunOS 5.7 includes getloadavg() function for determining load average. Patch from John Beck of Sun Microsystems. CONFIG: Increment version number of config file. CONFIG: add DATABASE_MAP_TYPE to set the default type of database map for the various maps. The default is hash. Patch from Robert Harker of Harker Systems. CONFIG: new confEBINDIR m4 variable for defining the executable directory for certain programs. CONFIG: new FEATURE(local_lmtp) to use the new LMTP support for local mail delivery. By the default, /usr/libexec/mail.local is used. This is expected to be the mail.local shipped with 8.9 which is LMTP capable. The path is based on the new confEBINDIR m4 variable. CONFIG: Use confEBINDIR in determining path to smrsh for FEATURE(smrsh). Note that this changes the default from /usr/local/etc/smrsh to /usr/libexec/smrsh. To obtain the old path for smrsh, use FEATURE(smrsh, /usr/local/etc/smrsh). CONFIG: DOMAIN(generic) changes the default confFORWARD_PATH to include $z/.forward.$w+$h and $z/.forward+$h which allow the user to setup different .forward files for user+detail addressing. CONFIG: add confMAX_RCPTS_PER_MESSAGE, confDONT_PROBE_INTERFACES, and confDONT_BLAME_SENDMAIL to set MaxRecipientsPerMessage, DontProbeInterfaces, and DontBlameSendmail options. CONFIG: by default do not allow relaying (that is, accepting mail from outside your domain and sending it to another host outside your domain). CONFIG: new FEATURE(promiscuous_relay) to allow mail relaying from any site to any site. CONFIG: new FEATURE(relay_entire_domain) allows any host in your domain as defined by the 'm' class ($=m) to relay. CONFIG: new FEATURE(relay_based_on_MX) to allow relaying based on the MX records of the host portion of an incoming recipient. CONFIG: new FEATURE(access_db) which turns on the access database feature. This database gives you the ability to allow or refuse to accept mail from specified domains for administrative reasons. By default, names that are listed as "OK" in the access db are domain names, not host names. CONFIG: new confCR_FILE m4 variable for defining the name of the file used for class 'R'. Defaults to /etc/mail/relay-domains. CONFIG: new command RELAY_DOMAIN(domain) and RELAY_DOMAIN_FILE(file) to add items to class 'R' ($=R) for hosts allowed to relay. CONFIG: new FEATURE(relay_hosts_only) to change the behavior of FEATURE(access_db) and class 'R' to lookup individual host names only. CONFIG: new FEATURE(loose_relay_check). Normally, if a recipient using % addressing is used, e.g. user%site@othersite, and othersite is in class 'R', the check_rcpt ruleset will strip @othersite and recheck user@site for relaying. This feature changes that behavior. It should not be needed for most installations. CONFIG: new FEATURE(relay_local_from) to allow relaying if the domain portion of the mail sender is a local host. This should only be used if absolutely necessary as it opens a window for spammers. Patch from Randall S. Winchester of the University of Maryland. CONFIG: new FEATURE(blacklist_recipients) turns on the ability to block incoming mail destined for certain recipient usernames, hostnames, or addresses. CONFIG: By default, MAIL FROM: commands in the SMTP session will be refused if the host part of the argument to MAIL FROM: cannot be located in the host name service (e.g., DNS). CONFIG: new FEATURE(accept_unresolvable_domains) accepts unresolvable hostnames in MAIL FROM: SMTP commands. CONFIG: new FEATURE(accept_unqualified_senders) accepts MAIL FROM: senders which do not include a domain. CONFIG: new FEATURE(rbl) Turns on rejection of hosts found in the Realtime Blackhole List. You can specify the RBL name server to contact by specifying it as an optional argument. The default is rbl.maps.vix.com. For details, see http://maps.vix.com/rbl/. CONFIG: Call Local_check_relay, Local_check_mail, and Local_check_rcpt from check_relay, check_mail, and check_rcpt. Users with local rulesets should place the rules using LOCAL_RULESETS. If a Local_check_* ruleset returns $#OK, the message is accepted. If the ruleset returns a mailer, the appropriate action is taken, else the return of the ruleset is ignored. CONFIG: CYRUS_MAILER_FLAGS now includes the /:| mailer flags by default to support file, :include:, and program deliveries. CONFIG: Remove the default for confDEF_USER_ID so the binary can pick the proper default value. See the SECURITY note above for more information. CONFIG: FEATURE(nodns) now warns the user that the feature is a no-op. Patch from Kari Hurtta of the Finnish Meteorological Institute. CONFIG: OSTYPE(osf1) now sets DefaultUserID (confDEF_USER_ID) to daemon since DEC's /bin/mail will drop the envelope sender if run as mailnull. See the Digital UNIX section of src/README for more information. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. CONFIG: .cf files are now stored in the same directory with the .mc files instead of in the obj directory. CONFIG: New options confSINGLE_LINE_FROM_HEADER, confALLOW_BOGUS_HELO, and confMUST_QUOTE_CHARS for setting SingleLineFromHeader, AllowBogusHELO, and MustQuoteChars respectively. MAIL.LOCAL: support -l flag to run LMTP on stdin/stdout. This SMTP-like protocol allows detailed reporting of delivery status on a per-user basis. Code donated by John Myers of CMU (now of Netscape). MAIL.LOCAL: HP-UX support from Randall S. Winchester of the University of Maryland. NOTE: mail.local is not compatible with the stock HP-UX mail format. Be sure to read mail.local/README. MAIL.LOCAL: Prevent other mail delivery agents from stealing a mailbox lock. Patch from Randall S. Winchester of the University of Maryland. MAIL.LOCAL: glibc portability from John Kennedy of Cal State University, Chico. MAIL.LOCAL: IRIX portability from Kari Hurtta of the Finnish Meteorological Institute. MAILSTATS: Display the number of rejected and discarded messages in the StatusFile. Patch from Randall Winchester of the University of Maryland. MAKEMAP: New -s flag to ignore safety checks on database map files such as linked files in world writable directories. MAKEMAP: Add support for Berkeley DB 2.X. Remove OLD_NEWDB support. PRALIASES: Add support for Berkeley DB 2.X. PRALIASES: Do not automatically include NDBM support. Problem noted by Ralf Hildebrandt of the Technical University of Braunschweig. RMAIL: Improve portability for other platforms. Patches from Randall S. Winchester of the University of Maryland and Kari Hurtta of the Finnish Meteorological Institute. Changed Files: src/Makefiles/Makefile.* files have been modified to use the new build mechanism and are now BuildTools/OS/*. src/makesendmail changed to symbolic link to src/Build. New Files: BuildTools/M4/header.m4 BuildTools/M4/depend/BSD.m4 BuildTools/M4/depend/CC-M.m4 BuildTools/M4/depend/NCR.m4 BuildTools/M4/depend/Solaris.m4 BuildTools/M4/depend/X11.m4 BuildTools/M4/depend/generic.m4 BuildTools/OS/AIX.4.2 BuildTools/OS/AIX.4.x BuildTools/OS/CRAYT3E.2.0.x BuildTools/OS/HP-UX.11.x BuildTools/OS/IRIX.6.5 BuildTools/OS/NEXTSTEP.4.x BuildTools/OS/NeXT.4.x BuildTools/OS/NetBSD.8.3 BuildTools/OS/QNX BuildTools/OS/SunOS.5.7 BuildTools/OS/dcosx.1.x.NILE BuildTools/README BuildTools/Site/README BuildTools/bin/Build BuildTools/bin/configure.sh BuildTools/bin/find_m4.sh BuildTools/bin/install.sh Makefile cf/cf/Build cf/cf/generic-hpux10.cf cf/feature/accept_unqualified_senders.m4 cf/feature/accept_unresolvable_domains.m4 cf/feature/access_db.m4 cf/feature/blacklist_recipients.m4 cf/feature/loose_relay_check.m4 cf/feature/local_lmtp.m4 cf/feature/promiscuous_relay.m4 cf/feature/rbl.m4 cf/feature/relay_based_on_MX.m4 cf/feature/relay_entire_domain.m4 cf/feature/relay_hosts_only.m4 cf/feature/relay_local_from.m4 cf/ostype/qnx.m4 contrib/doublebounce.pl mail.local/Build mail.local/Makefile.m4 mail.local/README mailstats/Build mailstats/Makefile.m4 makemap/Build makemap/Makefile.m4 praliases/Build praliases/Makefile.m4 rmail/Build rmail/Makefile.m4 rmail/rmail.0 smrsh/Build smrsh/Makefile.m4 src/Build src/Makefile.m4 src/snprintf.c Deleted Files: cf/cf/Makefile (replaced by Makefile.dist) mail.local/Makefile mail.local/Makefile.dist mailstats/Makefile mailstats/Makefile.dist makemap/Makefile makemap/Makefile.dist praliases/Makefile praliases/Makefile.dist rmail/Makefile smrsh/Makefile smrsh/Makefile.dist src/Makefile src/Makefiles/Makefile.AIX.4 (split into AIX.4.x and AIX.4.2) src/Makefiles/Makefile.SMP_DC.OSx.NILE (renamed BuildTools/OS/dcosx.1.x.NILE) src/Makefiles/Makefile.Utah (obsolete platform) Renamed Files: READ_ME => README cf/cf/Makefile.dist => Makefile cf/cf/obj/* => cf/cf/* src/READ_ME => src/README 8.8.8/8.8.8 1997/10/24 If the check_relay ruleset failed, the relay= field was logged incorrectly. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. If /usr/tmp/dead.letter already existed, sendmail could not add additional bounces to it. Problem noted by Thomas J. Arseneault of SRI International. If an SMTP mailer used a non-standard port number for the outgoing connection, it would be displayed incorrectly in verbose mode. Problem noted by John Kennedy of Cal State University, Chico. Log the ETRN parameter specified by the client before altering them to internal form. Suggested by Bob Kupiec of GES-Verio. EXPN and VRFY SMTP commands on malformed addresses were logging as User unknown with bogus delay= values. Change them to log the same as compliant addresses. Problem noted by Kari E. Hurtta of the Finnish Meteorological Institute. Ignore the debug resolver option unless using sendmail debug trace option for resolver. Problem noted by Greg Nichols of Wind River Systems. If SingleThreadDelivery was enabled and the remote server returned a protocol error on the DATA command, the connection would be closed but the persistent host status file would not be unlocked so other sendmail processes could not deliver to that host. Problem noted by Peter Wemm of DIALix. If queueing up a message due to an expensive mailer, don't increment the number of delivery attempts or set the last delivery attempt time so the message will be delivered on the next queue run regardless of MinQueueAge. Problem noted by Brian J. Coan of the Institute for Global Communications. Authentication warnings of "Processed from queue _directory_" and "Processed by _username_ with -C _filename_" would be logged with the incorrect timestamp. Problem noted by Kari E. Hurtta of the Finnish Meteorological Institute. Use a better heuristic for detecting GDBM. Log null connections on dropped connections. Problem noted by Jon Lewis of Florida Digital Turnpike. If class dbm maps are rebuilt, sendmail will now detect this and reopen the map. Previously, they could give stale results during a single message processing (but would recover when the next message was received). Fix from Joe Pruett of Q7 Enterprises. Do not log failures such as "User unknown" on -bv or SMTP VRFY requests. Problem noted by Kari E. Hurtta of the Finnish Meteorological Institute. Do not send a bounce message back to the sender regarding bad recipients if the SMTP connection is dropped before the message is accepted. Problem noted by Kari E. Hurtta of the Finnish Meteorological Institute. Use "localhost" instead of "[UNIX: localhost]" when connecting to sendmail via a UNIX pipe. This will allow rulesets using $&{client_name} to process without sending the string through dequote. Problem noted by Alan Barrett of Internet Africa. A combination of deferred delivery mode, a double bounce situation, and the inability to save a bounce message to /var/tmp/dead.letter would cause sendmail to send a bounce to postmaster but not remove the offending envelope from the queue causing it to create a new bounce message each time the queue was run. Problem noted by Brad Doctor of Net Daemons Associates. Remove newlines from hostname information returned via DNS. There are no known security implications of newlines in hostnames as sendmail filters newlines in all vital areas; however, this could cause confusing error messages. Starting with sendmail 8.8.6, mail sent with the '-t' option would be rejected if any of the specified addresses were bad. This behavior was modified to only reject the bad addresses and not the entire message. Problem noted by Jozsef Hollosi of SuperNet, Inc. Use Timeout.fileopen when delivering mail to a file. Suggested by Bryan Costales of InfoBeat, Inc. Display the proper Final-Recipient on DSN messages for non-SMTP mailers. Problem noted by Kari E. Hurtta of the Finnish Meteorological Institute. An error in calculating the available space in the list of addresses for logging deliveries could cause an address to be silently dropped. Include the initial user environment if sendmail is restarted via a HUP signal. This will give room for the process title. Problem noted by Jon Lewis of Florida Digital Turnpike. Mail could be delivered without a body if the machine does not support flock locking and runs out of processes during delivery. Fix from Chuck Lever of the University of Michigan. Drop recipient address from 251 and 551 SMTP responses per RFC 821. Problem noted by Kari E. Hurtta of the Finnish Meteorological Institute. Make sure non-rebuildable database maps are opened before the rebuildable maps (i.e., alias files) in case the database maps are needed for verifying the left hand side of the aliases. Problem noted by Lloyd Parkes of Victoria University. Make sure sender RFC822 source route addresses are alias expanded for bounce messages. Problem noted by Juergen Georgi of RUS University of Stuttgart. Minor lint fixes. Return a temporary error instead of a permanent error if an LDAP map search returns an error. This will allow sequenced maps which use other LDAP servers to be checked. Fix from Booker Bense of Stanford University. When automatically converting from quoted printable to 8bit text do not pad bare linefeeds with a space. Problem noted by Theo Nolte of the University of Technology Aachen, Germany. Portability: Non-standard C compilers may have had a problem compiling conf.c due to a standard C external declaration of setproctitle(). Problem noted by Ted Roberts of Electronic Data Systems. AUX: has a broken O_EXCL implementation. Reported by Jim Jagielski of jaguNET Access Services. BSD/OS: didn't compile if HASSETUSERCONTEXT was defined. Digital UNIX: Digital UNIX (and possibly others) moves loader environment variables into the loader memory area. If one of these environment variables (such as LD_LIBRARY_PATH) was the last environment variable, an invalid memory address would be used by the process title routine causing memory corruption. Problem noted by Sam Hartman of Mesa Internet Systems. GNU libc: uses an enum for _PC_CHOWN_RESTRICTED which caused chownsafe() to always return 0 even if the OS does not permit file giveaways. Problem noted by Yasutaka Sumi of The University of Tokyo. IRIX6: Syslog buffer size set to 512 bytes. Reported by Gerald Rinske of Siemens Business Services VAS. Linux: Pad process title with NULLs. Problem noted by Jon Lewis of Florida Digital Turnpike. SCO OpenServer 5.0: SIOCGIFCONF ioctl call returns an incorrect value for the number of interfaces. Problem noted by Chris Loelke of JetStream Internet Services. SINIX: Update for Makefile and syslog buffer size from Gerald Rinske of Siemens Business Services VAS. Solaris: Make sure HASGETUSERSHELL setting for SunOS is not used on a Solaris machine. Problem noted by Stephen Ma of Jtec Pty Limited. CONFIG: SINIX: Update from Gerald Rinske of Siemens Business Services VAS. MAKEMAP: Use a better heuristic for detecting GDBM. CONTRIB: expn.pl: Updated version from the author, David Muir Sharnoff. OP.ME: Document the F=i mailer flag. Problem noted by Per Hedeland of Ericsson. 8.8.7/8.8.7 1997/08/03 If using Berkeley DB on systems without O_EXLOCK (open a file with an exclusive lock already set -- i.e., almost all systems except 4.4-BSD derived systems), the initial attempt at rebuilding aliases file if the database didn't already exist would fail. Patch from Raymund Will of LST Software GmbH. Bogus incoming SMTP commands would reset the SMTP conversation. Problem noted by Fredrik Jönsson of the Royal Institute of Technology, Stockholm. Since TCP Wrappers includes setenv(), unsetenv(), and putenv(), some environments could give "multiple definitions" for these routines during compilation. If using TCP Wrappers, assume that these routines are included as though they were in the C library. Patch from Robert La Ferla. When a NEWDB database map was rebuilt at the same time it was being used by a queue run, the maps could be left locked for the duration of the queue run, causing other processes to hang. Problem noted by Kendall Libby of Shore.NET. In some cases, NoRecipientAction=add-bcc was being ignored, so the mail was passed on without any recipient header. This could cause problems downstream. Problem noted by Xander Jansen of SURFnet ExpertiseCentrum. Give error when GDBM is used with sendmail. GDBM's locking and linking of the .dir and .pag files interferes with sendmail's locking and security checks. Problems noted by Fyodor Yarochkin of the Kyrgyz Republic FreeNet. Don't fsync qf files if SuperSafe option is not set. Avoid extra calls to gethostbyname for addresses for which a gethostbyaddr found no value. Also, ignore any returns from gethostbyaddr that look like a dotted quad. If PTR lookup fails when looking up an SMTP peer, don't tag it as "may be forged", since at the network level we pretty much have to assume that the information is good. In some cases, errors during an SMTP session could leave files open or locked. Better handling of missing file descriptors (0, 1, 2) on startup. Better handling of non-set-user-ID binaries -- avoids certain obnoxious errors during testing. Errors in file locking of NEWDB maps had the incorrect file name printed in the error message. If the AllowBogusHELO option were set and an EHLO with a bad or missing parameter were issued, the EHLO behaved like a HELO. Load limiting never kicked in for incoming SMTP transactions if the DeliveryMode=background and any recipient was an alias or had a .forward file. From Nik Conwell of Boston University. On some non-Posix systems, the decision of whether chown(2) permits file giveaway was undefined. From Tetsu Ushijima of the Tokyo Institute of Technology. Fix race condition that could cause the body of a message to be lost (so only the header was delivered). This only occurs on systems that do not use flock(2), and only when a queue runner runs during a critical section in another message delivery. Based on a patch from Steve Schweinhart of Results Computing. If a qf file was found in a mail queue directory that had a problem (wrong ownership, bad format, etc.) and the file name was exactly MAXQFNAME bytes long, then instead of being tried once, it would be tried on every queue run. Problem noted by Bryan Costales of Mercury Mail. If the system supports an st_gen field in the status structure, include it when reporting that a file has changed after open. This adds a new compile flag, HAS_ST_GEN (0/1 option). This out to be checked as well as reported, since it is theoretically possible for an attacker to remove a file after it is opened and replace it with another file that has the same i-number, but some filesystems (notably AFS) return garbage in this field, and hence always look like the file has changed. As a practical matter this is not a security problem, since the files can be neither hard nor soft links, and on no filesystem (that I am aware of) is it possible to have two files on the same filesystem with the same i-number simultaneously. Delete the root Makefile from the distribution -- it is only for use internally, and does not work at customer sites. Fix botch that caused the second MAIL FROM: command in a single transaction to clear the entire transaction. Problem noted by John Kennedy of Cal State University, Chico. Work properly on machines that have _PATH_VARTMP defined without a trailing slash. (And a pox on vendors that decide to ignore the established conventions!) Problem noted by Gregory Neil Shapiro of WPI. Internal changes to make it easier to add another protocol family (intended for IPv6). Patches are from John Kennedy of CSU Chico. In certain cases, 7->8 bit MIME decoding of Base64 text could leave an extra space at the beginning of some lines. Problem noted by Charles Karney of Princeton University; fix based on a patch from Christophe Wolfhugel. Portability: Allow _PATH_VENDOR_CF to be set in Makefile for consistency with the _Sendmail_ book, 2nd edition. Note that the book is actually wrong: _PATH_SENDMAILCF should be used instead. AIX 3.x: Include . Patch from Gene Rackow of Argonne National Laboratory. OpenBSD from from Paul DuBois of the University of Wisconsin. RISC/os 4.0 from Paul DuBois of the University of Wisconsin. SunOS: Include to fix warning from util.c. From James Aldridge of EUnet Ltd. Solaris: Change STDIR (location of status file) to /etc/mail in Makefiles. Linux, Dynix, UNICOS: Remove -DNDBM and -lgdbm from Makefiles. Use NEWDB on Linux instead. NCR MP-RAS 3.x with STREAMware TCP/IP: SIOCGIFNUM ioctl exists but behaves differently than other OSes. Add SIOCGIFNUM_IS_BROKEN compile flag to get around the problem. Problem noted by Tom Moore of NCR Corp. HP-UX 9.x: fix compile warnings for old select API. Problem noted by Tom Smith of Digital Equipment Corp. UnixWare 2.x: compile warnings on offsetof macro. Problem noted by Tom Good of the Community Access Information Resource Network SCO 4.2: compile problems caused by a change in the type of the "length" parameters passed to accept, getpeername, getsockname, and getsockopt. Adds new compile flags SOCKADDR_SIZE_T and SOCKOPT_SIZE_T. Problem reported by Tom Good of St. Vincent's North Richmond Community Mental Health Center Residential Services. AIX 4: Use size_t for SOCKADDR_SIZE_T and SOCKOPT_SIZE_T. Suggested by Brett Hogden of Rochester Gas & Electric Corp. Linux: avoid compile problem for versions of that #define both setjmp and longjmp. Problem pointed out by J.R. Oldroyd of TerraNet. CONFIG: SCO UnixWare 2.1: Support for OSTYPE(sco-uw-2.1) from Christopher Durham of SCO. CONFIG: NEXTSTEP: define confCW_FILE to /etc/sendmail/sendmail.cw to match the usual configuration. Patch from Dennis Glatting of PlainTalk. CONFIG: MAILER(fax) called a program that hasn't existed for a long time. Convert to use the HylaFAX 4.0 conventions. Suggested by Harry Styron. CONFIG: Improve sample anti-spam rulesets in cf/cf/knecht.mc. These are the rulesets in use on sendmail.org. MAKEMAP: give error on GDBM files. MAIL.LOCAL: Make error messages a bit more explicit, for example, telling more details on what actually changed when "file changed after open". CONTRIB: etrn.pl: Ignore comments in Fw files. Support multiple Fw files. CONTRIB: passwd-to-alias.pl: Handle 8 bit characters and '-'. NEW FILES: src/Makefiles/Makefile.OpenBSD src/Makefiles/Makefile.RISCos.4_0 test/t_exclopen.c cf/ostype/sco-uw-2.1.m4 DELETED FILES: Makefile 8.8.6/8.8.6 1997/06/14 ************************************************************* * The extensive assistance of Gregory Neil Shapiro of WPI * * in preparing this release is gratefully appreciated. * * Sun Microsystems has also provided resources toward * * continued sendmail development. * ************************************************************* SECURITY: A few systems allow an open with the O_EXCL|O_CREAT open mode bits set to create a file that is a symbolic link that points nowhere. This makes it possible to create a root owned file in an arbitrary directory by inserting the symlink into a writable directory after the initial lstat(2) check determined that the file did not exist. The only verified example of a system having these odd semantics for O_EXCL and symbolic links was HP-UX prior to version 9.07. Most systems do not have the problem, since a exclusive create of a file disallows symbolic links. Systems that have been verified to NOT have the problem include AIX 3.x, *BSD, DEC OSF/1, HP-UX 9.07 and higher, Linux, SunOS, Solaris, and Ultrix. This is a potential exposure on systems that have this bug and which do not have a MAILER-DAEMON alias pointing at a legitimate account, since this will cause old mail to be dropped in /var/tmp/dead.letter. SECURITY: Problems can occur on poorly managed systems, specifically, if maps or alias files are in world writable directories. If your system has alias maps in writable directories, it is potentially possible for an attacker to replace the .db (or .dir and .pag) files by symbolic links pointing at another database; this can be used either to expose information (e.g., by pointing an alias file at /etc/spwd.db and probing for accounts), or as a denial-of-service attack (by trashing the password database). The fix disallows symbolic links entirely when rebuilding alias files or on maps that are in writable directories, and always warns on writable directories; 8.9 will probably consider writable directories to be fatal errors. This does not represent an exposure on systems that have alias files in unwritable system directories. SECURITY: disallow .forward or :include: files that are links (hard or soft) if the parent directory (or any directory in the path) is writable by anyone other than the owner. This is similar to the previous case for user files. This change should not affect most systems, but is necessary to prevent an attacker who can write the directory from pointing such files at other files that are readable only by the owner. SECURITY: Tighten safechown rules: many systems will say that they have a safe (restricted to root) chown even on files that are mounted from another system that allows owners to give away files. The new rules are very strict, trusting file ownership only in those few cases where the system has been verified to be at least as paranoid as necessary. However, it is possible to relax the rules to partially trust the ownership if the directory path is not world or group writable. This might allow someone who has a legitimate :include: file (referenced directly from /etc/aliases) to become another non-root user if the :include: file is in a non-writable directory on an NFS-mounted filesystem where the local system says that giveaway is denied but it is actually permitted. I believe this to be a very small set of cases. If in doubt, do not point :include: aliases at NFS-mounted filesystems. SECURITY: When setting a numeric group id using the RunAsUser option (e.g., "O RunAsUser=10:20", the group id would not be set. Implicit group ids (e.g., "O RunAsUser=mailnull") or alpha group ids (e.g., "O RunAsUser=mailuser:mailgrp") worked fine. The user id was still set properly. Problem noted by Uli Pralle of the Technical University of Berlin. Save the initial gid set for use when checking for if the PrivacyOptions=restrictmailq option is set. Problem reported by Wolfgang Ley of DFN-CERT. Make 55x reply codes to the SMTP DATA-"." be non-sticky (i.e., a failure on one message won't affect future messages to the same host). IP source route printing had an "off by one" error that would affect any options that came after the route option. Patch from Theo de Raadt. The "Message is too large" error didn't successfully bounce the error back to the sender. Problem reported by Stephen More of PSI; patch from Gregory Neil Shapiro of WPI. Change SMTP status code 553 to map into Extended code 5.1.0 (instead of 5.1.3); it apparently gets used in multiple ways. Suggested by John Myers of Portola Communications. Fix possible extra null byte generated during collection if errors occur at the beginning of the stream. Patch contributed by Andrey A. Chernov and Gregory Neil Shapiro. Code changes to avoid possible reentrant call of malloc/free within a signal handler. Problem noted by John Beck of Sun Microsystems. Move map initialization to be earlier so that check_relay ruleset will have the latest version of the map data. Problem noted by Paul Forgey of Metainfo; patch from Gregory Neil Shapiro. If there are fatal errors during the collection phase (e.g., message too large) don't send the bogus message. Avoid "cannot open xfAAA00000" messages when sending to aliases that have errors and have owner- aliases. Problem noted by Michael Barber of MTU; fix from Gregory Neil Shapiro of WPI. Avoid null pointer dereference on illegal Boundary= parameters in multipart/mixed Content-Type: header. Problem noted by Richard Muirden of RMIT University. Always print error messages during newaliases (-bi) even if the ErrorMode is not set to "print". Fix from Gregory Neil Shapiro. Test mode could core dump if you did a /map lookup in an optional map that could not be opened. Based on a fix from John Beck of Sun Microsystems. If DNS is misconfigured so that the last MX record tried points to a host that does not have an A record, but other MX records pointed to something reasonable, don't bounce the message with a "host unknown" error. Note that this should really be fixed in the zone file for the domain. Problem noted by Joe Rhett of Navigist, Inc. If a map fails (e.g., DNS times out) on all recipient addresses, mark the message as having been tried; otherwise the next queue run will not realize that this is a second attempt and will retry immediately. Problem noted by Bryan Costales of Mercury Mail. If the clock is set backwards, and a MinQueueAge is set, no jobs will be run until the later setting of the clock is reached. "Problem" (I use the term loosely) noted by Eric Hagberg of Morgan Stanley. If the load average rises above the cutoff threshold (above which sendmail will not process the queue at all) during a queue run, abort the queue run immediately. Problem noted by Bryan Costales of Mercury Mail. The variable queue processing algorithm (based on the message size, number of recipients, message precedence, and job age) was non-functional -- either the entire queue was processed or none of the queue was processed. The updated algorithm does no queue run if a single recipient zero size job will not be run. If there is a fatal ("panic") message that will cause sendmail to die immediately, never hold the error message for future printing. Force ErrorMode=print in -bt mode so that all errors are printed regardless of the setting of the ErrorMode option in the configuration file. Patch from Gregory Neil Shapiro. New compile flag HASSTRERROR says that this OS has the strerror(3) routine available in one of the libraries. Use it in conf.h. The -m (match only) flag now works on host class maps. If class hash or btree maps are rebuilt, sendmail will now detect this and reopen the map. Previously, they could give erroneous results during a single message processing (but would recover when the next message was received). Don't delete zero length queue files when doing queue runs until the files are at least ten minutes old. This avoids a potential race condition: the creator creates the qf file, getting back a file descriptor. The queue runner locks it and deletes it because it is zero length. The creator then writes the descriptor that is now for a disconnected file, and the job goes away. Based on a suggestion by Bryan Costales. When determining the "validated" host name ($_ macro), do a forward (A) DNS lookup on the result of the PTR lookup and compare results. If they differ or if the PTR lookup fails, tag the address as "may be forged". Log null connections (i.e., hosts that connect but do not do any substantive activity on the connection before disconnecting; "substantive" is defined to be MAIL, EXPN, VRFY, or ETRN. Always permit "writes" to /dev/null regardless of the link count. This is safe because /dev/null is special cased, and no open or write is ever actually attempted. Patch from Villy Kruse of TwinCom. If a message cannot be sent because of a 552 (exceeded storage allocation) response to the MAIL FROM:<>, and a SIZE= parameter was given, don't return the body in the bounce, since there is a very good chance that the message will double-bounce. Fix possible line truncation if a quoted-printable had an =00 escape in the body. Problem noted by Charles Karney of the Princeton Plasma Physics Laboratory. Notify flags (e.g., -NSUCCESS) were lost on user+detail addresses. Problem noted by Kari Hurtta of the Finnish Meteorological Institute. The MaxDaemonChildren option wasn't applying to queue runs as documented. Note that this increases the potential denial of service problems with this option: an attacker can connect many times, and thereby lock out queue runs as well as incoming connections. If you use this option, you should run the "sendmail -bd" and "sendmail -q30m" jobs separately to avoid this attack. Failure to limit noted by Matthew Dillon of BEST Internet Communications. Always give a message in newaliases if alias files cannot be opened instead of failing silently. Suggested by Gregory Neil Shapiro. This change makes the code match the O'Reilly book (2nd edition). Some older versions of the resolver could return with h_errno == -1 if no name server could be reached, causing mail to bounce instead of queueing. Treat this like TRY_AGAIN. Fix from John Beck of SunSoft. If a :include: file is owned by a user that does not have an entry in the passwd file, sendmail could dereference a null pointer. Problem noted by Satish Mynam of Sun Microsystems. Take precautions to make sure that the SMTP protocol cannot get out of sync if (for example) an alias file cannot be opened. Fix a possible race condition that can cause a SIGALRM to come in immediately after a SIGHUP, causing the new sendmail to die. Avoid possible hang on SVr3 systems when doing child reaping. Patch from Villy Kruse of TwinCom. Ignore improperly formatted SMTP reply codes. Previously these were partially processed, which could cause confusing error returns. Fix possible bogus pointer dereference when doing ldapx map lookups on some architectures. Portability: A/UX: from Jim Jagielski of NASA/GSFC. glibc: SOCK_STREAM was changed from a #define to an enum, thus breaking #ifdef SOCK_STREAM. Only option seems to be to assume SOCK_STREAM if __GNU_LIBRARY__ is defined. Problem reported by A Sun of the University of Washington. Solaris: use SIOCGIFNUM to get the number of interfaces on the system rather than guessing at compile time. Patch contributed by John Beck of Sun Microsystems. Intel Paragon: from Wendy Lin of Purdue University. GNU Hurd: from Miles Bader of the GNU project. RISC/os 4.50 from Harlan Stenn of PFCS Corporation. ISC Unix: wait never returns if SIGCLD signals are blocked. Unfortunately releasing them opens a race condition, but there appears to be no fix for this. Patch from Gregory Neil Shapiro. BIND 8.1 for IPv6 compatibility from John Kennedy. Solaris: a bug in strcasecmp caused characters with the high order bit set to apparently randomly match letters -- for example, $| (0233) matches "i" and "I". Problem noted by John Gregson of the University of Cambridge. IRIX 6.x: make Makefile.IRIX.6.2 apply to all 6.x. From Kari Hurtta. IRIX 6.x: Create Makefiles for systems that claim to be IRIX64 but are 6.2 or higher (so use the regular IRIX Makefile). IRIX 6.x: Fix load average computation on 64 bit kernels. Problem noted by Eric Hagberg of Morgan Stanley. CONFIG: Some canonification was still done for UUCP-like addresses even if FEATURE(nocanonify) was set. Problem pointed out by Brian Candler. CONFIG: In some cases UUCP mailers wouldn't properly recognize all local names as local. Problem noted by Jeff Polk of BSDI; fix provided by Gregory Neil Shapiro. CONFIG: The "local:user" syntax entries in mailertables and other "mailer:user" syntax locations returned an incorrect value for the $h macro. Problem noted by Gregory Neil Shapiro. CONFIG: Retain "+detail" information when forwarding mail to a MAIL_HUB, LUSER_RELAY, or LOCAL_RELAY. Patch from Philip Guenther of Gustavus Adolphus College. CONFIG: Make sure user+detail works for FEATURE(virtusertable); rules are the same as for aliasing. Based on a patch from Gregory Neil Shapiro. CONFIG: Break up parsing rules into several pieces; this should have no functional change in this release, but makes it possible to have better anti-spam rulesets in the future. CONFIG: Disallow double dots in host names to avoid having the HostStatusDirectory store status under the wrong name. In some cases this can be used as a denial-of-service attack. Problem noted by Ron Jarrell of Virginia Tech, patch from Gregory Neil Shapiro. CONFIG: Don't use F=m (multiple recipients per invocation) for MAILER(procmail), but do pass F=Pn9 (include Return-Path:, don't include From_, and convert to 8-bit). Suggestions from Kimmo Suominen and Roderick Schertler. CONFIG: Domains under $=M (specified with MASQUERADE_DOMAIN) were being masqueraded as though FEATURE(masquerade_entire_domain) was specified, even when it wasn't. MAIL.LOCAL: Solaris 2.6 has snprintf. From John Beck of SunSoft. MAIL.LOCAL: SECURITY: check to make sure that an attacker doesn't "slip in" a symbolic link between the lstat(2) call and the exclusive open. This is only a problem on System V derived systems that allow an exclusive create on files that are symbolic links pointing nowhere. MAIL.LOCAL: If the final mailbox close() failed, the user id was not reset back to root, which on some systems would cause later mailboxes to fail. Also, any partial message would not be truncated, which could result in repeated deliveries. Problem noted by Bruce Evans via Peter Wemm (FreeBSD developers). MAKEMAP: Handle cases where O_EXLOCK is #defined to be 0. A similar change to the sendmail map code was made in 8.8.3. Problem noted by Gregory Neil Shapiro. MAKEMAP: Give warnings on file problems such as map files that are symbolic links; although makemap is not set-user-ID root, it is often run as root and hence has the potential for the same sorts of problems as alias rebuilds. MAKEMAP: Change compilation so that it will link properly on NEXTSTEP. CONTRIB: etrn.pl: search for Cw as well as Fw lines in sendmail.cf. Accept an optional list of arguments following the server name for the ETRN arguments to use (instead of $=w). Other miscellaneous bug fixes. From Christian von Roques via John Beck of Sun Microsystems. CONTRIB: Add passwd-to-alias.pl, contributed by Kari Hurtta. This Perl script converts GECOS information in the /etc/passwd file into aliases, allowing for faster access to full name lookups; it is also clever about adding aliases (to root) for system accounts. NEW FILES: src/safefile.c cf/ostype/gnuhurd.m4 cf/ostype/irix6.m4 contrib/passwd-to-alias.pl src/Makefiles/Makefile.IRIX64.6.1 src/Makefiles/Makefile.IRIX64.6.x RENAMED FILES: src/Makefiles/Makefile.IRIX.6.2 => Makefile.IRIX.6.x src/Makefiles/Makefile.IRIX64 => Makefile.IRIX64.6.0 8.8.5/8.8.5 1997/01/21 SECURITY: Clear out group list during startup. Without this, sendmail will continue to run with the group permissions of the caller, even if RunAsUser is specified. SECURITY: Make purgestat (-bH) be root-only. This is not in response to any known attack, but it's best to be conservative. Suggested by Peter Wemm of DIALix. SECURITY: Fix buffer overrun problem in MIME code that has possible security implications. Patch from Alex Garthwaite of the University of Pennsylvania. Use of a -f flag with a phrase attached (e.g., "-f 'Full Name '") would truncate the address after "Full". Although the -f syntax is incorrect (since it is in the envelope, it shouldn't have comments and full names), the failure mode was unnecessarily awful. Fix a possible null pointer dereference when converting 8-bit data to a 7-bit format. Problem noted by Jim Hutchins of Sandia National Labs and David James of British Telecom. Clear out stale state that affected F=9 on SMTP mailers in queue runs. Although this really shouldn't be used (F=9 is for final delivery only, and using it on an SMTP mailer makes it possible for a message to be converted from 8->7->8->7 bits several times), it shouldn't have failed with a syserr. Problem noted by Eric Hagberg of Morgan Stanley. _Really_ fix the multiple :maildrop code in the user database module. Patch from Roy Mongiovi of Georgia Tech. Let F lines in the configuration file actually read root-only files if the configuration file is safe. Based on a patch from Keith Reynolds of SCO. ETRN followed by QUIT would hold the connection open until the queue run completed. Problem noted by Truck Lewis of TDK Semiconductor Corp. It turns out that despite the documentation, the TCP wrappers library does _not_ log rejected connections. Do the logging ourselves. Problem noted by Fletcher Mattox of the University of Texas at Austin. If sendmail finds a qf file in its queue directory that is an unknown version (e.g., when backing out to an old version), the error is reported on every queue run. Change it to only give the error once (and rename the qf => Qf). Patch from William A. Gianopoulos of Raytheon Company. Start a new session when doing background delivery; currently it ignored signals but didn't start a new signal, that caused some problems if a background process tried to send mail under certain circumstances. Problem noted by Eric Hagberg of Morgan Stanley; fix from Kari Hurtta. Simplify test for skipping a queue run to just check if the current load average is >= the queueing load average. Previously the check factored in some other parameters that caused it to essentially never skip the queue run. Patch from Bryan Costales. If the SMTP server is running in "nullserver" mode (that is, it is rejecting all commands), start sleeping after MAXBADCOMMAND (25) commands; this helps prevent a bad guy from putting you into a tight loop as a denial-of-service attack. Based on an e-mail conversation with Brad Knowles of AOL. Slow down when too many "light weight" commands have been issued; this helps prevent a class of denial-of-service attacks. The current values and defaults are: MAXNOOPCOMMANDS 20 NOOP, VERB, ONEX, XUSR MAXHELOCOMMANDS 3 HELO, EHLO MAXVRFYCOMMANDS 6 VRFY, EXPN MAXETRNCOMMANDS 8 ETRN These will probably be configurable in a future release. On systems that have uid_t typedefed to be an unsigned short, programs that had the F=S flag and no U= equate would be invoked with the real uid set to 65535 rather than being left unchanged. In some cases, NOTIFY=NEVER was not being honored. Problem noted by Steve Hubert of the University of Washington, Seattle. Mail that was Quoted-Printable encoded and had a soft line break on the last line (i.e., an incomplete continuation) had the last line dropped. Since this appears to be illegal it isn't clear what to do with it, but flushing the last line seems to be a better "fail soft" approach. Based on a patch from Eric Hagberg. If AllowBogusHELO and PrivacyOptions=needmailhelo are both set, a bogus HELO command still causes the "Polite people say HELO first" error message. Problem pointed out by Chris Thomas of UCLA; patch from John Beck of SunSoft. Handle "sendmail -bp -qSfoobar" properly if restrictqrun is set in PrivacyOptions. The -q shouldn't turn this command off. Problem noted by Murray Kucherawy of Pacific Bell Internet; based on a patch from Gregory Neil Shapiro of WPI. Don't consider SMTP reply codes 452 or 552 (exceeded storage allocation) in a DATA transaction to be sticky; these can occur because a message is too large, and smaller messages should still go through. Problem noted by Matt Dillon of Best Internet Communications. In some cases bounces were saved in /var/tmp/dead.letter even if they had been successfully delivered to the envelope sender. Problem noted Eric Hagberg of Morgan Stanley; solution from Gregory Neil Shapiro of WPI. Give better diagnostics on long alias lines. Based on code contributed by Patrick Gosling of the University of Cambridge. Increase the number of virtual interfaces that will be probed for alternate names. Problem noted by Amy Rich of Shore.Net. PORTABILITY: UXP/DS V20L10 for Fujitsu DS/90: Makefile patches from Toshiaki Nomura of Fujitsu Limited. SunOS with LDAP support: compile problems with struct timeval. Patch from Nick Cuccia of TCSI Corporation. SCO: from Keith Reynolds of SCO. Solaris: kstat load average computation wasn't being used. Fixes from Michael Ju. Tokarev of Telecom Service, JSC (Moscow). OpenBSD: from Jason Downs of teeny.org. Altos System V: from Tim Rice. Solaris 2.5: from Alan Perry of SunSoft. Solaris 2.6: from John Beck of SunSoft. Harris Nighthawk PowerUX (mh6000 box): from Bob Miorelli of Pratt & Whitney . CONFIG: It seems that I hadn't gotten the Received: line syntax _just_right_ yet. Tweak it again. I'll omit the names of the "contributors" (quantity two) in this one case. As of now, NO MORE DISCUSSION about the syntax of the Received: line. CONFIG: Although FEATURE(nullclient) uses EXPOSED_USER (class $=E), it never inserts that class into the output file. Fix it so it will honor EXPOSED_USER but will _not_ include root automatically in this class. Problem noted by Ronan KERYELL of Centre de Recherche en Informatique de l'École Nationale Supérieure des Mines de Paris (CRI-ENSMP). CONFIG: Clean up handling of "local:" syntax in relay specifications such as LUSER_RELAY. This change permits the following syntaxes: ``local:'' will send to the same user on the local machine (e.g., in a mailertable entry for "host", ``local:'' will cause an address addressed to user@host to go to user on the local machone). ``local:user'' will send to the named user on the local machine. ``local:user@host'' is equivalent to ``local:user'' (the host is ignored). In all cases, the original user@host is passed in $@ (i.e., the detail information). Inspired by a report from Michael Fuhr. CONFIG: Strip quotes from the first word of an "error:" host indication. This lets you set (for example) the LUSER_RELAY to be ``error:\"5.1.1\" Your Message Here''. Note the use of the \" so that the resulting string is properly quoted. Problem noted by Gregory Neil Shapiro of WPI. OP.ME: documentation was inconsistent about whether sendmail did a NOOP or a RSET to probe the connection (it does a RSET). Inconsistency noted by Deeran Peethamparam. OP.ME: insert additional blank pages so it will print properly on a duplex printer. From Matthew Black of Cal State University, Long Beach. 8.8.4/8.8.4 1996/12/02 SECURITY: under some circumstances, an attacker could get additional permissions by hard linking to files that were group writable by the attacker. The solution is to disallow any files that have hard links -- this will affect .forward, :include:, and output files. Problem noted by Terry Kyriacopoulos of Interlog Internet Services. As a workaround, set UnsafeGroupWrites -- always a good idea. SECURITY: the TryNullMXList (w) option should not be safe -- if it is, it is possible to do a denial-of-service attack on MX hosts that rely on the use of the null MX list. There is no danger if you have this option turned off (the default). Problem noted by Dan Bernstein. Also, make the DontInitGroups unsafe. I know of no specific attack against this, although a denial-of-service attack is probably possible, but in theory you should not be able to safely tweak anything that affects the permissions that are used when mail is delivered. Purgestat could go into an infinite loop if one of the host status directories somehow became empty. Problem noted by Roy Mongiovi of Georgia Tech. Processes got "lost" when counting children due to a race condition. This caused "proc_list_probe: lost pid" messages to be logged. Problem noted by several people. On systems with System V SIGCLD child signal semantics (notably AIX and HP-UX), mail transactions would print the message "451 SMTP-MAIL: lost child: No child processes". Problem noted by several people. Miscellaneous compiler warnings on picky compilers (or when setting gcc to high warning levels). From Tom Moore of NCR Corp. SMTP protocol errors, and most errors on MAIL FROM: lines should not be persistent between runs, since they are based on the message rather than the host. Problem noted by Matt Dillon of Best Internet Communications. The F=7 flag was ignored on SMTP mailers. Problem noted by Tom Moore of NCR (a.k.a., AT&T Global Information Solutions). Avoid the possibility of having a child daemon run to completion (including closing the SMTP socket) before the parent has had a chance to close the socket; this can cause the parent to hang for a long time waiting for the socket to drain. Patch from Don Lewis of TDK Semiconductor. If the fork() failed in a queue run, the queue runners would not be rescheduled (so queue runs would stop). Patch from Don Lewis. Some error conditions in ETRN could cause output without an SMTP status code. Problem noted by Don Lewis. Multiple :maildrop addresses in the user database didn't work properly. Patch from Roy Mongiovi of Georgia Tech. Add ".db" automatically onto any user database spec that does not already have it; this is for consistency with makemap, the K line, and the documentation. Inconsistency pointed out by Roy Mongiovi. Allow sendmail to be properly called in nohup mode. Patch from Kyle Jones of UUNET. Change ETRN to ignore but still update host status files; previously it would ignore them and not save the updated status, which caused stale information to be maintained. Based on a patch from Christopher Davis of Kapor Enterprises Inc. Also, have ETRN ignore the MinQueueAge option. Patch long term host status to recover more gracefully from an empty host status file condition. Patch from NAKAMURA Motonori of Kyoto University. Several patches to signal handling code to fix potential race conditions from Don Lewis. Make it possible to compile with -DDAEMON=0 (previously it had some compile errors). This turns DAEMON, QUEUE, and SMTP into 0/1 compilation flags. Note that DAEMON is an obsolete compile flag; use NETINET instead. Solution based on a patch from Bryan Costales. PORTABILITY FIXES: AIX4: getpwnam() and getpwuid() do a sequential scan of the /etc/security/passwd file when called as root. This is very slow on some systems. To speed it up, use the (undocumented) _getpw{nam,uid}_shadow() routines. Patch from Chris Thomas of UCLA/OAC Systems Group. SCO 5.x: include -lprot in the Makefile. Patch from Bill Glicker of Burrelle's Information Service. NEWS-OS 4.x: need a definition for MODE_T to compile. Patch from Makoto MATSUSHITA of Osaka University. SunOS 4.0.3: compile problems. Patches from Andrew Cole of Leeds University and SASABE Tetsuro of the University of Tokyo. DG/UX 5.4.4.11 from Brian J. Murrell of InterLinx Support Services, Inc. Domain/OS from Don (Truck) Lewis of TDK Semiconductor Corp. I believe this to have only been a problem if you compiled with -DUSE_VENDOR_CF_PATH -- another reason to stick with /etc/sendmail.cf as your One True Path. Digital UNIX (OSF/1 on Alpha) load average computation from Martin Laubach of the Technischen Universität Wien. CONFIG: change default Received: line to be multiple lines rather than one long one. By popular demand. MAIL.LOCAL: warnings weren't being logged on some systems. Patch from Jerome Berkman of U.C. Berkeley. MAKEMAP: be sure to zero hinfo to avoid cruft that can cause runs to take a very long time. Problem noted by Yoshiro YONEYA of NTT Software Corporation. CONTRIB: add etrn.pl, contributed by John Beck. NEW FILES: contrib/etrn.pl 8.8.3/8.8.3 1996/11/17 SECURITY: it was possible to get a root shell by lying to sendmail about argv[0] and then sending it a signal. Problem noted by Leshka Zakharoff on the best-of-security list. Log sendmail binary version number in "Warning: .cf version level (%d) exceeds program functionality (%d) message" -- this should make it clearer to people that they are running the wrong binary. Fix a problem that occurs when you open an SMTP connection and then do one or more ETRN commands followed by a MAIL command; at the end of the DATA phase sendmail would incorrectly report "451 SMTP-MAIL: lost child: No child processes". Problem noted by Eric Bishop of Virginia Tech. When doing text-based host canonification (typically /etc/hosts lookup), a null host name would match any /etc/hosts entry with space at the end of the line. Problem noted by Steve Hubert of the University of Washington, Seattle. 7 to 8 bit BASE64 MIME conversions could duplicate bits of text. Problem reported by Tom Smith of Digital Equipment Corp. Increase the size of the DNS answer buffer -- the standard UDP packet size PACKETSZ (512) is not sufficient for some nameserver answers containing very many resource records. The resolver may also switch to TCP and retry if it detects UDP packet overflow. Also, allow for the fact that the resolver routines res_query and res_search return the size of the *un*truncated answer in case the supplied answer buffer it not big enough to accommodate the entire answer. Patch from Eric Wassenaar. Improvements to MaxDaemonChildren code. If you think you have too many children, probe the ones you have to verify that they are still around. Suggested by Jared Mauch of CICnet, Inc. Also, do this probe before growing the vector of children pids; this previously caused the vector to grow indefinitely due to a race condition. Problem reported by Kyle Jones of UUNET. On some architectures, (from the Berkeley DB library) defines O_EXLOCK to zero; this fools the map compilation code into thinking that it can avoid race conditions by locking on open. Change it to check for O_EXLOCK non-zero. Problem noted by Leif Erlingsson of Data Lege. Always call res_init() on startup (if compiled in, of course) to allow the sendmail.cf file to tweak resolver flags; without it, flag tweaks in ResolverOptions are ignored. Patch from Andrew Sun of Merrill Lynch. Improvements to host status printing code. Suggested by Steve Hubert of the University of Washington, Seattle. Change MinQueueAge option processing to do the check for the job age when reading the queue file, rather than at the end; this avoids parsing the addresses, which can do DNS lookups. Problem noted by John Beck of InReference, Inc. When MIME was being 7->8 bit decoded, "From " lines weren't being properly escaped. Problem noted by Peter Nilsson of the University of Linkoping. In some cases, sendmail would retain root permissions during queue runs even if RunAsUser was set. Problem noted by Mark Thomas of Mark G. Thomas Consulting. If the F=l flag was set on an SMTP mailer to indicate that it is actually local delivery, and NOTIFY=SUCCESS is specified in the envelope, and the receiving SMTP server speaks DSN, then the DSN would be both generated locally and propagated to the other end. The U= mailer field didn't correctly extract the group id if the user id was numeric. Problem noted by Kenneth Herron of MCI Telecommunications Communications. If a message exceeded the fixed maximum size on input, the body of the message was included in the bounce. Note that this did not occur if it exceeded the maximum _output_ size. Problem reported by Kyle Jones of UUNET. PORTABILITY FIXES: AIX4: 4.1 doesn't have a working setreuid(2); change the AIX4 defines to use seteuid(2) instead, which works on 4.1 as well as 4.2. Problem noted by Håkan Lindholm of interAF, Sweden. AIX4: use tzname[] vector to determine time zone name. Patch from NAKAMURA Motonori of Kyoto University. MkLinux: add Makefile.Linux.ppc and OSTYPE(mklinux) support. Contributed by Paul DuBois . Solaris: kstat(3k) support for retrieving the load average. This adds the LA_KSTAT definition for LA_TYPE. The outline of the implementation was contributed by Michael Tokarev of Telecom Service, JSC, Moscow. HP-UX 10.0 gripes about the (perfectly legal!) forward declaration of struct rusage at the top of conf.h; change it to only be included if you are using gcc, which is apparently the only compiler that requires it in the first place. Problem noted by Jeff Earickson of Colby College. IRIX: don't default to using gcc. IRIX is a civilized operating system that comes with a decent compiler by default. Problem noted by Barry Bouwsma and Kari Hurtta. CONFIG: specify F=9 as default in FEATURE(local_procmail) for consistency with other local mailers. Inconsistency pointed out by Teddy Hogeborn . CONFIG: if the "limited best mx" feature is used (to reduce DNS overhead) as part of the bestmx_is_local feature, the domain part was dropped from the name. Patch from Steve Hubert of the University of Washington, Seattle. CONFIG: catch addresses of the form "user@.dom.ain"; these could end up being translated to the null host name, which would return any entry in /etc/hosts that had a space at the end of the line. Problem noted by Steve Hubert of the University of Washington, Seattle. CONFIG: add OSTYPE(aix4). From Michael Sofka of Rensselaer Polytechnic Institute. MAKEMAP: tweak hash and btree parameters for better performance. Patch from Matt Dillon of Best Internet Communications. NEW FILES: src/Makefiles/Makefile.Linux.ppc cf/ostype/aix4.m4 cf/ostype/mklinux.m4 8.8.2/8.8.2 1996/10/18 SECURITY: fix a botch in the 7-bit MIME patch; the previous patch changed the code but didn't fix the problem. PORTABILITY FIXES: Solaris: Don't use the system getusershell(3); it can apparently corrupt the heap in some circumstances. Problem found by Ken Pizzini of Spry, Inc. OP.ME: document several mailer flags that were accidentally omitted from this document. These flags were F=d, F=j, F=R, and F=9. CONFIG: no changes. 8.8.1/8.8.1 1996/10/17 SECURITY: unset all environment variables that the resolver will examine during queue runs and daemon mode. Problem noted by Dan Bernstein of the University of Illinois at Chicago. SECURITY: in some cases an illegal 7-bit MIME-encoded text/plain message could overflow a buffer if it was converted back to 8 bits. This caused core dumps and has the potential for a remote attack. Problem first noted by Gregory Shapiro of WPI. Avoid duplicate deliveries of error messages on systems that don't have flock(2) support. Patch from Motonori Nakamura of Kyoto University. Ignore null FallBackMX (V) options. If this option is null (as opposed to undefined) it can cause "null signature" syserrs on illegal host names. If a Base64 encoded text/plain message has no trailing newline in the encoded text, conversion back to 8 bits will drop the final line. Problem noted by Pierre David. If running with a RunAsUser, sendmail would give bogus "cannot setuid" (or seteuid, or setreuid) messages on some systems. Problem pointed out by Jordan Mendelson of Web Services, Inc. Always print error messages in -bv mode -- previously, -bv would be absolutely silent on errors if the error mode was sent to (say) mail-back. Problem noted by Kyle Jones of UUNET. If -qI/R/S is set (or the ETRN command is used), ignore all long term host status. This is necessary because it is common to do this when you know a host has just come back up. Disallow duplicate HELO/EHLO commands as required by RFC 1651 section 4.2. Excessive permissiveness noted by Lee Flight of the University of Leicester. If a service (such as NIS) is specified as the last entry in the service switch, but that service is not compiled in, sendmail would return a temporary failure when an entry was not found in the map. This caused the message to be queued instead of bouncing immediately. Problem noted by Harry Edmon of the University of Washington. PORTABILITY FIXES: Solaris 2.3 had compilation problems in conf.c. Several people pointed this out. NetBSD from Charles Hannum of MIT. AIX4 improvements based on info from Steve Bauer of South Dakota School of Mines & Technology. CONFIG: ``error:code message'' syntax was broken in virtusertable. Patch from Gil Kloepfer Jr. CONFIG: if FEATURE(nocanonify) was specified, hosts in $=M (set using MASQUERADE_DOMAIN) were not masqueraded unless they were also in $=w. Problem noted by Zoltan Basti of Softec. MAIL.LOCAL: patches to compile and link cleanly on AIX. Based on a patch from Eric Hagberg of Morgan Stanley. MAIL.LOCAL: patches to compile on NEXTSTEP. From Patrick Nolan of Stanford via Robert La Ferla. 8.8.0/8.8.0 1996/09/26 Under some circumstances, Bcc: headers would not be properly deleted. Pointed out by Jonathan Kamens of OpenVision. Log a warning if the sendmail daemon is invoked without a full pathname, which prevents "kill -1" from working. I was urged to put this in by Andrey A. Chernov of DEMOS (Russia). Fix small buffer overflow. Since the data in this buffer was not read externally, there was no security problem (and in fact probably wouldn't really overflow on most compilers). Pointed out by KIZU takashi of Osaka University. Fix problem causing domain literals such as [1.2.3.4] to be ignored if a FallbackMXHost was specified in the configuration file -- all mail would be sent to the fallback even if the original host was accessible. Pointed out by Munenari Hirayama of NSC (Japan). A message that didn't terminate with a newline would (sometimes) not have the trailing "." added properly in the SMTP dialogue, causing SMTP to hang. Patch from Per Hedeland of Ericsson. The DaemonPortOptions suboption to bind to a particular address was incorrect and nonfunctional due to a misunderstanding of the semantics of binding on a passive socket. Patch from NIIBE Yutaka of Mitsubishi Research Institute. Increase the number of MX hosts for a single name to 100 to better handle the truly huge service providers such as AOL, which has 13 at the moment (and climbing). In order to avoid trashing memory, the buffer for all names has only been slightly increased in size, to 12.8K from 10.2K -- this means that if a single name had 100 MX records, the average size of those records could not exceed 128 bytes. Requested by Brad Knowles of America On Line. Restore use of IDENT returns where the OSTYPE field equals "OTHER". Urged by Dan Bernstein of U.C. Berkeley. Print q_statdate and q_specificity in address structure debugging printout. Expand MCI structure flag bits for debugging output. Support IPv6-style domain literals, which can have colons between square braces. Log open file descriptors for the "cannot dup" messages in deliver(); this is an attempt to track down a bug that one person seems to be having (it may be a Solaris bug!). DSN NOTIFY parameters were not properly propagated across queue runs; this caused the NOTIFY info to sometimes be lost. Problem pointed out by Claus Assmann of the Christian-Albrechts-University of Kiel. The statistics gathered in the sendmail.st file were too high; in some cases failures (e.g., user unknown or temporary failure) would count as a delivery as far as the statistics were concerned. Problem noted by Tom Moore of AT&T GIS. Systems that don't have flock() would not send split envelopes in the initial run. Problem pointed out by Leonard Zubkoff of Dandelion Digital. Move buffer overflow checking -- these primarily involve distrusting results that may come from NIS and DNS. 4.4-BSD-derived systems, including FreeBSD, NetBSD, and BSD/OS didn't include and hence had the wrong pathnames for a few things like /var/tmp. Reported by Matthew Green. Conditions were reversed for the Priority: header, resulting in all values being interpreted as non-urgent except for non-urgent, which was interpreted as normal. Patch from Bryan Costales. The -o (optional) flag was being ignored on hash and btree maps since 8.7.2. Fix from Bryan Costales. Content-Types listed in class "q" will always be encoded as Quoted-Printable (or more accurately, will never be encoded as base64). The class can have primary types (e.g., "text") or full types (e.g., "text/plain"). Based on a suggestion by Marius Olafsson of the University of Iceland. Define ${envid} to be the original envelope id (from the ESMTP DSN dialogue) so it can be passed to programs in mailers. Define ${bodytype} to be the body type (from the -B flag or the BODY= ESMTP parameter) so it can be passed to programs in mailers. Cause the VRFY command to return 252 instead of 250 unless the F=q flag is set in the mailer descriptor. Suggested by John Myers of CMU. Implement ESMTP ETRN command to flush the queue for a specific host. The command takes a host name; data for that host is immediately (and asynchronously) flushed. Because this shares the -qR implementation, other hosts may be attempted, but there should be no security implications. Implementation from John Beck of InReference, Inc. See RFC 1985 for details. Add three new command line flags to pass in DSN parameters: -V envid (equivalent to ENVID=envid on the MAIL command), -R ret (equivalent to RET=ret on the MAIL command), and -Nnotify (equivalent to NOTIFY=notify on the RCPT command). Note that the -N flag applies to all recipients; there is no way to specify per-address notifications on the command line, nor is there an equivalent for the ORCPT= per-address parameter. Restore LogLevel option to be safe (it can only be increased); apparently I went into paranoid mode between 8.6 and 8.7 and made it unsafe. Pointed out by Dabe Murphy of the University of Maryland. New logging on log level 15: all SMTP traffic. Patches from Andrew Gross of San Diego Supercomputer Center. NetInfo property value searching code wasn't stopping when it found a match. This was causing the wrong values to be found (and had a memory leak). Found by Bastian Schleuter of TU-Berlin. Add new F=0 (zero) mailer flag to turn off MX lookups. It was pointed out by Bill Wisner of Electronics for Imaging that you can't use the bracket address form for the MAIL_HUB macro, since that causes the brackets to remain in the envelope recipient address used for delivery. The simple fix (stripping off the brackets in the config file) breaks the use of IP literal addresses. This flag will solve that problem. Add MustQuoteChars option. This is a list of characters that must be quoted if they are found in the phrase part of an address (that is, the full name part). The characters @,;:\()[] are always in this list and cannot be removed. The default is this list plus . and ' to match RFC 822. Add AllowBogusHELO option; if set, sendmail will allow HELO commands that do not include a host name for back compatibility with some stupid SMTP clients. Setting this violates RFC 1123 section 5.2.5. Add MaxDaemonChildren option; if this is set, sendmail will start rejecting connections if it has more than this many outstanding children accepting mail. Note that you may see more processes than this because of outgoing mail; this is for incoming connections only. Add ConnectionRateThrottle option. If set to a positive value, the number of incoming SMTP connections that will be permitted in a single second is limited to this number. Connections are not refused during this time, just deferred. The intent is to flatten out demand so that load average limiting can kick in. It is less radical than MaxDaemonChildren, which will stop accepting connections even if all the connections are idle (e.g., due to connection caching). Add Timeout.hoststatus option. This interval (defaulting to 30m) specifies how long cached information about the state of a host will be kept before they are considered stale and the host is retried. If you are using persistent host status (i.e., the HostStatusDirectory option is set) this will apply between runs; otherwise, it applies only within a single queue run and hence is useful only for hosts that have large queues that take a very long time to run. Add SingleLineFromHeader option. If set, From: headers are coerced into being a single line even if they had newlines in them when read. This is to get around a botch in Lotus Notes. Text class maps were totally broken -- if you ever retrieved the last item in a table it would be truncated. Problem noted by Gregory Neil Shapiro of WPI. Extend the lines printed by the mailq command (== the -bp flag) when -v is given to 120 characters; this allows more information to be displayed. Suggested by Gregory Neil Shapiro of WPI. Allow macro definitions (`D' lines) with unquoted commas; previously this was treated as end-of-input. Problem noted by Bryan Costales. The RET= envelope parameter (used for DSNs) wasn't properly written to the queue file. Fix from John Hughes of Atlantic Technologies, Inc. Close /var/tmp/dead.letter after a successful write -- otherwise if this happens in a queue run it can cause nasty delays. Problem noted by Mark Horton of AT&T. If userdb entries pointed to userdb entries, and there were multiple values for a given key, the database cursor would get trashed by the recursive call. Problem noted by Roy Mongiovi of Georgia Tech. Fixed by reading all the values and creating a comma-separated list; thus, the -v output will be somewhat different for this case. Fix buffer allocation problem with Hesiod-based userdb maps when HES_GETMAILHOST is defined. Based on a patch by Betty Lee of Stanford University. When envelopes were split due to aliases with owner- aliases, and there was some error on one of the lists, more than one of the owners would get the message. Problem pointed out by Roy Mongiovi of Georgia Tech. Detect excessive recursion in macro expansions, e.g., $X defined in terms of $Y which is defined in terms of $X. Problem noted by Bryan Costales; patch from Eric Wassenaar. When using F=U to get "ugly UUCP" From_ lines, a buffer could in some cases get trashed causing bogus From_ lines. Fix from Kyle Jones of UUNET. When doing load average initialization, if the nlist call for avenrun failed, the second and subsequent lookups wouldn't notice that fact causing bogus load averages to be returned. Noted by Casper Dik of Sun Holland. Fix problem with incompatibility with some versions of inet_aton that have changed the return value to unsigned, so a check for an error return of -1 doesn't work. Use INADDR_NONE instead. This could cause mail to addresses such as [foo.com] to bounce or get dropped. Problem noted by Christophe Wolfhugel of the Pasteur Institute. DSNs were inconsistent if a failure occurred during the DATA phase rather than the RCPT phase: the Action: would be correct, but the detailed status information would be wrong. Problem noted by Bob Snyder of General Electric Company. Add -U command line flag and the XUSR ESMTP extension, both indicating that this is the initial MUA->MTA submission. The flag current does nothing, but in future releases (when MUAs start using these flags) it will probably turn on things like DNS canonification. Default end-of-line string (E= specification on mailer [M] lines) to \r\n on SMTP mailers. Default remains \n on non-SMTP mailers. Change the internal definition for the *file* and *include* mailers to have $u in the argument vectors so that they aren't misinterpreted as SMTP mailers and thus use \r\n line termination. This will affect anyone who has redefined either of these in their configuration file. Don't assume that IDENT servers close the connection after a query; responses can be newline terminated. From Terry Kennedy of St. Peter's College. Avoid core dumps on erroneous configuration files that have $#mailer with nothing following. From Bryan Costales. Avoid null pointer dereference with high debug values in unlockqueue. Fix from Randy Martin of Clemson University. Fix possible buffer overrun when expanding very large macros. Fix from Kyle Jones of UUNET. After 25 EXPN or VRFY commands, start pausing for a second before processing each one. This avoids a certain form of denial of service attack. Potential attack pointed out by Bryan Costales. Allow new named (not numbered!) config file rules to do validity checking on SMTP arguments: check_mail for MAIL commands and check_rcpt for RCPT commands. These rulesets can do anything they want; their result is ignored unless they resolve to the $#error mailer, in which case the indicated message is printed and the command is rejected. Similarly, the check_compat ruleset is called before delivery with "from_addr $| to_addr" (the $| is a meta-symbol used to separate the two addresses); it can give a "this sender can't send to this recipient" notification. Note that this patch allows $| to stand alone in rulesets. Define new macros ${client_name}, ${client_addr}, and ${client_port} that have the name, IP address, and port number (respectively) of the SMTP client (that is, the entity at the other end of the connection. These can be used in (e.g.) check_rcpt to verify that someone isn't trying to relay mail through your host inappropriately. Be sure to use the deferred evaluation form, for example $&{client_name}, to avoid having these bound when sendmail reads the configuration file. Add new config file rule check_relay to check the incoming connection information. Like check_compat, it is passed the host name and host address separated by $| and can reject connections on that basis. Allow IDA-style recursive function calls. Code contributed by Mark Lovell and Paul Vixie. Eliminate the "No ! in UUCP From address!" message" -- instead, create a virtual UUCP address using either a domain address or the $k macro. Based on code contributed by Mark Lovell and Paul Vixie. Add Stanford LDAP map. Requires special libraries that are not included with sendmail. Contributed by Booker C. Bense ; contact him for support. See also the src/READ_ME file. Allow -dANSI to turn on ANSI escape sequences in debug output; this puts metasymbols (e.g., $+) in reverse video. Really useful only for debugging deep bits of code where it is important to distinguish between the single-character metasymbol $+ and the two characters $, +. Changed ruleset 89 (executed in dumpstate()) to a named ruleset, debug_dumpstate. Add new UnsafeGroupWrites option; if set, .forward and :include: files that are group writable are considered "unsafe" -- that is, programs and files referenced from such files are not valid recipients. Delete bogosity test for FallBackMX host; this prevented it to be a name that was not in DNS or was a domain-literal. Problem noted by Tom May. Change the introduction to error messages to more clearly delineate permanent from temporary failures; if both existed in a single message it could be confusing. Suggested by John Beck of InReference, Inc. The IngoreDot (i) option didn't work for lines that were terminated with CRLF. Problem noted by Ted Stockwell of Secure Computing Corporation. Add a heuristic to improve the handling of unbalanced `<' signs in message headers. Problem reported by Matt Dillon of Best Internet Communications. Check for bogus characters in the 0200-0237 range; since these are used internally, very strange errors can occur if those characters appear in headers. Problem noted by Anders Gertz of Lysator. Implement 7 -> 8 bit MIME conversions. This only takes place if the recipient mailer has the F=9 flag set, and only works on text/plain body types. Code contributed by Marius Olafsson of the University of Iceland. Special case "postmaster" name so that it is always treated as lower case in alias files regardless of configuration settings; this prevents some potential problems where "Postmaster" or "POSTMASTER" might not match "postmaster". In most cases this change is a no-op. The -o map flag was ignored for text maps. Problem noted by Bryan Costales. The -a map flag was ignored for dequote maps. Problem noted by Bryan Costales. Fix core dump when a lookup of a class "prog" map returns no response. Patch from Bryan Costales. Log instances where sendmail is deferring or rejecting connections on LogLevel 14. Suggested by Kyle Jones of UUNET. Include port number in process title for network daemons. Suggested by Kyle Jones of UUNET. Send ``double bounces'' (errors that occur when sending an error message) to the address indicated in the DoubleBounceAddress option (default: postmaster). Previously they were always sent to postmaster. Suggested by Kyle Jones of UUNET. Add new mode, -bD, that acts like -bd in all respects except that it runs in foreground. This is useful for using with a wrapper that "watches" system services. Suggested by Kyle Jones of UUNET. Fix botch in spacing around (parenthesized) comments in addresses when the comment comes before the address. Patch from Motonori Nakamura of Kyoto University. Use the prefix "Postmaster notify" on the Subject: lines of messages that are being bounced to postmaster, rather than "Returned mail". This permits the person who is postmaster more easily determine what messages are to their role as postmaster versus bounces to mail they actually sent. Based on a suggestion by Motonori Nakamura. Add new value "time" for QueueSortOrder option; this causes the queue to be sorted strictly by the time of submission. Note that this can cause very bad behavior over slow lines (because large jobs will tend to delay small jobs) and on nodes with heavy traffic (because old things in the queue for hosts that are down delay processing of new jobs). Also, this does not guarantee that jobs will be delivered in submission order unless you also set DeliveryMode=queue. In general, it should probably only be used on the command line, and only in conjunction with -qRhost.domain. In fact, there are very few cases where it should be used at all. Based on an implementation by Motonori Nakamura. If a map lookup in ruleset 5 returns tempfail, queue the message in the same manner as other rulesets. Previously a temporary failure in ruleset 5 was ignored. Patch from Booker Bense of Stanford University. Don't proceed to the next MX host if an SMTP MAIL command returns a 5yz (permanent failure) code. The next MX host will still be tried if the connection cannot be opened in the first place or if the MAIL command returns a 4yz (temporary failure) code. (It's hard to know what to do here, since neither RFC 974 nor RFC 1123 specify when to proceed to the next MX host.) Suggested by Jonathan Kamens of OpenVision, Inc. Add new "-t" flag for map definitions (the "K" line in the .cf file). This causes map lookups that get a temporary failure (e.g., name server failure) to _not_ defer the delivery of the message. This should only be used if your configuration file is prepared to do something sensible in this case. Based on an idea by Gregory Shapiro of WPI. Fix problem finding network interface addresses. Patch from Motonori Nakamura. Don't reject qf entries that are not owned by your effective uid if you are not running set-user-ID; this makes management of certain kinds of firewall setups difficult. Patch suggested by Eamonn Coleman of Qualcomm. Add persistent host status. This keeps the information normally maintained within a single queue run in disk files that are shared between sendmail instances. The HostStatusDirectory is the directory in which the information is maintained. If not set, persistent host status is turned off. If not a full pathname, it is relative to the queue directory. A common value is ".hoststat". There are also two new operation modes: * -bh prints the status of hosts that have had recent connections. * -bH purges the host statuses. No attempt is made to save recent status information. This feature was originally written by Paul Vixie of Vixie Enterprises for KJS and adapted for V8 by Mark Lovell of Bigrock Consulting. Paul's funding of Mark and Mark's patience with my insistence that things fit cleanly into the V8 framework is gratefully appreciated. New SingleThreadDelivery option (requires HostStatusDirectory to operate). Avoids letting two sendmails on the local machine open connections to the same remote host at the same time. This reduces load on the other machine, but can cause mail to be delayed (for example, if one sendmail is delivering a huge message, other sendmails won't be able to send even small messages). Also, it requires another file descriptor (for the lock file) per connection, so you may have to reduce ConnectionCacheSize to avoid running out of per-process file descriptors. Based on the persistent host status code contributed by Paul Vixie and Mark Lovell. Allow sending to non-simple files (e.g., /dev/null) even if the SafeFileEnvironment option is set. Problem noted by Bryan Costales. The -qR flag mistakenly matched flags in the "R" line of the queue file. Problem noted by Bryan Costales. If a job was aborted using the interrupt signal (e.g., control-C from the keyboard), on some occasions an empty df file would be left around; these would collect in the queue directory. Problem noted by Bryan Costales. Change the makesendmail script to enhance the search for Makefiles based on release number. For example, on SunOS 5.5.1, it will search for Makefile.SunOS.5.5.1, Makefile.SunOS.5.5, and then Makefile.SunOS.5.x (in addition to the other rules, e.g., adding $arch). Problem noted by Jason Mastaler of Atlanta Webmasters. When creating maps using "newaliases", always map the keys to lower case when creating the map unless the -f flag is specified on the map itself. Previously this was done based on the F=u flag in the local mailer, which meant you could create aliases that you could never access. Problem noted by Bob Wu of DEC. When a job was read from the queue, the bits causing notification on failure or delay were always set. This caused those notifications to be sent even if NOTIFY=NEVER had been specified. Problem noted by Steve Hubert of the University of Washington, Seattle. Add new configurable routine validate_connection (in conf.c). This lets you decide if you are willing to accept traffic from this host. If it returns FALSE, all SMTP commands will return "550 Access denied". -DTCPWRAPPERS will include support for TCP wrappers; you will need to add -lwrap to the link line. (See src/READ_ME for details.) Don't include the "THIS IS A WARNING MESSAGE ONLY" banner on postmaster bounces. Some people seemed to think that this could be confusing (even though it is true). Suggested by Motonori Nakamura. Add new RunAsUser option; this causes sendmail to do a setuid to that user early in processing to avoid potential security problems. However, this means that all .forward and :include: files must be readable by that user, and all files to be written must be writable by that user and all programs will be executed by that user. It is also incompatible with the SafeFileEnvironment option. In other words, it may not actually add much to security. However, it should be useful on firewalls and other places where users don't have accounts and the aliases file is well constrained. Add Timeout.iconnect. This is like Timeout.connect except it is used only on the first attempt to delivery to an address. It could be set to be lower than Timeout.connect on the principle that the mail should go through quickly to responsive hosts; less responsive hosts get to wait for the next queue run. Fix a problem on Solaris that occasionally causes programs (such as vacation) to hang with their standard input connected to a UDP port. It also created some signal handling problems. The problems turned out to be an interaction between vfork(2) and some of the libraries, particularly NIS/NIS+. I am indebted to Tor Egge for this fix. Change user class map to do the same matching that actual delivery will do instead of just a /etc/passwd lookup. This adds fuzzy matching to the user map. Patch from Dan Oscarsson. The Timeout.* options are not safe -- they can be used to create a denial-of-service attack. Problem noted by Christophe Wolfhugel. Don't send PostmasterCopy messages in the event of a "delayed" notification. Suggested by Barry Bouwsma. Don't advertise "VERB" ESMTP extension if the "noexpn" privacy option is set, since this disables VERB mode. Suggested by John Hawkinson of MIT. Complain if the QueueDirectory (Q) option is not set. Problem noted by Motonori Nakamura of Kyoto University. Only queue messages on transient .forward open failures if there were no successful opens. The previous behavior caused it to queue even if a "fall back" .forward was found. Problem noted by Ann-Kian Yeo of the Dept. of Information Systems and Computer Science (DISCS), NUS, Singapore. Don't do 8->7 bit conversions when bouncing a MIME message that is bouncing because of a MIME error during 8->7 bit conversion; the encapsulated message will bounce again, causing a loop. Problem noted by Steve Hubert of the University of Washington. Create xf (transcript) files using the TempFileMode option value instead of 0644. Suggested by Ann-Kian Yeo of the National University of Singapore. Print errors if setgid/setuid/etc. fail during delivery. This helps detect cases where DefaultUid is set to something that the system can't cope with. PORTABILITY FIXES: Support for AIX/RS 2.2.1 from Mark Whetzel of Western Atlas International. Patches for Intel Paragon OSF/1 1.3 from Leo Bicknell . On DEC OSF/1 3.2 and earlier, the MatchGECOS code would only work on the first recipient of a message due to a bug in the getpwent family. If this is something you use, you can define DEC_OSF_BROKEN_GETPWENT=1 for a workaround. From Maximum Entropy of Sanford C. Bernstein and Associates. FreeBSD 1.1.5.1 uname -r returns a string containing parentheses, which breaks makesendmail. Reported by Piero Serini . Sequent DYNIX/ptx 4.0.2 patches from Jack Woolley of Systems and Computer Technology Corporation. Solaris 2.x: omit the UUCP grade parameter (-g flag) because it is system-dependent. Problem noted by J.J. Bailey of Bailey Computer Consulting. Pyramid NILE running DC/OSx support from Earle F. Ake of Hassler Communication Systems Technology, Inc. HP-UX 10.x compile glitches, reported by Anne Brink of the U.S. Army and James Byrne of Harte & Lyne Limited. NetBSD from Matthew Green of the NetBSD crew. SCO 5.x from Keith Reynolds of SCO. IRIX 6.2 from Robert Tarrall of the University of Colorado and Kari Hurtta of the Finnish Meteorological Institute. UXP/DS (Fujitsu/ICL DS/90 series) support from Diego R. Lopez, CICA (Seville). NCR SVR4 MP-RAS 3.x support from Tom Moore of NCR. PTX 3.2.0 from Kenneth Stailey of the US Department of Labor Employment Standards Administration. Altos System V (5.3.1) from Tim Rice of Multitalents. Concurrent Systems Corporation Maxion from Donald R. Laster Jr. NetInfo maps (improved debugging and multi-valued aliases) from Adrian Steinmann of Steinmann Consulting. ConvexOS 11.5 (including SecureWare C2 and the Share Scheduler) from Eric Schnoebelen of Convex. Linux 2.0 mail.local patches from Horst von Brand. NEXTSTEP 3.x compilation from Robert La Ferla. NEXTSTEP 3.x code changes from Allan J. Nathanson of NeXT. Solaris 2.5 configuration fixes for mail.local by Jim Davis of the University of Arizona. Solaris 2.5 has a working setreuid. Noted by David Linn of Vanderbilt University. Solaris changes for praliases, makemap, mailstats, and smrsh. Previously you had to add -DSOLARIS in Makefile.dist; this auto-detects. Based on a patch from Randall Winchester of the University of Maryland. CONFIG: add generic-nextstep3.3.mc file. Contributed by Robert La Ferla of Hot Software. CONFIG: allow mailertables to resolve to ``error:code message'' (where "code" is an exit status) on domains (previously worked only on hosts). Patch from Cor Bosman of Xs4all Foundation. CONFIG: hooks for IPv6-style domain literals. CONFIG: predefine ALIAS_FILE and change the prototype file so that if it is undefined the AliasFile option is never set; this should be transparent for most everyone. Suggested by John Myers of CMU. CONFIG: add FEATURE(limited_masquerade). Without this feature, any domain listed in $=w is masqueraded. With it, only those domains listed in a MASQUERADE_DOMAIN macro are masqueraded. CONFIG: add FEATURE(masquerade_entire_domain). This causes masquerading specified by MASQUERADE_DOMAIN to apply to all hosts under those domains as well as the domain headers themselves. For example, if a configuration had MASQUERADE_DOMAIN(foo.com), then without this feature only foo.com would be masqueraded; with it, *.foo.com would be masqueraded as well. Based on an implementation by Richard (Pug) Bainter of U. Texas. CONFIG: add FEATURE(genericstable) to do a more general rewriting of outgoing addresses. Defaults to ``hash -o /etc/genericstable''. Keys are user names; values are outgoing mail addresses. Yes, this does overlap with the user database, and figuring out just when to use which one may be tricky. Based on code contributed by Richard (Pug) Bainter of U. Texas with updates from Per Hedeland of Ericsson. CONFIG: add FEATURE(virtusertable) to do generalized rewriting of incoming addresses. Defaults to ``hash -o /etc/virtusertable''. Keys are either fully qualified addresses or just the host part (with the @ sign). For example, a table containing: info@foo.com foo-info info@bar.com bar-info @baz.org jane@elsewhere.net would send all mail destined for info@foo.com to foo-info (which is presumably an alias), mail addressed to info@bar.com to bar-info, and anything addressed to anyone at baz.org will be sent to jane@elsewhere.net. The names foo.com, bar.com, and baz.org must all be in $=w. Based on discussions with a great many people. CONFIG: add nullclient configurations to define SMTP_MAILER_FLAGS. Suggested by Richard Bainter. CONFIG: add FAX_MAILER_ARGS to tweak the arguments passed to the "fax" mailer. CONFIG: allow mailertable entries to resolve to local:user; this passes the original user@host in to procmail-style local mailers as the "detail" information to allow them to do additional clever processing. From Joe Pruett of Teleport Corporation. Delivery to the original user can be done by specifying "local:" (with nothing after the colon). CONFIG: allow any context that takes "mailer:domain" to also take "mailer:user@domain" to force mailing to the given user; "local:user" can also be used to do local delivery. This applies on *_RELAY and in the mailertable entries. Based on a suggestion by Ribert Kiessling of Easynet. CONFIG: Allow FEATURE(bestmx_is_local) to take an argument that limits the possible domains; this reduces the number of DNS lookups required to support this feature. For example, FEATURE(bestmx_is_local, my.site.com) limits the lookups to domains under my.site.com. Code contributed by Anthony Thyssen . CONFIG: LOCAL_RULESETS introduces any locally defined rulesets, such as the check_rcpt ruleset. Suggested by Gregory Shapiro of WPI. CONFIG: MAILER_DEFINITIONS introduces any mailer definitions, in the event you have to define local mailers. Suggested by Gregory Shapiro of WPI. CONFIG: fix cases where a three- (or more-) stage route-addr could be misinterpreted as a list:...; syntax. Based on a patch by Vlado Potisk . CONFIG: Fix masquerading of UUCP addresses when the UUCP relay is remotely connected. The address host!user was being converted to host!user@thishost instead of host!user@uurelay. Problem noted by William Gianopoulos of Raytheon Company. CONFIG: add confTO_ICONNECT to set Timeout.iconnect. CONFIG: change FEATURE(redirect) message from "User not local" to "User has moved"; the former wording was confusing if the new address is still on the local host. Based on a suggestion by Andreas Luik. CONFIG: add support in FEATURE(nullclient) for $=E (exposed users). However, the class is not pre-initialized to contain root. Suggested by Gregory Neil Shapiro. CONTRIB: Remove XLA code at the request of the author, Christophe Wolfhugel. CONTRIB: Add re-mqueue.pl, contributed by Paul Pomes of Qualcomm. MAIL.LOCAL: make it possible to compile mail.local on Solaris. Note well: this produces a slightly different mailbox format (no Content-Length: headers), file ownerships and modes are different (not owned by group mail; mode 600 instead of 660), and the local mailer flags will have to be tweaked (make them match bsd4.4) in order to use this mailer. Patches from Paul Hammann of the Missouri Research and Education Network. MAIL.LOCAL: in some cases it could return EX_OK even though there was a delivery error, such as if the ownership on the file was wrong or the mode changed between the initial stat and the open. Problem reported by William Colburn of the New Mexico Institute of Mining and Technology. MAILSTATS: handle zero length files more reliably. Patch from Bryan Costales. MAILSTATS: add man page contributed by Keith Bostic of BSDI. MAKEMAP: The -d flag (to allow duplicate keys) to a btree map wasn't honored. Fix from Michael Scott Shappe. PRALIASES: add man page contributed by Keith Bostic of BSDI. NEW FILES: src/Makefiles/Makefile.AIX.2 src/Makefiles/Makefile.IRIX.6.2 src/Makefiles/Makefile.maxion src/Makefiles/Makefile.NCR.MP-RAS.3.x src/Makefiles/Makefile.SCO.5.x src/Makefiles/Makefile.UXPDSV20 mailstats/mailstats.8 praliases/praliases.8 cf/cf/generic-nextstep3.3.mc cf/feature/genericstable.m4 cf/feature/limited_masquerade.m4 cf/feature/masquerade_entire_domain.m4 cf/feature/virtusertable.m4 cf/ostype/aix2.m4 cf/ostype/altos.m4 cf/ostype/maxion.m4 cf/ostype/solaris2.ml.m4 cf/ostype/uxpds.m4 contrib/re-mqueue.pl DELETED FILES: src/Makefiles/Makefile.Solaris contrib/xla/README contrib/xla/xla.c RENAMED FILES: src/Makefiles/Makefile.NCR3000 => Makefile.NCR.MP-RAS.2.x src/Makefiles/Makefile.SCO.3.2v4.2 => Makefile.SCO.4.2 src/Makefiles/Makefile.UXPDS => Makefile.UXPDSV10 src/Makefiles/Makefile.NeXT => Makefile.NeXT.2.x src/Makefiles/Makefile.NEXTSTEP => Makefile.NeXT.3.x 8.7.6/8.7.3 1996/09/17 SECURITY: It is possible to force getpwuid to fail when writing the queue file, causing sendmail to fall back to running programs as the default user. This is not exploitable from off-site. Workarounds include using a unique user for the DefaultUser (old u & g options) and using smrsh as the local shell. SECURITY: fix some buffer overruns; in at least one case this allows a local user to get root. This is not known to be exploitable from off-site. The workaround is to disable chfn(1) commands. 8.7.5/8.7.3 1996/03/04 Fix glitch in 8.7.4 when putting certain internal lines; this can in some case cause connections to hang or messages to have extra spaces in odd places. Patch from Eric Wassenaar; reports from Eric Hall of Chiron Corporation, Stephen Hansen of Stanford University, Dean Gaudet of HotWired, and others. 8.7.4/8.7.3 1996/02/18 SECURITY: In some cases it was still possible for an attacker to insert newlines into a queue file, thus allowing access to any user (except root). CONFIG: no changes -- it is not a bug that the configuration version number is unchanged. 8.7.3/8.7.3 1995/12/03 Fix botch in name server timeout in RCPT code; this problem caused two responses in SMTP, which breaks things horribly. Fix from Gregory Neil Shapiro of WPI. Verify that L= value on M lines cannot be negative, which could cause negative array subscripting. Not a security problem since this has to be in the config file, but it could have caused core dumps. Pointed out by Bryan Costales. Fix -d21 debug output for long macro names. Pointed out by Bryan Costales. PORTABILITY FIXES: SCO doesn't have ftruncate. From Bill Aten of Computerizers. IBM's version of arpa/nameser.h defaults to the wrong byte order. Tweak it to work properly. Based on fixes from Fletcher Mattox of UTexas and Betty Lee of Stanford University. CONFIG: add confHOSTS_FILE m4 variable to set HostsFile option. Deficiency pointed out by Bryan Costales of ICSI. 8.7.2/8.7.2 1995/11/19 REALLY fix the backslash escapes in SmtpGreetingMessage, OperatorChars, and UnixFromLine options. They were not properly repaired in 8.7.1. Completely delete the Bcc: header if and only if there are other valid recipient headers (To:, Cc: or Apparently-To:, the last being a historic botch, of course). If Bcc: is the only recipient header in the message, its value is tossed, but the header name is kept. The old behavior (always keep the header name and toss the value) allowed primary recipients to see that a Bcc: went to _someone_. Include queue id on ``Authentication-Warning: : set sender to
using -f'' syslog messages. Suggested by Kari Hurtta. If a sequence or switch map lookup entry gets a tempfail but then continues on to another map type, but the name is not found, return a temporary failure from the sequence or switch map. For example, if hosts search ``dns files'' and DNS fails with a tempfail, the hosts map will go on and search files, but if it fails the whole thing should be a tempfail, not a permanent (host unknown) failure, even though that is the failure in the hosts.files map. This error caused hard bounces when it should have requeued. Aliases to files such as /users/bar/foo/inbox, with /users/bar/foo owned by bar mode 700 and inbox being set-user-ID bar stopped working properly due to excessive paranoia. Pointed out by John Hawkinson of Panix. An SMTP RCPT command referencing a host that gave a nameserver timeout would return a 451 command (8.6 accepted it and queued it locally). Revert to the 8.6 behavior in order to simplify queue management for clustered systems. Suggested by Gregory Neil Shapiro of WPI. The same problem could break MH, which assumes that the SMTP session will succeed (tsk, tsk -- mail gets lost!); this was pointed out by Stuart Pook of Infobiogen. Fix possible buffer overflow in munchstring(). This was not a security problem because you couldn't specify any argument to this without first giving up root privileges, but it is still a good idea to avoid future problems. Problem noted by John Hawkinson and Sam Hartman of MIT. ``452 Out of disk space for temp file'' messages weren't being printed. Fix from David Perlin of Nanosoft. Don't advertise the ESMTP DSN extension if the SendMimeErrors option is not set, since this is required to get the actual DSNs created. Problem pointed out by John Gardiner Myers of CMU. Log permission problems that cause .forward and :include: files to be untrusted or ignored on log level 12 and higher. Suggested by Randy Martin of Clemson University. Allow user ids in U= clauses of M lines to have hyphens and underscores. Fix overcounting of recipients -- only happened when sending to an alias. Pointed out by Mark Andrews of SGI and Jack Woolley of Systems and Computer Technology Corporation. If a message is sent to an address that fails, the error message that is returned could show some extraneous "success" information included even if the user did not request success notification, which was confusing. Pointed out by Allan Johannesen of WPI. Config files that had no AliasFile definition were defaulting to using /etc/aliases; this caused problems with nullclient configurations. Change it back to the 8.6 semantics of having no local alias file unless it is declared. Problem noted by Charles Karney of Princeton University. Fix compile problem if NOTUNIX is defined. Pointed out by Bryan Costales of ICSI. Map lookups of class "userdb" maps were always case sensitive; they should be controlled by the -f flag like other maps. Pointed out by Bjart Kvarme . Fix problem that caused some addresses to be passed through ruleset 5 even when they were tagged as "sticky" by prefixing the address with an "@". Patch from Thomas Dwyer III of Michigan Technological University. When converting a message to Quoted-Printable, prevent any lines with dots alone on a line by themselves. This is because of the preponderance of broken mailers that still get this wrong. Code contributed by Per Hedeland of Ericsson. Fix F{macro}/file construct -- it previously did nothing. Pointed out by Bjart Kvarme of USIT/UiO (Norway). Announce whether a cached connection is SMTP or ESMTP (in -v mode). Requested by Allan Johannesen. Delete check for text format of alias files -- it should be legal to have the database format of the alias files without the text version. Problem pointed out by Joe Rhett of Navigist, Inc. If "Ot" was specified with no value, the TZ variable was not properly imported from the environment. Pointed out by Frank Crawford . Some architectures core dumped on "program" maps that didn't have extra arguments. Patch from Booker C. Bense of Stanford University. Queue run processes would re-spawn daemons when given a SIGHUP; only the parent should do this. Fix from Brian Coan of the Association for Progressive Communications. If MinQueueAge was set and a message was considered but not run during a queue run and the Timeout.queuereturn interval was reached, a "timed out" error message would be returned that didn't include the failed address (and claimed to be a warning even though it was fatal). The fix is to not return such messages until they are actually tried, i.e., in the next MinQueueAge interval. Problem noted by Rein Tollevik of SINTEF RUNIT, Oslo. Add HES_GETMAILHOST compile flag to support MIT Hesiod distributions that have the hes_getmailhost() routine. DEC Hesiod distributions do not have this routine. Based on a patch from Betty Lee of Stanford University. Extensive cleanups to map open code to handle a locking race condition in ndbm, hash, and btree format database files on some (most non-4.4-BSD based) OS architectures. This should solve the occasional "user unknown" problem during alias rebuilds that has plagued me for quite some time. Based on a patch from Thomas Dwyer III of Michigan Technological University. PORTABILITY FIXES: Solaris: Change location of newaliases and mailq from /usr/ucb to /usr/bin to match Sun settings. From James B. Davis of TCI. DomainOS: Makefile.DomainOS doesn't require -ldbm. From Don Lewis of Silicon Systems. HP-UX 10: rename Makefile.HP-UX.10 => Makefile.HP-UX.10.x so that the makesendmail script will find it. Pointed out by Richard Allen of the University of Iceland. Also, use -Aa -D_HPUX_SOURCE instead of -Ae, which isn't supported on all compilers. UXPDS: compilation fixes from Diego R. Lopez. CONFIG: FAX mailer wasn't setting .FAX as a pseudo-domain unless you also had a FAX_RELAY. From Thomas.Tornblom@Hax.SE. CONFIG: Minor glitch in S21 -- attachment of local domain name didn't have trailing dot. From Jim Hickstein of Teradyne. CONFIG: Fix best_mx_is_local feature to allow nested addresses such as user%host@thishost. From Claude Scarpelli of Infobiogen (France). CONFIG: OSTYPE(hpux10) failed to define the location of the help file. Pointed out by Hannu Martikka of Nokia Telecommunications. CONFIG: Diagnose some inappropriate ordering in configuration files, such as FEATURE(smrsh) listed after MAILER(local). Based on a bug report submitted by Paul Hoffman of Proper Publishing. CONFIG: Make OSTYPE files consistently not override settings that have already been set. Previously it worked differently for different files. CONFIG: Change relay mailer to do masquerading like 8.6 did. My take is that this is wrong, but the change was causing problems for some people. From Per Hedeland of Ericsson. CONTRIB: bitdomain.c patch from John Gardiner Myers ; portability changes for Posix environments (no functional changes). 8.7.1/8.7.1 1995/10/01 Old macros that have become options (SmtpGreetingMessage, OperatorChars, and UnixFromLine) didn't allow backslash escapes in the options, where they previously had. Bug pointed out by John Hawkinson of MIT. Fix strange case of an executable called by a program map that returns a value but also a non-zero exit status; this would give contradictory results in the higher level; in particular, the default clause in the map lookup would be ignored. Change to ignore the value if the program returns non-zero exit status. From Tom Moore of AT&T GIS. Shorten parameters passed to syslog() in some contexts to avoid a bug in many vendors' implementations of that routine. Although this isn't really a bug in sendmail per se, and my solution has to assume that syslog() has at least a 1K buffer size internally (I know some vendors have shortened this dramatically -- they're on their own), sendmail is a popular target. Also, limit the size of %s arguments in sprintf. These both have possible security implications. Solutions suggested by Casper Dik of Sun's Network Security Group (Holland), Mark Seiden, and others. Fix a problem that might cause a non-standard -B (body type) parameter to be passed to the next server with undefined results. This could have security implications. If a filesystem was at > 100% utilization, the freediskspace() routine incorrectly returned an error rather than zero. Problem noted by G. Paul Ziemba of Alantec. Change MX sort order so that local hostnames (those in $=w) always sort first within a given preference. This forces the bestmx map to always return the local host first, if it is included in the list of highest priority MX records. From K. Robert Elz. Avoid some possible null pointer dereferences. Fixes from Randy Martin When sendmail starts up on systems that have no fully qualified domain name (FQDN) anywhere in the first matching host map (e.g., /etc/hosts if the hosts service searches "files dns"), sendmail would sleep to try to find a FQDN, which it really really needs. This has been changed to fall through to the next map type if it can't find a FQDN -- i.e., if the hosts file doesn't have a FQDN, it will try dns even though the short name was found in /etc/hosts. This is probably a crock, but many people have hosts files without FQDNs. Remember: domain names are your friends. Log a high-priority message if you can't find your FQDN during startup. Suggested by Simon Barnes of Schlumberger Limited. When using Hesiod, initialize it early to improve error reporting. Patch from Don Lewis of Silicon Systems, Inc. Apparently at least some versions of Linux have a 90 !minute! TCP connection timeout in the kernel. Add a new "connect" timeout to limit this time. Defaults to zero (use whatever the kernel provides). Based on code contributed by J.R. Oldroyd of TerraNet. Under some circumstances, a failed message would not be properly removed from the queue, causing tons of bogus error messages. (This fix eliminates the problematic EF_KEEPQUEUE flag.) Problem noted by Allan E Johannesen and Gregory Neil Shapiro of WPI. PORTABILITY FIXES: On IRIX 5.x, there was an inconsistency in the setting of sendmail.st location. Change the Makefile to install it in /var/sendmail.st to match the OSTYPE file and SGI standards. From Andre . Support for Fujitsu/ICL UXP/DS (For the DS/90 Series) from Diego R. Lopez . Linux compilation patches from J.R. Oldroyd of TerraNet, Inc. LUNA 2 Mach patches from Motonori Nakamura. SunOS Makefile was including -ldbm, which is for the old dbm library. The ndbm library is part of libc. CONFIG: avoid bouncing ``user@host.'' (note trailing dot) with ``local configuration error'' in nullclient configuration. Patch from Gregory Neil Shapiro of WPI. CONFIG: don't allow an alias file in nullclient configurations -- since all addresses are relayed, they give errors during rebuild. Suggested by Per Hedeland of Ericsson. CONFIG: local mailer on Solaris 2 should always get a -f flag because otherwise the F=S causes the From_ line to imply that root is the sender. Problem pointed out by Claude Scarpelli of Infobiogen (France). NEW FILES: cf/feature/use_ct_file.m4 (omitted from 8.7 by mistake) src/Makefiles/Makefile.KSR (omitted from 8.7 by mistake) src/Makefiles/Makefile.UXPDS 8.7/8.7 1995/09/16 Fix a problem that could cause sendmail to run out of file descriptors due to a trashed data structure after a vfork. Fix from Brian Coan of the Institute for Global Communications. Change the VRFY response if you have disabled VRFY -- some people seemed to think that it was too rude. Avoid reference to uninitialized file descriptor if HASFLOCK was not defined. This was used "safely" in the sense that it only did a stat, but it would have set the map modification time improperly. Problem pointed out by Roy Mongiovi of Georgia Tech. Clean up the Subject: line on warning messages and return receipts so that they don't say "Returned mail:"; this can be confusing. Move ruleset entry/exit debugging from 21.2 to 21.1 -- this is useful enough to make it worthwhile printing on "-d". Avoid logging alias statistics every time you read the alias file on systems with no database method compiled in. If you have a name with a trailing dot, and you try looking it up using gethostbyname without the dot (for /etc/hosts compatibility), be sure to turn off RES_DEFNAMES and RES_DNSRCH to avoid finding the wrong name accidentally. Problem noted by Charles Amos of the University of Maryland. Don't do timeouts in collect if you are not running SMTP. There is nothing that says you can't have a long running program piped into sendmail (possibly via /bin/mail, which just execs sendmail). Problem reported by Don "Truck" Lewis of Silicon Systems. Try gethostbyname() even if the DNS lookup fails iff option I is not set. This allows you to have hosts listed in NIS or /etc/hosts that are not known to DNS. It's normally a bad idea, but can be useful on firewall machines. This should really be broken out on a separate flag, I suppose. Avoid compile warnings against BIND 4.9.3, which uses function prototypes. From Don Lewis of Silicon Systems. Avoid possible incorrect diagnosis of DNS-related errors caused by things like attempts to resolve uucp names using $[ ... $] -- the fix is to clear h_errno at appropriate times. From Kyle Jones of UUNET. SECURITY: avoid denial-of-service attacks possible by destroying the alias database file by setting resource limits low. This involves adding two new compile-time options: HASSETRLIMIT (indicating that setrlimit(2) support is available) and HASULIMIT (indicating that ulimit(2) support is available -- the Release 3 form is used). The former is assumed on BSD-based systems, the latter on System V-based systems. Attack noted by Phil Brandenberger of Swarthmore University. New syntaxes in test (-bt) mode: ``.Dmvalue'' will define macro "m" to "value". ``.Ccvalue'' will add "value" to class "c". ``=Sruleset'' will dump the contents of the indicated ruleset. ``=M'' will display the known mailers. ``-ddebug-spec'' is equivalent to the command-line -d debug flag. ``$m'' will print the value of macro $m. ``$=c'' will print the contents of class $=c. ``/mx host'' returns the MX records for ``host''. ``/parse address'' will parse address, returning the value of crackaddr (essentially, the comment information) and the parsed address. ``/try mailer address'' will rewrite address into the form it will have when presented to the indicated mailer. ``/tryflags flags'' will set flags used by parsing. The flags can be `H' for header or `E' for envelope, and `S' for sender or `R' for recipient. These can be combined, so `HR' sets flags for header recipients. ``/canon hostname'' will try to canonify hostname and return the result. ``/map mapname key'' will look up `key' in the indicated `mapname' and return the result. Somewhat better handling of UNIX-domain socket addresses -- it should show the pathname rather than hex bytes. Restore ``-ba'' mode -- this reads a file from stdin and parses the header for envelope sender information and uses CR-LF as message terminators. It was thought to be obsolete (used only for Arpanet NCP protocols), but it turns out that the UK ``Grey Book'' protocols require that functionality. Fix a fix in previous release -- if gethostname and gethostbyname return a name without dots, and if an attempt to canonify that name fails, wait one minute and try again. This can result in an extra 60 second delay on startup if your system hostname (as returned by hostname(1)) has no dot and no names listed in /etc/hosts or your NIS map have a dot. Check for proper domain name on HELO and EHLO commands per RFC 1123 section 5.2.5. Problem noted by Thomas Dwyer III of Michigan Technological University. Relax chownsafe rules slightly -- old version said that if you can't tell if _POSIX_CHOWN_RESTRICTED is set (that is, if fpathconf returned EINVAL or ENOSYS), assume that chown is not safe. The new version falls back to whether you are on a BSD system or not. This is important for SunOS, which apparently always returns one of those error codes. This impacts whether you can mail to files or not. Syntax errors such as unbalanced parentheses in the configuration file could be omitted if you had "Oem" prior to the syntax error in the config file. Change to always print the error message. It was especially weird because it would cause a "warning" message to be sent to the Postmaster for every message sent (but with no transcript). Problem noted by Gregory Paris of Motorola. Rewrite collect and putbody to handle full 8-bit data, including zero bytes. These changes are internally extensive, but should have minimal impact on external function. Allow full words for option names -- if the option letter is (apparently) a space, then take the word following -- e.g., O MatchGECOS=TRUE The full list of old and new names is as follows: 7 SevenBitInput 8 EightBitMode A AliasFile a AliasWait B BlankSub b MinFreeBlocks/MaxMessageSize C CheckpointInterval c HoldExpensive D AutoRebuildAliases d DeliveryMode E ErrorHeader e ErrorMode f SaveFromLine F TempFileMode G MatchGECOS H HelpFile h MaxHopCount i IgnoreDots I ResolverOptions J ForwardPath j SendMimeErrors k ConnectionCacheSize K ConnectionCacheTimeout L LogLevel l UseErrorsTo m MeToo n CheckAliases O DaemonPortOptions o OldStyleHeaders P PostmasterCopy p PrivacyOptions Q QueueDirectory q QueueFactor R DontPruneRoutes r, T Timeout S StatusFile s SuperSafe t TimeZoneSpec u DefaultUser U UserDatabaseSpec V FallbackMXHost v Verbose w TryNullMXList x QueueLA X RefuseLA Y ForkEachJob y RecipientFactor z ClassFactor Z RetryFactor The old macros that passed information into sendmail have been changed to options; those correspondences are: $e SmtpGreetingMessage $l UnixFromLine $o OperatorChars $q (deleted -- not necessary) To avoid possible problems with an older sendmail, configuration level 6 is accepted by this version of sendmail; any config file using the new names should specify "V6" in the configuration. Change address parsing to properly note that a phrase before a colon and a trailing semicolon are essentially the same as text outside of angle brackets (i.e., sendmail should treat them as comments). This is to handle the ``group name: addr1, addr2, ..., addrN;'' syntax (it will assume that ``group name:'' is a comment on the first address and the ``;'' is a comment on the last address). This requires config file support to get right. It does understand that :: is NOT this syntax, and can be turned off completely by setting the ColonOkInAddresses option. Level 6 config files added with new mailer flags: A Addresses are aliasable. i Do udb rewriting on envelope as well as header sender lines. Applies to the from address mailer flags rather than the recipient mailer flags. j Do udb rewriting on header recipient addresses. Applies to the sender mailer flags rather than the recipient mailer flags. k Disable check for loops when doing HELO command. o Always run as the mail recipient, even on local delivery. w Check for an /etc/passwd entry for this user. 5 Pass addresses through ruleset 5. : Check for :include: on this address. | Check for |program on this address. / Check for /file on this address. @ Look up sender header addresses in the user database. Applies to the mailer flags for the mailer corresponding to the envelope sender address, rather than to recipient mailer flags. Pre-level 6 configuration files set A, w, 5, :, |, /, and @ on the "local" mailer, the o flag on the "prog" and "*file*" mailers, and the ColonOkInAddresses option. Eight-to-seven bit MIME conversions. This borrows ideas from John Beck of Hewlett-Packard, who generously contributed their implementation to me, which I then didn't use (see mime.c for an explanation of why). This adds the EightBitMode option (a.k.a. `8') and an F=8 mailer flag to control handling of 8-bit data. These have to cope with two types of 8-bit data: unlabelled 8-bit data (that is, 8-bit data that is entered without declaring it as 8-bit MIME -- technically this is illegal according to the specs) and labelled 8-bit data (that is, it was declared as 8BITMIME in the ESMTP session or by using the -B8BITMIME command line flag). If the F=8 mailer flag is set then 8-bit data is sent to non-8BITMIME machines instead of converting to 7 bit (essentially using just-send-8 semantics). The values for EightBitMode are: m convert unlabelled 8-bit input to 8BITMIME, and do any necessary conversion of 8BITMIME to 7BIT (essentially, the full MIME option). p pass unlabelled 8-bit input, but convert labelled 8BITMIME input to 7BIT as required (default). s strict adherence: reject unlabelled 8-bit input, convert 8BITMIME to 7BIT as required. The F=8 flag is ignored. Unlabelled 8-bit data is rejected in mode `s' regardless of the setting of F=8. Add new internal class 'n', which is the set of MIME Content-Types which can not be 8 to 7 bit encoded because of other considerations. Types "multipart/*" and "message/*" are never directly encoded (although their components can be). Add new internal class 's', which is the set of subtypes of the MIME message/* content type that can be treated as though they are an RFC822 message. It is predefined to have "rfc822". Suggested By Kari Hurtta. Add new internal class 'e'. This is the set of MIME Content-Transfer-Encodings that can be converted to a seven bit format (Quoted-Printable or Base64). It is preinitialized to contain "7bit", "8bit", and "binary". Add C=charset mailer parameter and the the DefaultCharSet option (no short name) to set the default character set to use in the Content-Type: header when doing encoding of an 8-bit message which isn't marked as MIME into MIME format. If the C= parameter is set on the Envelope From address, use that as the default encoding; else use the DefaultCharSet option. If neither is set, it defaults to "unknown-8bit" as suggested by RFC 1428 section 3. Allow ``U=user:group'' field in mailer definition to set a default user and group that a mailer will be executed as. This overrides the 'u' and 'g' options, and if the `F=S' flag is also set, it is the uid/gid that will always be used (that is, the controlling address is ignored). The values may be numeric or symbolic; if only a symbolic user is given (no group) that user's default group in the passwd file is used as the group. Based on code donated by Chip Rosenthal of Unicom. Allow `u' option to also accept user:group as a value, in the same fashion as the U= mailer option. Add the symbolic time zone name in the Arpanet format dates (as a comment). This adds a new compile-time configuration flag: TZ_TYPE can be set to TZ_TM_NAME (use the value of (struct tm *)->tm_name), TZ_TM_ZONE (use the value of (struct tm *)->tm_zone), TZ_TZNAME (use extern char *tzname[(struct tm *)->tm_isdst]), TZ_TIMEZONE (use timezone()), or TZ_NONE (don't include the comment). Code from Chip Rosenthal. The "Timeout" option (formerly "r") is extended to allow suboptions. For example, O Timeout.helo = 2m There are also two new suboptions "queuereturn" and "queuewarn"; these subsume the old T option. Thus, to set them both the preferred new syntax is O Timeout.queuereturn = 5d O Timeout.queuewarn = 4h Sort queue by host name instead of by message priority if the QueueSortOrder option (no short name) is set is set to ``host''. This makes better use of the connection cache, but may delay more ``interactive'' messages behind large backlogs under some circumstances. This is probably a good option if you have high speed links or don't do lots of ``batch'' messages, but less good if you are using something like PPP on a 14.4 modem. Based on code contributed by Roy Mongiovi of Georgia Tech (my main contribution was to make it configurable). Save i-number of df file in qf file to simplify rebuilding of queue after disastrous disk crash. Suggested by Kyle Jones of UUNET; closely based on code from KJS DECWRL code written by Paul Vixie. NOTA BENE: The qf files produced by 8.7 are NOT back compatible with 8.6 -- that is, you can convert from 8.6 to 8.7, but not the other direction. Add ``F=d'' mailer flag to disable all use of angle brackets in route-addrs in envelopes; this is because in some cases they can be sent to the shell, which interprets them as I/O redirection. Don't include error file (option E) with return-receipts; this can be confusing. Don't send "Warning: cannot send" messages to owner-* or *-request addresses. Suggested by Christophe Wolfhugel of the Institut Pasteur, Paris. Allow -O command line flag to set long form options. Add "MinQueueAge" option to set the minimum time between attempts to run the queue. For example, if the queue interval (-q value) is five minutes, but the minimum queue age is fifteen minutes, jobs won't be tried more often than once every fifteen minutes. This can be used to give you more responsiveness if your delivery mode is set to queue-only. Allow "fileopen" timeout (default: 60 seconds) for opening :include: and .forward files. Add "-k", "-v", and "-z" flags to map definitions; these set the key field name, the value field name, and the field delimiter. The field delimiter can be a single character or the sequence "\t" or "\n" for tab or newline. These are for use by NIS+ and similar access methods. Change maps to always strip quotes before lookups; the -q flag turns off this behavior. Suggested by Motonori Nakamura. Add "nisplus" map class. Takes -k and -v flags to choose the key and value field names respectively. Code donated by Sun Microsystems. Add "hesiod" map class. The "file name" is used as the "HesiodNameType" parameter to hes_resolve(3). Returns the first value found for the match. Code donated by Scott Hutton of Indiana University. Add "netinfo" (NeXT NetInfo) map class. Maps can have a -k flag to specify the name of the property that is searched as the key and a -v flag to specify the name of the property that is returned as the value (defaults to "members"). The default map is "/aliases". Some code based on code contributed by Robert La Ferla of Hot Software. Add "text" map class. This does slow, linear searches through text files. The -z flag specifies a column delimiter (defaults to any sequence of white space), the -k flag sets the key column number, and the -v flag sets the value column number. Lines beginning with `#' are treated as comments. Add "program" map class to execute arbitrary programs. The search key is presented as the last argument; the output is one line read from the programs standard output. Exit statuses are from sysexits.h. Add "sequence" map class -- searches maps in sequence until it finds a match. For example, the declarations: Kmap1 ... Kmap2 ... Kmapseq sequence map1 map2 defines a map "mapseq" that first searches map1; if the value is found it is returned immediately, otherwise map2 is searched and the value returned. Add "switch" map class. This is much like "sequence" except that the ordering is fetched from an external file, usually the system service switch. The parameter is the name of the service to switch on, and the maps that it will use are the name of the switch map followed by ".service_type". For example, if the declaration of the map is Ksample switch hosts and the system service switch specifies that hosts are looked up using dns and nis in that order, then this is equivalent to Ksample sequence sample.dns sample.nis The subordinate maps (sample.*) must already be defined. Add "user" map class -- looks up users using getpwnam. Takes a "-v field" flag on the definition that tells what passwd entry to return -- legal values are name, passwd, uid, gid, gecos, dir, and shell. Generally expected to be used with the -m (matchonly) flag. Add "bestmx" map class -- returns the best MX value for the host listed as the value. If there are several "best" MX records for this host, one will be chosen at random. Add "userdb" map class -- looks up entries in the user database. The "file name" is actually the tag that will be used, typically "mailname". If there are multiple entries matching the name, the one chosen is undefined. Add multiple queue timeouts (both return and warning). These are set by the Precedence: or Priority: header fields to one of three values. If a Priority: is set and has value "normal", "urgent", or "non-urgent" the corresponding timeouts are used. If no priority is set, the Precedence: is consulted; if negative, non-urgent timeouts are used; if greater than zero, urgent timeouts are used. Otherwise, normal timeouts are used. The timeouts are set by setting the six timeouts queue{warn,return}.{urgent,normal,non-urgent}. Fix problem when a mail address is resolved to a $#error mailer with a temporary failure indication; it works in SMTP, but when delivering locally the mail is silently discarded. This patch, from Kyle Jones of UUNET, bounces it instead of queueing it (queueing is very hard). When using /etc/hosts or NIS-style lookups, don't assume that the first name in the list is the best one -- instead, search for the first one with a dot. For example, if an /etc/hosts entry reads 128.32.149.68 mammoth mammoth.CS.Berkeley.EDU this change will use the second name as the canonical machine name instead of the initial, unqualified name. Change dequote map to replace spaces in quoted text with a value indicated by the -s flag on the dequote map definition. For example, ``Mdequote dequote -s_'' will change "Foo Bar" into an unquoted Foo_Bar instead of leaving it quoted (because of the space character). Suggested by Dan Oscarsson for use in X.400 addresses. Implement long macro names as ${name}; long class names can be similarly referenced as $={name} and $~{name}. Definitions are (e.g.) ``D{name}value''. Names that have a leading lower case letter or punctuation characters are reserved for internal use by sendmail; i.e., config files should use names that begin with a capital letter. Based on code contributed by Dan Oscarsson. Fix core dump if getgrgid returns a null group list (as opposed to an empty group list, that is, a pointer to a list with no members). Fix from Andrew Chang of Sun Microsystems. Fix possible core dump if malloc fails -- if the malloc in xalloc failed, it called syserr which called newstr which called xalloc.... The newstr is now avoided for "panic" messages. Reported by Stuart Kemp of James Cook University. Improve connection cache timeouts; previously, they were not even checked if you were delivering to anything other than an IPC-connected host, so a series of (say) local mail deliveries could cause cached connections to be open much longer than the specified timeout. If an incoming message exceeds the maximum message size, stop writing the incoming bytes to the queue data file, since this can fill your mqueue partition -- this is a possible denial-of-service attack. Don't reject all numeric local user names unless HESIOD is defined. It turns out that Posix allows all-numeric user names. Fix from Tony Sanders of BSDI. Add service switch support. If the local OS has a service switch (e.g., /etc/nsswitch.conf on Solaris or /etc/svc.conf on DEC systems) that will be used; otherwise, it falls back to using a local mechanism based on the ServiceSwitchFile option (default: /etc/service.switch). For example, if the service switch lists "files" and "nis" for the aliases service, that will be the default lookup order. the "files" ("local" on DEC) service type expands to any alias files you listed in the configuration file, even if they aren't actually file lookups. Option I (NameServerOptions) no longer sets the "UseNameServer" variable which tells whether or not DNS should be considered canonical. This is now determined based on whether or not "dns" is in the service list for "hosts". Add preliminary support for the ESMTP "DSN" extension (Delivery Status Notifications). DSN notifications override Return-Receipt-To: headers, which are bogus anyhow -- support for them has been removed. Add T=mts-name-type/address-type/diagnostic-type keyletter to mailer definitions to define the types used in DSN returns for MTA names, addresses, and diagnostics respectively. Extend heuristic to force running in ESMTP mode to look for the five-character string "ESMTP" anywhere in the 220 greeting message (not just the second line). This is to provide better compatibility with other ESMTP servers. Print sequence number of job when running the queue so you can easily see how much progress you have made. Suggested by Peter Wemm of DIALix. Map newlines to spaces in logged message-ids; some versions of syslog truncate the rest of the line after newlines. Suggested by Fletcher Mattox of U. Texas. Move up forking for job runs so that if a message is split into multiple envelopes you don't get "fork storms" -- this also improves the connection cache utilization. Accept "<<>>", "<<<>>>", and so forth as equivalent to "<>" for the purposes of refusing to send error returns. Suggested by Motonori Nakamura of Ritsumeikan University. Relax rules on when a file can be written when referenced from the aliases file: use the default uid/gid instead of the real uid/gid. This allows you to create a file owned by and writable only by the default uid/gid that will work all the time (without having the set-user-ID bit set). Change suggested by Shau-Ping Lo and Andrew Cheng of Sun Microsystems. Add "DialDelay" option (no short name) to provide an "extra" delay for dial on demand systems. If this is non-zero and a connect fails, sendmail will wait this long and then try again. If it takes longer than the kernel timeout interval to establish the connection, this option can give the network software time to establish the link. The default units are seconds. Move logging of sender information to be as early as possible; previously, it could be delayed a while for SMTP mail sent to aliases. Suggested by Brad Knowles of the Defense Information Systems Agency. Call res_init() before setting RES_DEBUG; this is required by BIND 4.9.3, or so I'm told. From Douglas Anderson of the National Computer Security Center. Add xdelay= field in logs -- this is a transaction delay, telling you how long it took to deliver to this address on the last try. It is intended to be used for sorting mailing lists to favor "quick" addresses. Provided for use by the mailprio scripts (see below). If a map cannot be opened, and that map is non-optional, and an address requires that map for resolution, queue the map instead of bouncing it. This involves creating a pseudo-class of maps called "bogus-map" -- if a required map cannot be opened, the class is changed to bogus-map; all queries against bogus-map return "tempfail". The bogus-map class is not directly accessible. A sample implementation was donated by Jem Taylor of Glasgow University Computing Service. Fix a possible core dump when mailing to a program that talks SMTP on its standard input. Fix from Keith Moore of the University of Kentucky. Make it possible to resolve filenames to $#local $: @ /filename; previously, the "@" would cause it to not be recognized as a file. Problem noted by Brian Hill of U.C. Davis. Accept a -1 signal to re-exec the daemon. This only works if argv[0] is a full path to sendmail. Fix bug in "addr=..." field in O option on little-endian machines -- the network number wasn't being converted to network byte order. Patch from Kurt Lidl of Pix Technologies Corporation. Pre-initialize the resolver early on; this is to avoid a bug with BIND 4.9.3 that can cause the _res.retry field to get reset to zero, causing all name server lookups to time out. Fix from Matt Day of Artisoft. Restore T line (trusted users) in config file -- but instead of locking out the -f flag, they just tell whether or not an X-Authentication-Warning: will be added. This really just creates new entries in class 't', so "Ft/file/name" can be used to read trusted user names from a file. Trusted users are also allowed to execute programs even if they have a shell that isn't in /etc/shells. Improve NEWDB alias file rebuilding so it will create them properly if they do not already exist. This had been a MAYBENEXTRELEASE feature in 8.6.9. Check for @:@ entry in NIS maps before starting up to avoid (but not prevent, sigh) race conditions. This ought to be handled properly in ypserv, but isn't. Suggested by Michael Beirne of Motorola. Refuse connections if there isn't enough space on the filesystem holding the queue. Contributed by Robert Dana of Wolf Communications. Skip checking for directory permissions in the path to a file when checking for file permissions iff setreuid() succeeded -- it is unnecessary in that case. This avoids significant performance problems when looking for .forward files. Based on a suggestion by Win Bent of USC. Allow symbolic ruleset names. Syntax can be "Sname" to get an arbitrary ruleset number assigned or "Sname = integer" to assign a specific ruleset number. Reference is $>name_or_number. Names can be composed of alphas, digits, underscore, or hyphen (first character must be non-numeric). Allow -o flag on AliasFile lines to make the alias file optional. From Bryan Costales of ICSI. Add NoRecipientAction option to handle the case where there is no legal recipient header in the message. It can take on values: None Leave the message as is. The message will be passed on even though it is in technically illegal syntax. Add-To Add a To: header with any recipients that it can find from the envelope. This risks exposing Bcc: recipients. Add-Apparently-To Add an Apparently-To: header. This has almost no redeeming social value, and is provided only for back compatibility. Add-To-Undisclosed Add a header reading To: undisclosed-recipients:; which will have the effect of making the message legal without exposing Bcc: recipients. Add-Bcc To add an empty Bcc: header. There is a chance that mailers down the line will delete this header, which could cause exposure of Bcc: recipients. The default is NoRecipientAction=None. Truncate (rather than delete) Bcc: lines in the header. This should prevent later sendmails (at least, those that don't themselves delete Bcc:) from considering this message to be non-conforming -- although it does imply that non-blind recipients can see that a Bcc: was sent, albeit not to whom. Add SafeFileEnvironment option. If declared, files named as delivery targets must be regular files in addition to the regular checks. Also, if the option is non-null then it is used as the name of a directory that is used as a chroot(2) environment for the delivery; the file names listed in an alias or forward should include the name of this root. For example, if you run with O SafeFileEnvironment=/arch then aliases should reference "/arch/rest/of/path". If a value is given, sendmail also won't try to save to /usr/tmp/dead.letter (instead it just leaves the job in the queue as Qfxxxxxx). Inspired by *Hobbit*'s sendmail patch kit. Support -A flag for alias files; this will comma concatenate like entries. For example, given the aliases: list: member1 list: member2 and an alias file declared as: OAhash:-A /etc/aliases the final alias inserted will be "list: member1,member2"; without -A you will get an error on the second and subsequent alias for "list". Contributed by Bryan Costales of ICSI. Line-buffer transcript file. Suggested by Liudvikas Bukys. Fix a problem that could cause very long addresses to core dump in some special circumstances. Problem pointed out by Allan Johannesen. (Internal change.) Change interface to expand() (macro expansion) to be simpler and more consistent. Delete check for funny qf file names. This didn't really give any extra security and caused some people some problems. (If you -really- want this, define PICKY_QF_NAME_CHECK at compile time.) Suggested by Kyle Jones of UUNET. (Internal change.) Change EF_NORETURN to EF_NO_BODY_RETN and merge with DSN code; this is simpler and more consistent. This may affect some people who have written their own checkcompat() routine. (Internal change.) Eliminate `D' line in qf file. The df file is now assumed to be the same name as the qf file (with the `q' changed to a `d', of course). Avoid forking for delivery if all recipient mailers are marked as "expensive" -- this can be a major cost on some systems. Essentially, this forces sendmail into "queue only" mode if all it is going to do is queue anyway. Avoid sending a null message in some rather unusual circumstances (specifically, the RCPT command returns a temporary failure but the connection is lost before the DATA command). Fix from Scott Hammond of Secure Computing Corporation. Change makesendmail to use a somewhat more rational naming scheme: Makefiles and obj directories are named $os.$rel.$arch, where $os is the operating system (e.g., SunOS), $rel is the release number (e.g., 5.3), and $arch is the machine architecture (e.g., sun4). Any of these can be omitted, and anything after the first dot in a release number can be replaced with "x" (e.g., SunOS.4.x.sun4). The previous version used $os.$arch.$rel and was rather less general. Change makesendmail to do a "make depend" in the target directory when it is being created. This involves adding an empty "depend:" entry in most Makefiles. Ignore IDENT return value if the OSTYPE field returns "OTHER", as indicated by RFC 1413. Pointed out by Kari Hurtta of the Finnish Meteorological Institute. Fix problem that could cause multiple responses to DATA command on header syntax errors (e.g., lines beginning with colons). Problem noted by Jens Thomassen of the University of Oslo. Don't let null bytes in headers cause truncation of the rest of the header. Log Authentication-Warning:s. Suggested by Motonori Nakamura. Increase timeouts on message data puts to allow time for receivers to canonify addresses in headers on the fly. This is still a rather ugly heuristic. From Motonori Nakamura. Add "HasWildcardMX" suboption to ResolverOptions; if set, MX records are not used when canonifying names, and when MX lookups are done for addressing they must be fully qualified. This is useful if you have a wildcard MX record, although it may cause other problems. In general, don't use wildcard MX records. Patch from Motonori Nakamura. Eliminate default two-line SMTP greeting message. Instead of adding an extra "ESMTP spoken here" line, the word "ESMTP" is added between the first and second word of the first line of the greeting message (i.e., immediately after the host name). This eliminates the need for the BROKEN_SMTP_PEERS compile flag. Old sendmails won't see the ESMTP, but that's acceptable because SIZE was the only useful extension that old sendmails understand. Avoid gethostbyname calls on UNIX domain sockets during SIGUSR1 invoked state dumps. From Masaharu Onishi. Allow on-line comments in .forward and :include: files; they are introduced by the string "#@#", where is a space or a tab. This is intended for native representation of non-ASCII sets such as Japanese, where existing encodings would be unreadable or would lose data -- for example, NAKAMURA Motonori (romanized/less information) =?ISO-2022-JP?B?GyRCQ2ZCPBsoQg==?= =?ISO-2022-JP?B?GyRCQUdFNRsoQg==?= (with MIME encoding, not human readable) #@# ^[$BCfB<^[(B ^[$BAGE5^[(B (native encoding with ISO-2022-JP) The last form is human readable in the Japanese environment. Based on a fix from (surprise!) Motonori Nakamura. Don't make SMTP error returns on MAIL FROM: line be "sticky" for all messages to that host; these are most frequently associated with addresses rather than the host, with the exception of 421 (service shutting down). The effect was to cause queues to sometimes take an excessive time to flush. Reported by Robert Sargent of Southern Geographics Technologies and Eric Prestemon of American University. Add Nice=N mailer option to set the niceness at which a mailer will run. This is actually a relative niceness (that is, an increment on the background value). Log queue runs that are skipped due to high loads. They are logged at LOG_INFO priority iff the log level is > 8. Contributed by Bruce Nagel of Data General. Allow the error mailer to accept a DSN-style error status code instead of an sysexits status code in the host part. Anything with a dot will be interpreted as a DSN-style code. Add new mailer flag: F=3 will tell translations to Quoted-Printable to encode characters that might be munged by an EBCDIC system in addition to the set required by RFC 1521. The additional characters are !, ", #, $, @, [, \, ], ^, `, {, |, }, and ~. (Think of "IBM 360" as the mnemonic for this flag.) Change check for mailing to files to look for a pathname of [FILE] rather than looking for the mailer named *file*. The mapping of leading slashes still goes to the *file* mailer. This allows you to implement the *file* mailer as a separate program, for example, to insert a Content-Length: header or do special security policy. However, note that the usual initial checking for the file permissions is still done, and the program in question needs to be very careful about how it does the file write to avoid security problems. Be able to read ~root/.forward even if the path isn't accessible to regular users. This is disrecommended because sendmail sometimes does not run as root (e.g., when an unsafe option is specified on the command line), but should otherwise be safe because .forward files must be owned by the user for whom mail is being forwarded, and cannot be a symbolic link. Suggested by Forrest Aldrich of Wang Laboratories. Add new "HostsFile" option that is the pathname to the /etc/hosts file. This is used for canonifying hostnames when the service type is "files". Implement programs on F (read class from file) line. The syntax is Fc|/path/to/program to read the output from the program into class "c". Probe the network interfaces to find alternate names for this host. Requires the SIOCGIFCONF ioctl call. Code contributed by SunSoft. Add "E" configuration line to set or propagate environment variables into children. "E" will propagate the named variable from the environment when sendmail was invoked into any children it calls; "E=" sets the named variable to the indicated value. Any variables not explicitly named will not be in the child environment. However, sendmail still forces an "AGENT=sendmail" environment variable, in part to enforce at least one environment variable, since many programs and libraries die horribly if this is not guaranteed. Change heuristic for rebuilding both NEWDB and NDBM versions of alias databases -- new algorithm looks for the substring "/yp/" in the file name. This is more portable and involves less overhead. Suggested by Motonori Nakamura. Dynamically allocate the queue work list so that you don't lose jobs in large queue runs. The old QUEUESIZE compile parameter is replaced by QUEUESEGSIZE (the unit of allocation, which should not need to be changed) and the MaxQueueRunSize option, which is the absolute maximum number of jobs that will ever be handled in a single queue run. Based on code contributed by Brian Coan of the Institute for Global Communications. Log message when a message is dropped because it exceeds the maximum message size. Suggested by Leo Bicknell of Virginia Tech. Allow trusted users (those on a T line or in $=t) to use -bs without an X-Authentication-Warning: added. Suggested by Mark Thomas of Mark G. Thomas Consulting. Announce state of compile flags on -d0.1 (-d0.10 throws in the OS-dependent defines). The old semantic of -d0.1 to not run the daemon in background has been moved to -d99.100, and the old 52.5 flag (to avoid disconnect() from closing all output files) has been moved to 52.100. This makes things more consistent (flags below .100 don't change semantics) and separates out the backgrounding so that it doesn't happen automatically on other unrelated debugging flags. If -t is used but no addresses are found in the header, give an error message rather than just doing nothing. Fix from Motonori Nakamura. On systems (like SunOS) where the effective gid is not necessarily included in the group list returned by getgroups(), the `restrictmailq' option could sometimes cause an authorized user to not be able to use `mailq'. Fix from Charles Hannum of MIT. Allow symbolic service names for [IPC] mailers. Suggested by Gerry Magennis of Logica International. Add DontExpandCnames option to prevent $[ ... $] from expanding CNAMEs when running DNS. For example, if the name FTP.Foo.ORG is a CNAME for Cruft.Foo.ORG, then when sitting on a machine in the Foo.ORG domain a lookup of "FTP" returns "Cruft.Foo.ORG" if this option is not set, or "FTP.Foo.ORG" if it is set. This is technically illegal under RFC 822 and 1123, but the IETF is moving toward legalizing it. Note that turning on this option is not sufficient to guarantee that a downstream neighbor won't rewrite the address for you. Add "-m" flag to makesendmail script -- this tells you what object directory and Makefile it will use, but doesn't actually do the make. Do some additional checking on the contents of the qf file to try to detect attacks against the qf file. In particular, abort on any line beginning "From ", and add an "end of file" line -- any data after that line is prohibited. Always use /etc/sendmail.cf, regardless of the arbitrary vendor choices. This can be overridden in the Makefile by using either -DUSE_VENDOR_CF_PATH to get the vendor location (to the extent that we know it) or by defining _PATH_SENDMAILCF (which is a "hard override"). This allows sendmail 8 to have more consistent installation instructions. Allow macros on `K' line in config file. Suggested by Andrew Chang of Sun Microsystems. Improved symbol table hash function from Eric Wassenaar. This one is at least 50% faster. Fix problem that didn't notice that timeout on file open was a transient error. Fix from Larry Parmelee of Cornell University. Allow comments (lines beginning with a `#') in files read for classes. Suggested by Motonori Nakamura. Make SIGINT (usually ^C) in test mode return to the prompt instead of dropping out entirely. This makes testing some of the name server lookups easier to deal with when there are hung servers. From Motonori Nakamura. Add new ${opMode} macro that is set to the current operation mode (e.g., `s' for -bs, `t' for -bt, etc.). Suggested by Claude Marinier . Add new delivery mode (Odd) that defers all map lookups to queue runs. Kind of like queue-only mode (Odq) except it tries to avoid any external service requests; for dial-on-demand hosts that want to minimize DNS lookups when mail is being queued. For this to work you will also have to make sure that gethostbyname of your local host name does not do a DNS lookup. Improved handling of "out of space" conditions from John Myers of Carnegie Mellon. Improved security for mailing to files on systems that have fchmod(2) support. Improve "cannot send message for N days" message -- now says "could not send for past N days". Suggested by Tom Moore of AT&T Global Information Solutions. Less misleading Subject: line on messages sent to postmaster only. From Motonori Nakamura. Avoid duplicate error messages on bad command line flags. From Motonori Nakamura. Better error message for case where ruleset 0 falls off the end or otherwise does not resolve to a canonical triple. Fix a problem that could cause multiple bounce messages if a bad address was sent along with a good address to an SMTP site where that SMTP site returned a 4yz code in response to the final dot of the data. Problem reported by David James of British Telecom. Add "volatile" declarations so that gcc -O2 will work. Patches from Alexander Dupuy of System Management ARTS. Delete duplicates in MX lists -- believe it or not, there are sites that list the same host twice in an MX list. This deletion only works on adjacent preferences, so an MX list that had A=5, B=10, A=15 would leave both As, but one that had A=5, A=10, B=15 would reduce to A, B. This is intentional, just in case there is something weird I haven't thought of. Suggested by Barry Shein of Software Tool & Die. SECURITY: .forward files cannot be symbolic links. If they are, a bad guy can read your private files. PORTABILITY FIXES: Solaris 2 from Rob McMahon . System V Release 4 from Motonori Nakamura of Ritsumeikan University. This expands the disk size checking to include all (?) SVR4 configurations. System V Release 4 from Kimmo Suominen -- initgroups(3) and setrlimit(2) are both available. System V Release 4 from sob@sculley.ffg.com -- some versions apparently "have EX_OK defined in other headerfiles." Linux Makefile typo. Linux getusershell(3) is broken in Slackware 2.0 -- from Andrew Pam of Xanadu Australia. More Linux tweaking from John Kennedy of California State University, Chico. Cray changes from Eric Wassenaar: ``On Cray, shorts, ints, and longs are all 64 bits, and all structs are multiples of 64 bits. This means that the sizeof operator returns only multiples of 8. This requires adaptation of code that really deals with 32 bit or 16 bit fields, such as IP addresses or nameserver fields.'' DG/UX 5.4.3 from Mark T. Robinson . To get the old behavior, use -DDGUX_5_4_2. DG/UX hack: add _FORCE_MAIL_LOCAL_=yes environment variable to fix bogus /bin/mail behavior. Tandem NonStop-UX from Rick McCarty . This also cleans up some System V Release 4 compile problems. Solaris 2: sendmail.cw file should be in /etc/mail to match all the other configuration files. Fix from Glenn Barry of Emory University. Solaris 2.3: compile problem in conf.c. Fix from Alain Nissen of the University of Liege, Belgium. Ultrix: freespace calculation was incorrect. Fix from Takashi Kizu of Osaka University. SVR4: running in background gets a SIGTTOU because the emulation code doesn't realize that "getpeername" doesn't require reading the file. Fix from Peter Wemm of DIALix. Solaris 2.3: due to an apparent bug in the socket emulation library, sockets can get into a "wedged" state where they just return EPROTO; closing and re-opening the socket clears the problem. Fix from Bob Manson of Ohio State University. Hitachi 3050R & 3050RX running HI-UX/WE2: portability fixes from Akihiro Hashimoto ("Hash") of Chiba University. AIX changes to allow setproctitle to work from Rainer Schöpf of Zentrum für Datenverarbeitung der Universität Mainz. AIX changes for load average from Ed Ravin of NASA/Goddard. SCO Unix from Chip Rosenthal of Unicom (code was using the wrong statfs call). ANSI C fixes from Adam Glass (NetBSD project). Stardent Titan/ANSI C fixes from Kate Hedstrom of Rutgers University. DG-UX fixes from Bruce Nagel of Data General. IRIX64 updates from Mark Levinson of the University of Rochester Medical Center. Altos System V (``the first UNIX/XENIX merge the Altos did for their Series 1000 & Series 2000 line; their merged code was licensed back to AT&T and Microsoft and became System V release 3.2'') from Tim Rice . OSF/1 running on Intel Paragon from Jeff A. Earickson of Intel Scalable Systems Division. Amdahl UTS System V 2.1.5 (SVr3-based) from Janet Jackson . System V Release 4 (statvfs semantic fix) from Alain Durand of I.M.A.G. HP-UX 10.x multiprocessor load average changes from Scott Hutton and Jeff Sumler of Indiana University. Cray CSOS from Scott Bolte of Cray Computer Corporation. Unicos 8.0 from Douglas K. Rand of the University of North Dakota, Scientific Computing Center. Solaris 2.4 fixes from Sanjay Dani of Dani Communications. ConvexOS 11.0 from Christophe Wolfhugel. IRIX 4.0.5 from David Ashton-Reader of CADcentre. ISC UNIX from J. J. Bailey. HP-UX 9.xx on the 8xx series machines from Remy Giraud of Meteo France. HP-UX configuration from Tom Lane . IRIX 5.2 and 5.3 from Kari E. Hurtta. FreeBSD 2.0 from Mike Hickey of Federal Data Corporation. Sony NEWS-OS 4.2.1R and 6.0.3 from Motonori Nakamura. Omron LUNA unios-b, mach from Motonori Nakamura. NEC EWS-UX/V 4.2 from Motonori Nakamura. NeXT 2.1 from Bryan Costales. AUX patch thanks to Mike Erwin of Apple Computer. HP-UX 10.0 from John Beck of Hewlett-Packard. Ultrix: allow -DBROKEN_RES_SEARCH=0 if you are using a non-DEC resolver. Suggested by Allan Johannesen. UnixWare 2.0 fixes from Petr Lampa of the Technical University of Brno (Czech Republic). KSR OS 1.2.2 support from Todd Miller of the University of Colorado. UX4800 support from Kazuhisa Shimizu of NEC. MAKEMAP: allow -d flag to allow insertion of duplicate aliases in type ``btree'' maps. The semantics of this are undefined for regular maps, but it can be useful for the user database. MAKEMAP: lock database file while rebuilding to avoid sendmail lookups while the rebuild is going on. There is a race condition between the open(... O_TRUNC ...) and the lock on the file, but it should be quite small. SMRSH: sendmail restricted shell added to the release. This can be used as an alternative to /bin/sh for the "prog" mailer, giving the local administrator more control over what programs can be run from sendmail. MAIL.LOCAL: add this local mailer to the tape. It is not really part of the release proper, and isn't fully supported; in particular, it does not run on System V based systems and never will. CONTRIB: a patch to rmail.c from Bill Gianopoulos of Raytheon to allow rmail to compile on systems that don't have function prototypes and systems that don't have snprintf. CONTRIB: add the "mailprio" scripts that will help you sort mailing lists by transaction delay times so that addresses that respond quickly get sent first. This is to prevent very sluggish servers from delaying other peoples' mail. Contributed by Tony Sanders of BSDI. CONTRIB: add the "bsdi.mc" file as contributed by Tony Sanders of BSDI. This has a lot of comments to help people out. CONFIG: Don't have .mc files include(../m4/cf.m4) -- instead, put this on the m4 command line. On GNU m4 (which supports the __file__ primitive) you can run m4 in an arbitrary directory -- use either: m4 ${CFDIR}/m4/cf.m4 config.mc > config.cf or m4 -I${CFDIR} m4/cf.m4 config.mc > config.cf On other versions of m4 that don't support __file__, you can use: m4 -D_CF_DIR_=${CFDIR}/ ${CFDIR}/m4/cf.m4 ... (Note the trailing slash on the _CF_DIR_ definition.) Old versions of m4 will default to _CF_DIR_=.. for back compatibility. CONFIG: fix mail from <> so it will properly convert to MAILER-DAEMON on local addresses. CONFIG: fix code that was supposed to catch colons in host names. Problem noted by John Gardiner Myers of CMU. CONFIG: allow use of SMTP_MAILER_MAX in nullclient configuration. From Paul Riddle of the University of Maryland, Baltimore County. CONFIG: Catch and reject "." as a host address. CONFIG: Generalize domaintable to look up all domains, not just unqualified ones. CONFIG: Delete OLD_SENDMAIL support -- as near as I can tell, it was never used and didn't work anyway. CONFIG: Set flags A, w, 5, :, /, |, and @ on the "local" mailer and d on all mailers in the UUCP class. CONFIG: Allow "user+detail" to be aliased specially: it will first look for an alias for "user+detail", then for "user+*", and finally for "user". This is intended for forwarding mail for system aliases such as root and postmaster to a centralized hub. CONFIG: add confEIGHT_BIT_HANDLING to set option 8 (see above). CONFIG: add smtp8 mailer; this has the F=8 (just-send-8) flag set. The F=8 flag is also set on the "relay" mailer, since this is expected to be another sendmail. CONFIG: avoid qualifying all UUCP addresses sent via SMTP with the name of the UUCP_RELAY -- in some cases, this is the wrong value (e.g., when we have local UUCP connections), and this can create unreplyable addresses. From Chip Rosenthal of Unicom. CONFIG: add confRECEIVED_HEADER to change the format of the Received: header inserted into all messages. Suggested by Gary Mills of the University of Manitoba. CONFIG: Make "notsticky" the default; use FEATURE(stickyhost) to get the old behavior. I did this upon observing that almost everyone needed this feature, and that the concept I was trying to make happen didn't work with some user agents anyway. FEATURE(notsticky) still works, but it is a no-op. CONFIG: Add LUSER_RELAY -- the host to which unrecognized user names are sent, rather than immediately diagnosing them as User Unknown. CONFIG: Add SMTP_MAILER_ARGS, ESMTP_MAILER_ARGS, SMTP8_MAILER_ARGS, and RELAY_MAILER_ARGS to set the arguments for the indicated mailers. All default to "IPC $h". Patch from Larry Parmelee of Cornell University. CONFIG: pop mailer needs F=n flag to avoid "annoying side effects on the client side" and F=P to get an appropriate return-path. From Kimmo Suominen. CONFIG: add FEATURE(local_procmail) to use the procmail program as the local mailer. For addresses of the form "user+detail" the "detail" part is passed to procmail via the -a flag. Contributed by Kimmo Suominen. CONFIG: add MAILER(procmail) to add an interface to procmail for use from mailertables. This lets you execute arbitrary procmail scripts. Contributed by Kimmo Suominen. CONFIG: add T= fields (MTS type) to local, smtp, and uucp mailers. CONFIG: add OSTYPE(ptx2) for DYNIX/ptx 2.x from Sequent. From Paul Southworth of CICNet Systems Support. CONFIG: use -a$g as default to UUCP mailers, instead of -a$f. This causes the null return path to be rewritten as MAILER-DAEMON; otherwise UUCP gets horribly confused. From Michael Hohmuth of Technische Universitat Dresden. CONFIG: Add FEATURE(bestmx_is_local) to cause any hosts that list us as the best possible MX record to be treated as though they were local (essentially, assume that they are included in $=w). This can cause additional DNS traffic, but is easier to administer if this fits your local model. It does not work reliably if there are multiple hosts that share the best MX preference. Code contributed by John Oleynick of Rutgers. CONFIG: Add FEATURE(smrsh) to use smrsh (the SendMail Restricted SHell) instead of /bin/sh as the program used for delivery to programs. If an argument is included, it is used as the path to smrsh; otherwise, /usr/local/etc/smrsh is assumed. CONFIG: Add LOCAL_MAILER_MAX and PROCMAILER_MAILER_MAX to limit the size of messages to the local and procmail mailers respectively. Contributed by Brad Knowles of the Defense Information Systems Agency. CONFIG: Handle leading ``phrase:'' and trailing ``;'' as comments (just like text outside of angle brackets) in order to properly deal with ``group: addr1, ... addrN;'' syntax. CONFIG: Require OSTYPE macro (the defaults really don't apply to any real systems any more) and tweak the DOMAIN macro so that it is less likely that users will accidentally use the Berkeley defaults. Also, create some generic files that really can be used in the real world. CONFIG: Add new configuration macros to set character sets for messages _arriving from_ various mailers: LOCAL_MAILER_CHARSET, SMTP_MAILER_CHARSET, and UUCP_MAILER_CHARSET. CONFIG: Change UUCP_MAX_SIZE to UUCP_MAILER_MAX for consistency. The old name will still be accepted for a while at least. CONFIG: Implement DECNET_RELAY as spec for host to which DECNET mail (.DECNET pseudo-domain or node::user) will be sent. As with all relays, it can be ``mailer:hostname''. Suggested by Scott Hutton. CONFIG: Add MAILER(mail11) to get DECnet support. Code contributed by Barb Dijker of Labyrinth Computer Services. CONFIG: change confCHECK_ALIASES to default to False -- it has poor performance for large alias files, and this confused many people. CONFIG: Add confCF_VERSION to append local information to the configuration version number displayed during SMTP startup. CONFIG: fix some.newsgroup.usenet@local.host syntax (previously it would only work when locally addressed. Fix from Edvard Tuinder of Cistron Internet Services. CONFIG: use ${opMode} to avoid error on .REDIRECT addresses if option "n" (CheckAliases) is set when rebuilding alias database. Based on code contributed by Claude Marinier. CONFIG: Allow mailertable to have values of the form ``error:code message''. The ``code'' is a status code derived from the sysexits codes -- e.g., NOHOST or UNAVAILABLE. Contributed by David James . CONFIG: add MASQUERADE_DOMAIN(domain list) to extend the list of sender domains that will be replaced with the masquerade name. These domains will not be treated as local, but if mail passes through with sender addresses in those domains they will be replaced by the masquerade name. These can also be specified in a file using MASQUERADE_DOMAIN_FILE(filename). CONFIG: add FEATURE(masquerade_envelope) to masquerade the envelope as well as the header. Substantial improvements to this code were contributed by Per Hedeland. CONFIG: add MAILER(phquery) to define a new "ph" mailer; this can be accessed from a mailertable to do CCSO ph lookups. Contributed by Kimmo Suominen. CONFIG: add MAILER(cyrus) to define a new Cyrus mailer; this can be used to define cyrus and cyrusbb mailers (for IMAP support). Contributed by John Gardiner Myers of Carnegie Mellon. CONFIG: add confUUCP_MAILER to select default mailer to use for UUCP addressing. Suggested by Tom Moore of AT&T GIS. NEW FILES: cf/cf/cs-hpux10.mc cf/cf/cs-solaris2.mc cf/cf/cyrusproto.mc cf/cf/generic-bsd4.4.mc cf/cf/generic-hpux10.mc cf/cf/generic-hpux9.mc cf/cf/generic-osf1.mc cf/cf/generic-solaris2.mc cf/cf/generic-sunos4.1.mc cf/cf/generic-ultrix4.mc cf/cf/huginn.cs.mc cf/domain/berkeley-only.m4 cf/domain/generic.m4 cf/feature/bestmx_is_local.m4 cf/feature/local_procmail.m4 cf/feature/masquerade_envelope.m4 cf/feature/smrsh.m4 cf/feature/stickyhost.m4 cf/feature/use_ct_file.m4 cf/m4/cfhead.m4 cf/mailer/cyrus.m4 cf/mailer/mail11.m4 cf/mailer/phquery.m4 cf/mailer/procmail.m4 cf/ostype/amdahl-uts.m4 cf/ostype/bsdi2.0.m4 cf/ostype/hpux10.m4 cf/ostype/irix5.m4 cf/ostype/isc4.1.m4 cf/ostype/ptx2.m4 cf/ostype/unknown.m4 contrib/bsdi.mc contrib/mailprio contrib/rmail.oldsys.patch mail.local/mail.local.0 makemap/makemap.0 smrsh/README smrsh/smrsh.0 smrsh/smrsh.8 smrsh/smrsh.c src/Makefiles/Makefile.CSOS src/Makefiles/Makefile.EWS-UX_V src/Makefiles/Makefile.HP-UX.10 src/Makefiles/Makefile.IRIX.5.x src/Makefiles/Makefile.IRIX64 src/Makefiles/Makefile.ISC src/Makefiles/Makefile.KSR src/Makefiles/Makefile.NEWS-OS.4.x src/Makefiles/Makefile.NEWS-OS.6.x src/Makefiles/Makefile.NEXTSTEP src/Makefiles/Makefile.NonStop-UX src/Makefiles/Makefile.Paragon src/Makefiles/Makefile.SCO.3.2v4.2 src/Makefiles/Makefile.SunOS.5.3 src/Makefiles/Makefile.SunOS.5.4 src/Makefiles/Makefile.SunOS.5.5 src/Makefiles/Makefile.UNIX_SV.4.x.i386 src/Makefiles/Makefile.uts.systemV src/Makefiles/Makefile.UX4800 src/aliases.0 src/mailq.0 src/mime.c src/newaliases.0 src/sendmail.0 test/t_seteuid.c RENAMED FILES: cf/cf/alpha.mc => cf/cf/s2k-osf1.mc cf/cf/chez.mc => cf/cf/chez.cs.mc cf/cf/hpux-cs-exposed.mc => cf/cf/cs-hpux9.mc cf/cf/osf1-cs-exposed.mc => cf/cf/cs-osf1.mc cf/cf/s2k.mc => cf/cf/s2k-ultrix4.mc cf/cf/sunos4.1-cs-exposed.mc => cf/cf/cs-sunos4.1.mc cf/cf/ultrix4.1-cs-exposed.mc => cf/cf/cs-ultrix4.mc cf/cf/vangogh.mc => cf/cf/vangogh.cs.mc cf/domain/Berkeley.m4 => cf/domain/Berkeley.EDU.m4 cf/domain/cs-exposed.m4 => cf/domain/CS.Berkeley.EDU.m4 cf/domain/eecs-hidden.m4 => cf/domain/EECS.Berkeley.EDU.m4 cf/domain/s2k.m4 => cf/domain/S2K.Berkeley.EDU.m4 cf/ostype/hpux.m4 => cf/ostype/hpux9.m4 cf/ostype/irix.m4 => cf/ostype/irix4.m4 cf/ostype/ultrix4.1.m4 => cf/ostype/ultrix4.m4 src/Makefile.* => src/Makefiles/Makefile.* src/Makefile.AUX => src/Makefiles/Makefile.A-UX src/Makefile.BSDI => src/Makefiles/Makefile.BSD-OS src/Makefile.DGUX => src/Makefiles/Makefile.dgux src/Makefile.RISCos => src/Makefiles/Makefile.UMIPS src/Makefile.SunOS.4.0.3 => src/Makefiles/Makefile.SunOS.4.0 OBSOLETED FILES: cf/cf/cogsci.mc cf/cf/cs-exposed.mc cf/cf/cs-hidden.mc cf/cf/hpux-cs-hidden.mc cf/cf/knecht.mc cf/cf/osf1-cs-hidden.mc cf/cf/sunos3.5-cs-exposed.mc cf/cf/sunos3.5-cs-hidden.mc cf/cf/sunos4.1-cs-hidden.mc cf/cf/ultrix4.1-cs-hidden.mc cf/domain/cs-hidden.m4 contrib/rcpt-streaming src/Makefiles/Makefile.SunOS.5.x 8.6.13/8.6.12 1996/01/25 SECURITY: In some cases it was still possible for an attacker to insert newlines into a queue file, thus allowing access to any user (except root). CONFIG: no changes -- it is not a bug that the configuration version number is unchanged. 8.6.12/8.6.12 1995/03/28 Fix to IDENT code (it was getting the size of the reply buffer too small, so nothing was ever accepted). Fix from several people, including Allan Johannesen, Shane Castle of the Boulder County Information Services, and Jeff Smith of Warwick University (all arrived within a few hours of each other!). Fix a problem that could cause large jobs to run out of file descriptors on systems that use vfork() rather than fork(). 8.6.11/8.6.11 1995/03/08 The ``possible attack'' message would be logged more often than necessary if you are using Pine as a user agent. The wrong host would be reported in the ``possible attack'' message when attempted from IDENT. In some cases the syslog buffer could be overflowed when reporting the ``possible attack'' message. This can cause denial of service attacks. Truncate the message to 80 characters to prevent this problem. When reading the IDENT response a loop is needed around the read from the network to ensure that you don't get partial lines. Password entries without any shell listed (that is, a null shell) wouldn't match as "ok". Problem noted by Rob McMahon. When running BIND 4.9.x a problem could occur because the _res.options field is initialized differently than it was historically -- this requires that sendmail call res_init before it tweaks any bits. Fix an incompatibility in openxscript() between the file open mode and the stdio mode passed to fdopen. This caused UnixWare 2.0 to have conniptions. Fix from Martin Sohnius of Novell Labs Europe. Fix problem with static linking of local getopt routine when using GNU's ld command. Fix from John Kennedy of Cal State Chico. It was possible to turn off privacy flags. Problem noted by *Hobbit*. Be more paranoid about writing files. Suggestions by *Hobbit* and Liudvikas Bukys. MAKEMAP: fixes for 64 bit machines (DEC Alphas in particular) from Spider Boardman. CONFIG: No changes (version number only, to keep it in sync with the binaries). 8.6.10/8.6.10 1995/02/10 SECURITY: Diagnose bogus values to some command line flags that could allow trash to get into headers and qf files. Validate the name of the user returned by the IDENT protocol. Some systems that really dislike IDENT send intentionally bogus information. Problem pointed out by Michael Bushnell of the Free Software Foundation. Has some security implications. Fix a problem causing error messages about DNS problems when the host name contained a percent sign to act oddly because it was passed as a printf-style format string. In some cases this could cause core dumps. Avoid possible buffer overrun in returntosender() if error message is quite long. From Fletcher Mattox of the University of Texas. Fix a problem that would silently drop "too many hops" error messages if and only if you were sending to an alias. From Jon Giltner of the University of Colorado and Dan Harton of Oak Ridge National Laboratory. Fix a bug that caused core dumps on some systems if -d11.2 was set and e->e_message was null. Fix from Bruce Nagel of Data General. Fix problem that can still cause df files to be left around after "hop count exceeded" messages. Fix from Andrew Chang and Shau-Ping Lo of SunSoft. Fix a problem that can cause buffer overflows on very long user names (as might occur if you piped to a program with a lot of arguments). Avoid returning an error and re-queueing if the host signature is null; this can occur on addresses like ``user@.''. Problem noted by Wesley Craig and the University of Michigan. Avoid possible calls to malloc(0) if MCI caching is turned off. Bug fix from Pierre David of the Laboratoire Parallelisme, Reseaux, Systemes et Modelisation (PRiSM), Universite de Versailles - St Quentin, and Jacky Thibault. Make a local copy of the line being sent via senttolist() -- in some cases, buffers could get trashed by map lookups causing it to do unexpected things. This also simplifies some of the map code. CONFIG: No changes (version number only, to keep it in sync with the binaries). 8.6.9/8.6.9 1994/04/19 Do all mail delivery completely disconnected from any terminal. This provides consistency with daemon delivery and may have some security implications. Make sure that malloc doesn't get called with zero size, since that fails on some systems. Reported by Ed Hill of the University of Iowa. Fix multi-line values for $e (SMTP greeting message). Reported by Mike O'Connor of Ford Motor Company. Avoid syserr if no NIS domain name is defined, but the map it is trying to open is optional. From Win Bent of USC. Changes for picky compilers from Ed Gould of Digital Equipment. Hesiod support for UDB from Todd Miller of the University of Colorado. Use "hesiod" as the service name in the U option. Fix a problem that failed to set the "authentic" host name (that is, the one derived from the socket info) if you called sendmail -bs from inetd. Based on code contributed by Todd Miller (this problem was also reported by Guy Helmer of Dakota State University). This also fixes a related problem reported by Liudvikas Bukys of the University of Rochester. Parameterize "nroff -h" in all the Makefiles so people with variant versions can use them easily. Suggested by Peter Collinson of Hillside Systems. SMTP "MAIL" commands with multiple ESMTP parameters required two spaces between parameters instead of one. Reported by Valdis Kletnieks of Virginia Tech. Reduce the number of system calls during message collection by using global timeouts around the collect() loop. This code was contributed by Eric Wassenaar. If the initial hostname name gathering results in a name without a dot (usually caused by NIS misconfiguration) and BIND is compiled in, directly access DNS to get the canonical name. This should make life easier for Solaris systems. If it still can't be resolved, and if the name server is listed as "required", try again in 30 seconds. If that also fails, exit immediately to avoid bogus "config error: mail loops back to myself" messages. Improve the "MAIL DELETED BECAUSE OF LACK OF DISK SPACE" error message to explain how much space was available and sound a bit less threatening. Suggested by Stan Janet of the National Institute of Standards and Technology. If mail is delivered to an alias that has an owner, deliver any requested return-receipt immediately, and strip the Return-Receipt-To: header from the subsequent message. This prevents a certain class of denial of service attack, arguably gives more reasonable semantics, and moves things more towards what will probably become a network standard. Suggested by Christopher Davis of Kapor Enterprises. Add a "noreceipts" privacy flag to turn off all return receipts without recompiling. Avoid printing ESMTP parameters as part of the error message if there are errors during parsing. This change is purely cosmetic. Avoid sending out error messages during the collect phase of SMTP; there is an MVS mailer from UCLA that gets confused by this. Of course, I think it's their bug.... Check for the $j macro getting undefined, losing a dot, or getting lost from $=w in the daemon before accepting a connection; if it is, it dumps state, prints a LOG_ALERT message, and drops core for debugging. This is an attempt to track down a bug that I thought was long since gone. If you see this, please forward the log fragment to sendmail@sendmail.ORG. Change OLD_NEWDB from a #ifdef to a #if so it can be turned off with -DOLD_NEWDB=0 on the command line. From Christophe Wolfhugel. Instead of trying to truncate the listen queue for the server SMTP port when the load average is too high, just close the port completely and reopen it later as needed. This ensures that the other end gets a quick "connection refused" response, and that the connection can be recovered later. In particular, some socket emulations seem to get confused if you tweak the listen queue size around and can never start listening to connections again. The down side is that someone could start up another daemon process in the interim, so you could have multiple daemons all not listening to connections; this could in turn cause the sendmail.pid file to be incorrect. A better approach might be to accept the connection and give a 421 code, but that could break other mailers in mysterious ways and have paging behavior implications. Fix a glitch in TCP-level debugging that caused flag 16.101 to set debugging on the wrong socket. From Eric Wassenaar. When creating a df* temporary file, be sure you truncate any existing data in the file -- otherwise system crashes and the like could result in extra data being sent. DOC: Replace the CHANGES-R5-R8 readme file with a paper in the doc directory. This includes some additional information. CONFIG: change UUCP rules to never add $U! or $k! on the front of recipient envelope addresses. This should have been handled by the $&h trick, but broke if people were mixing domainized and UUCP addresses. They should probably have converted all the way over to uucp-uudom instead of uucp-{new,old}, but the failure mode was to loop the mail, which was bad news. Portability fixes: Newer BSDI systems (several people). Older BSDI systems from Christophe Wolfhugel. Intergraph CLIX, from Paul Southworth of CICNet. UnixWare, from Evan Champion. NetBSD from Adam Glass. Solaris from Quentin Campbell of the University of Newcastle upon Tyne. IRIX from Dean Cookson and Bill Driscoll of Mitre Corporation. NCR 3000 from Kevin Darcy of Chrysler Financial Corporation. SunOS (it has setsid() and setvbuf() calls) from Jonathan Kamens of OpenVision Technologies. HP-UX from Tor Lillqvist. New Files: src/Makefile.CLIX src/Makefile.NCR3000 doc/changes/Makefile doc/changes/changes.me doc/changes/changes.ps 8.6.8/8.6.6 1994/03/21 SECURITY: it was possible to read any file as root using the E (error message) option. Reported by Richard Jones; fixed by Michael Corrigan and Christophe Wolfhugel. 8.6.7/8.6.6 1994/03/14 SECURITY: it was possible to get root access by using weird values to the -d flag. Thanks to Alain Durand of INRIA for forwarding me the notice from the bugtraq list. 8.6.6/8.6.6 1994/03/13 SECURITY: the ability to give files away on System V-based systems proved dangerous -- don't run as the owner of a :include: file on a system that allows giveaways. Unfortunately, this also applies to determining a valid shell. IMPORTANT: Previous versions weren't expiring old connections in the connection cache for a long time under some circumstances. This could result in resource exhaustion, both at your end and at the other end. This checks the connections for timeouts much more frequently. From Doug Anderson of NCSC. Fix a glitch that snuck in that caused programs to be run as the sender instead of the recipient if the mail was from a local user to another local user. From Motonori Nakamura of Kyoto University. Fix "wildcard" on /etc/shells matching -- instead of looking for "*", look for "/SENDMAIL/ANY/SHELL/". From Bryan Costales of ICSI. Change the method used to declare the "statfs" availability; instead of HASSTATFS and/or HASUSTAT with a ton of tweaking in conf.c, there is a single #define called SFS_TYPE which takes on one of six values (SFS_NONE for no statfs availability, SFS_USTAT for the ustat(2) syscall, SFS_4ARGS for a four argument statfs(2) call, and SFS_VFS, SFS_MOUNT, or SFS_STATFS for a two argument statfs(2) call with the declarations in , , or respectively). Fix glitch in NetInfo support that could return garbage if there was no "/locations/sendmail" property. From David Meyer of the University of Virginia. Change HASFLOCK from defined/not-defined to a 0/1 definition to allow Linux to turn it off even though it is a BSD-like system. Allow setting of "ident" timeout to zero to turn off the ident protocol entirely. Make 7-bit stripping local to a connection (instead of to a mailer); this allows you to specify that SMTP is a 7-bit channel, but revert to 8-bit should it advertise that it supports 8BITMIME. You still have to specify mailer flag 7 to get this stripping at all. Improve makesendmail script so it handles more cases automatically. Tighten up restrictions on taking ownership of :include: files to avoid problems on systems that allow you to give away files. Fix a problem that made it impossible to rebuild the alias file if it was on a read-only file system. From Harry Edmon of the University of Washington. Improve MX randomization function. From John Gardiner Myers of CMU. Fix a minor glitch causing a bogus message to be printed (used %s instead of %d in a printf string for the line number) when a bad queue file was read. From Harry Edmon. Allow $s to remain NULL on locally generated mail. I'm not sure this is necessary, but a lot of people have complained about it, and there is a legitimate question as to whether "localhost" is legal as an 822-style domain. Fix a problem with very short line lengths (mailer L= flag) in headers. This causes a leading space to be added onto continuation lines (including in the body!), and also tries to wrap headers containing addresses (From:, To:, etc) intelligently at the shorter line lengths. Problem Reported by Lars-Johan Liman of SUNET Operations Center. Log the real user name when logging syserrs, since these can have security implications. Suggested by several people. Fix address logging of cached connections -- it used to always log the numeric address as zero. This is a somewhat bogus implementation in that it does an extra system call, but it should be an inexpensive one. Fix from Motonori Nakamura. Tighten up handling of short syslog buffers even more -- there were cases where the outgoing relay= name was too long to share a line with delay= and mailer= logging. Limit the overhead on split envelopes to one open file descriptor per envelope -- previously the overhead was three descriptors. This was in response to a problem reported by P{r (Pell) Emanuelsson. Fixes to better handle the case of unexpected connection closes; this redirects the output to the transcript so the info is not lost. From Eric Wassenaar. Fix potential string overrun if you macro evaluate a string that has a naked $ at the end. Problem noted by James Matheson . Make default error number on $#error messages 553 (``Requested action not taken: mailbox name not allowed'') instead of 501 (``Syntax error in parameters or arguments'') to avoid bogus "protocol error" messages. Strip off any existing trailing dot on names during $[ ... $] lookup. This prevents it from ending up with two dots on the end of dot terminated names. From Wesley Craig of the University of Michigan and Bryan Costales of ICSI. Clean up file class reading so that the debugging information is more informative. It hadn't been using setclass, so you didn't see the class items being added. Avoid core dump if you are running a version of sendmail where NIS is compiled in, and you specify an NIS map, but NIS is not running. Fix from John Oleynick of Rutgers. Diagnose bizarre case where res_search returns a failure value, but sets h_errno to a success value. Make sure that "too many hops" messages are considered important enough to send an error to the Postmaster (that is, the address specified in the P option). This fix should help problems that cause the df file to be left around sometimes -- unfortunately, I can't seem to reproduce the problem myself. Avoid core dump (null pointer reference) on EXPN command; this only occurred if your log level was set to 10 or higher and the target account was an alias or had a .forward file. Problem noted by Janne Himanka. Avoid "denial of service" attacks by someone who is flooding your SMTP port with bad commands by shutting the connection after 25 bad commands are issued. From Kyle Jones of UUNET. Fix core dump on error messages with very long "to" buffers; fmtmsg overflows the message buffer. Fixed by trimming the to address to 203 characters. Problem reported by John Oleynick. Fix configuration for HASFLOCK -- there were some spots where a #ifndef was incorrectly #ifdef. Pointed out by George Baltz of the University of Maryland. Fix a typo in savemail() that could cause the error message To: lists to be incorrect in some places. From Motonori Nakamura. Fix a glitch that can cause duplicate error messages on split envelopes where an address on one of the lists has a name server failure. Fix from Voradesh Yenbut of the University of Washington. Fix possible bogus pointer reference on ESMTP parameters that don't have an ``=value'' part. CNAME loops caused an error message to be generated, but also re-queued the message. Changed to just re-queue the message (it's really hard to just bounce it because of the weird way the name server works in the presence of CNAME loops). Problem noted by James M.R.Matheson of Cambridge University. Avoid giving ``warning: foo owned process doing -bs'' messages if they use ``MAIL FROM:'' where foo is their true user name. Suggested by Andreas Stolcke of ICSI. Change the NAMED_BIND compile flag to be a 0/1 flag so you can override it easily in the Makefile -- that is, you can turn it off using -DNAMED_BIND=0. If a gethostbyname(...) of an address with a trailing dot fails, try it without the trailing dot. This is because if you have a version of gethostbyname() that falls back to NIS or the /etc/hosts file it will fail to find perfectly reasonable names that just don't happen to be dot terminated in the hosts file. You don't want to strip the dot first though because we're trying to ensure that country names that match one of your subdomains get a chance. PRALIASES: fix bogus output on non-null-terminated strings. From Bill Gianopoulos of Raytheon. CONFIG: Avoid rewriting anything that matches $w to be $j. This was in code intended to only catch the self-literal address (that is, [1.2.3.4], where 1.2.3.4 is your IP address), but the code was broken. However, it will still do this if $M is defined; this is necessary to get client configurations to work (sigh). Note that this means that $M overrides :mailname entries in the user database! Problem noted by Paul Southworth. CONFIG: Fix definition of Solaris help file location. From Steve Cliffe . CONFIG: Fix bug that broke news.group.USENET mappings. CONFIG: Allow declaration of SMTP_MAILER_MAX, FAX_MAILER_MAX, and USENET_MAILER_MAX to tweak the maximum message size for various mailers. CONFIG: Change definition of USENET_MAILER_ARGS to include argv[0] instead of assuming that it is "inews" for consistency with other mailers. From Michael Corrigan of UC San Diego. CONFIG: When mail is forwarded to a LOCAL_RELAY or a MAIL_HUB, qualify the address in the SMTP envelope as user@{relay|hub} instead of user@$j. From Bill Wisner of The Well. CONFIG: Fix route-addr syntax in nullrelay configuration set. CONFIG: Don't turn off case mapping of user names in the local mailer for IRIX. This was different than most every other system. CONFIG: Avoid infinite loops on certainly list:; syntaxes in envelope. Noted by Thierry Besancon . CONFIG: Don't include -z by default on uux line -- most systems don't want it set by default. Pointed out by Philippe Michel of Thomson CSF. CONFIG: Fix some bugs with mailertables -- for example, if your host name was foo.bar.ray.com and you matched against ".ray.com", the old implementation bound %1 to "bar" instead of "foo.bar". Also, allow "." in the mailertable to match anything -- essentially, take over SMART_HOST. This also moves matching of explicit local host names before the mailertable so they don't have to be special cased in the mailertable data. Reported by Bill Gianopoulos of Raytheon; the fix for the %1 binding problem was contributed by Nicholas Comanos of the University of Sydney. CONFIG: Don't include "root" in class $=L (users to deliver locally, even if a hub or relay exists) by default. This is because of the known bug where definition of both a LOCAL_RELAY and a MAIL_HUB causes $=L to ignore both and deliver into the local mailbox. CONFIG: Move up bitdomain and uudomain handling so that they are done before .UUCP class matching; uudomain was reported as ineffective before. This also frees up diversion 8 for future use. Problem reported by Kimmo Suominen. CONFIG: Don't try to convert dotted IP address (e.g., [1.2.3.4]) into host names. As pointed out by Jonathan Kamens, these are often used because either the forward or reverse mapping is broken; this translation makes it broken again. DOC: Clarify $@ and $: in the Install & Op Guide. From Kimmo Suominen. Portability fixes: Unicos from David L. Kensiski of Sterling Software. DomainOS from Don Lewis of Silicon Systems. GNU m4 1.0.3 from Karst Koymans of Utrecht University. Convex from Kimmo Suominen . NetBSD from Adam Glass . BSD/386 from Tony Sanders of BSDI. Apollo from Eric Wassenaar. DGUX from Doug Anderson. Sequent DYNIX/ptx 2.0 from Tim Wright of Sequent. NEW FILES: src/Makefile.DomainOS src/Makefile.PTX src/Makefile.SunOS.5.1 src/Makefile.SunOS.5.2 src/Makefile.SunOS.5.x src/mailq.1 cf/ostype/domainos.m4 doc/op/Makefile doc/intro/Makefile doc/usenix/Makefile 8.6.5/8.6.5 1994/01/13 Security fix: /.forward could be owned by anyone (the test to allow root to own any file was backwards). From Bob Campbell at U.C. Berkeley. Security fix: group ids were not completely set when programs were invoked. This caused programs to have group permissions they should not have had (usually group daemon instead of their own group). In particular, Perl scripts would refuse to run. Security: check to make sure files that are written are not symbolic links (at least under some circumstances). Although this does not respond to a specific known attack, it's just a good idea. Suggested by Christian Wettergren. Security fix: if a user had an NFS mounted home directory on a system with a restricted shell listed in their /etc/passwd entry, they could still execute any program by putting that in their .forward file. This fix prevents that by insisting that their shell appear in /etc/shells before allowing a .forward to execute a program or write a file. You can disable this by putting "*" in /etc/shells. It also won't permit world-writable :include: files to reference programs or files (there's no way to disable this). These behaviors are only one level deep -- for example, it is legal for a world-writable :include: file to reference an alias that writes a file, on the assumption that the alias file is well controlled. Security fix: root was not treated suspiciously enough when looking into subdirectories. This would potentially allow a cracker to examine files that were publicly readable but in a non-publicly searchable directory. Fix a problem that causes an error on QUIT on a cached connection to create problems on the current job. These are typically unrelated, so errors occur in the wrong place. Reset CurrentLA in sendall() -- this makes sendmail queue runs more responsive to load average, and fixes a problem that ignored the load average in locally generated mail. From Eric Wassenaar. Fix possible core dump on aliases with null LHS. From John Orthoefer of BB&N. Revert to using flock() whenever possible -- there are just too many bugs in fcntl() locking, particularly over NFS, that cause sendmail to fail in perverse ways. Fix a bug that causes the connection cache to get confused when sending error messages. This resulted in "unexpected close" messages. It should fix itself on the following queue run. Problem noted by Liudvikas Bukys of the University of Rochester. Include $k in $=k as documented in the Install & Op Guide. This seems odd, but it was documented.... From Michael Corrigan of UCSD. Fix problem that caused :include:s from alias files to be forced to be owned by root instead of daemon (actually DefUid). From Tim Irvin. Diagnose unrecognized I option values -- from Mortin Forssen of the Chalmers University of Technology. Make "error" mailer work consistently when there is no error code associated with it -- previously it returned OK even though there was a real problem. Now it assumes EX_UNAVAILABLE. Fix bug that caused the last header line of messages that had no body and which were terminated with EOF instead of "." to be discarded. Problem noted by Liudvikas Bukys. Fix core dump on SMTP mail to programs that failed -- it tried to go to a "next MX host" when none existed, causing a core dump. From der Mouse at McGill University. Change IDENTPROTO from a defined/not defined to a 0/1 switch; this makes it easier to turn it off (using -DIDENTPROTO=0 in the Makefile). From der Mouse. Fix YP_MASTER_NAME store to use the unupdated result of gethostname() (instead of myhostname(), which tries to fully qualify the name) to be consistent with SunOS. If your hostname is unqualified, this fixes transfers to slave servers. Bug noted by Keith McMillan of Ameritech Services, Inc. Fix Ultrix problem: gethostbyname() can return a very large (> 500) h_length field, which causes the sockaddr to be trashed. Use the size of the sockaddr instead. Fix from Bob Manson of Ohio State. Don't assume "-a." on host lookups if NAMED_BIND is not defined -- this confuses gethostbyname on hosts file lookups, which doesn't understand the trailing dot convention. Log SMTP server subprocesses that die with a signal instead of from a clean exit. If you don't have option "I" set, don't assume that a DNS "host unknown" message is authoritative -- it might still be found in /etc/hosts. Fix a problem that would cause Deferred: messages to be sent as the subject of an error message, even though the actual cause of a message was more severe than that. Problem noted by Chris Seabrook of OSSI. Fix race condition in DBM alias file locking. From Kyle Jones of UUNET. Limit delivery syslog line length to avoid bugs in some versions of syslog(3). This adds a new compile time variable SYSLOG_BUFSIZE. From Jay Plett of Princeton University, which is in turn derived from IDA. Fix quotes inside of comments in addresses -- previously it insisted that they be balanced, but the 822 spec says that they should be ignored. Dump open file state to syslog upon receiving SIGUSR1 (for debugging). This also evaluates ruleset 89, if set (with the null input), and logs the result. This should be used sparingly, since the rewrite process is not reentrant. Change -qI, -qR, and -qS flags to be case-insensitive as documented in the Bat Book. If the mailer returned EX_IOERR or EX_OSERR, sendmail did not return an error message and did not requeue the message. Fix based on code from Roland Dirlewanger of Reseau Regional Aquarel, Bordeaux, France. Fix a problem that caused a seg fault if you got a 421 error code during some parts of connection initialization. I've only seen this when talking to buggy mailers on the other end, but it shouldn't give a seg fault in any case. From Amir Plivatsky. Fix core dump caused by a ruleset call that returns null. Fix from Bryan Costales of ICSI. Full-Name: field was being ignored. Fix from Motonori Nakamura of Kyoto University. Fix a possible problem with very long input lines in setproctitle. From P{r Emanuelsson. Avoid putting "This is a warning message" out on return receipts. Suggested by Douglas Anderson. Detect loops caused by recursive ruleset calls. Suggested by Bryan Costales. Initialize non-alias maps during alias rebuilds -- they may be needed for parsing. Problem noted by Douglas Anderson. Log sender address even if no message was collected in SMTP (e.g., if all RCPTs failed). Suggested by Motonori Nakamura. Don't reflect the owner-list contents into the envelope sender address if the value contains ", :, /, or | (to avoid illegal addresses appearing there). Efficiency hack for toktype macro -- from Craig Partridge of BB&N. Clean up DNS error printing so that a host name is always included. Remember to set $i during queue runs. Reported by Stephen Campbell of Dartmouth University. If the environment variable HOSTALIASES is set, use it during canonification as the name of a file with per-user host translations so that headers are properly mapped. Reported by Anne Bennett of Concordia University. Avoid printing misleading error message if SMTP mailer (not using [IPC]) should die on a core dump. Avoid incorrect diagnosis of "file 1 closed" when it is caused by the other end closing the connection. From Dave Morrison of Oracle. Improve several of the error messages printed by "mailq" to include a host name or other useful information. Add NetInfo preliminary support for NeXT systems. From Vince DeMarco. Fix a glitch that sometimes caused :include:s that pointed to NFS filesystems that were down to give an "aliasing/ forwarding loop broken" message instead of queueing the message for retry. Noted by William C Fenner of the NRL Connection Machine Facility. Fix a problem that could cause a core dump if the input sequence had (or somehow acquired) a \231 character. Make sure that route-addrs always have around them in non-SMTP envelopes (SMTP envelopes already do this properly). Avoid weird headers on unbalanced punctuation of the form: ``Joe User ; this has uucp-dom semantics but old UUCP syntax. This also permits "uucp-old" as an alias for "uucp" and "uucp-new" as a synonym for "suucp" for consistency. CONFIG: add POP mailer support (from Kimmo Suominen ). CONFIG: drop CSNET_RELAY support -- CSNET is long gone. CONFIG: fix bug caused with domain literal addresses (e.g., ``[128.32.131.12]'') when FEATURE(allmasquerade) was set; it would get an additional @masquerade.host added to the address. Problem noted by Peter Wan of Georgia Tech. CONFIG: make sure that the local UUCP name is in $=w. From Jim Murray of Stratus. CONFIG: changes to UUCP rewriting to simulate IDA-style "V" mailer flag. Briefly, if you are sending to host "foo", then it rewrites "foo!...!baz" to "...!baz", "foo!baz" remains "foo!baz", and anything else has the local name prepended. CONFIG: portability fixes for HP-UX. DOC: several minor problems fixed in the Install & Op Guide. MAKEMAP: fix core dump problem on lines that are too long or which lack newline. From Mark Delany. MAILSTATS: print sums of columns (total messages & kbytes in and out of the system). From Tom Ferrin of UC San Francisco Computer Graphics Lab. SIGNIFICANT USER- OR SYSAD-VISIBLE CHANGES: On HP-UX, /etc/sendmail.cf has been moved to /usr/lib/sendmail.cf to match HP sendmail. Permissions have been tightened up on world-writable :include: files and accounts that have shells that are not listed in /etc/shells. This may cause some .forward files that have worked before to start failing. SIGUSR1 dumps some state to the log. NEW FILES: src/Makefile.DGUX src/Makefile.Dynix src/Makefile.FreeBSD src/Makefile.Mach386 src/Makefile.NetBSD src/Makefile.RISCos src/Makefile.SCO src/Makefile.SVR4 src/Makefile.Titan cf/mailer/pop.m4 cf/ostype/bsdi1.0.m4 cf/ostype/dgux.m4 cf/ostype/dynix3.2.m4 cf/ostype/sco3.2.m4 makemap/Makefile.dist praliases/Makefile.dist 8.6.4/8.6.4 1993/10/31 Repair core-dump problem (write to read-only memory segment) if you fall back to the return-to-Postmaster case in savemail. Problem reported by Richard Liu. Immediately diagnose bogus sender addresses in SMTP. This makes quite certain that crackers can't use this class of attack. Reliability Fix: check return value from fclose() and fsync() in a few critical places. Minor problem in initsys() that reversed a condition for redirecting the output channel on queue runs. It's not clear this code even does anything. From Eric Wassenaar of the Dutch National Institute for Nuclear and High-Energy Physics. Fix some problems that caused queue runs to do "too much work", such as double-reading the Errors-To: header. From Eric Wassenaar. Error messages on writing the temporary file (including the data file) were getting suppressed in SMTP -- this fix causes them to be properly reported. From Eric Wassenaar. Some changes to support AF_UNIX sockets -- this will only really become relevant in the next release, but some people need it for local patches. From Michael Corrigan of UC San Diego. Use dynamically allocated memory (instead of static buffers) for macros defined in initsys() and settime(); since these can have different values depending on which envelope they are in. From Eric Wassenaar. Improve logging to show ctladdr on to= logging; this tells you what uid/gid processes ran as. Fix a problem that caused error messages to be discarded if the sender address was unparseable for some reason; this was supposed to fall back to the "return to postmaster" case. Improve aliaswait backoff algorithm. Portability patches for Linux (8.6.3 required another header file) (from Karl London) and SCO UNIX. CONFIG: patch prog mailer to not strip host name off of envelope addresses (so that it matches local again). From Christopher Davis. CONFIG: change uucp-dom mailer so that "<>" translates to $n; this prevents uux from seeing lines with null names like ``From Sat Oct 30 14:55:31 1993''. From Motonori Nakamura of Kyoto University. CONFIG: handle syntax correctly. This isn't legal, but it shouldn't fail miserably. From Motonori Nakamura. 8.6.2/8.6.2 1993/10/15 Put a "successful delivery" message in the transcript for addresses that get return-receipts. Put a prominent "this is only a warning" message in warning messages -- some people don't read carefully enough and end up sending the message several times. Include reason for temporary failure in the "warning" return message. Currently, it just says "cannot send for four hours". Fix the "Original message received" time generated for returntosender messages. It was previously listed as the current time. Bug reported by Eric Hagberg of Cornell University Medical College. If there is an error when writing the body of a message, don't send the trailing dot and wait for a response in sender SMTP, as this could cause the connection to hang up under some bizarre circumstances. From Eric Wassenaar. Fix some server SMTP synchronization problems caused when connections fail during message collection. From Eric Wassenaar. Fix a problem that can cause srvrsmtp to reject mail if the name server is down -- it accepts the RCPT but rejects the DATA command. Problem reported by Jim Murray of Stratus. Fix a problem that can cause core dumps if the config file incorrectly resolves to a null hostname. Reported by Allan Johannesen of WPI. Non-root use of -C flag, dangerous -f flags, and use of -oQ by non-root users were not put into X-Authentication-Warning:s as intended because the config file hadn't set the PrivacyOptions yet. Fix from Sven-Ove Westberg of the University of Lulea. Under very odd circumstances, the alias file rebuild code could get confused as to whether a database was open or not. Check "vendor code" on the end of V lines -- this is intended to provide a hook for vendor-specific configuration syntax. (This is a "new feature", but I've made an exception to my rule in a belief that this is a highly exceptional case.) Portability fixes for DG/UX (from Douglas Anderson of NCSC), SCO Unix (from Murray Kucherawy), A/UX, and OSF/1 (from Jon Forrest of UC Berkeley) CONFIG: fix ``mailer:host'' form of UUCP relay naming. 8.6.1/8.6 1993/10/08 Portability fixes for A/UX and Encore UMAX V. Fix error message handling -- if you had a name server down causing an error during parsing, that message was never propagated to the queue file. 8.6/8.6 1993/10/05 Configuration cleanup: make it easier to undo IDENTPROTO in conf.h (other systems have the same bug). If HASGETDTABLESIZE and _SC_OPEN_MAX are both defined, assume getdtablesize() instead of sysconf(); a disturbingly large number of systems defined _SC_OPEN_MAX in the header files but don't have the syscall. Another patch to really truly ignore MX records in getcanonname if trymx == FALSE. Fix problem that caused the "250 IAA25499 Message accepted for delivery" message to be omitted if there was an error in the header of the message (e.g., a bad Errors-To: line). Pointed out by Michael Corrigan of UCSD. Announce name of host we are chatting when we get errors; this is an IDA-ism suggested by Christophe Wolfhugel. Portability fixes for Alpha OSF/1 (from Anthony Baxter of the Australian Artificial Intelligence Institute), SCO Unix (from Murray Kucherawy of Hookup Communication Corp.), NeXT (from Vince DeMarco and myself), Linux (from Karl London ), BSDI (from Christophe Wolfhugel, and SVR4 on Dell (from Kimmo Suominen), AUX 3.0 on Macintosh, and ANSI C compilers. Some changes to get around gcc optimizer bugs. From Takahiro Kanbe. Fix error recovery in queueup if another tf file of the same name already exists. Problem stumbled over by Bill Wisner of The Well. Output YP_MASTER_NAME and YP_LAST_MODIFIED without null bytes. Problem noted by Keith McMillan of Ameritech Services. Deal with group permissions properly when opening .forward and :include: files. This relaxes the 8.1C restrictions slightly more. This includes proper setting of groups when reading :include: files, allowing you to read some files that you should be able to read but have previously been denied unless you owned them or they had "other" read permission. Make certain that $j is in $=w (after the .cf is read) so that if the user is forced to override some silly system, MX suppression will still work. Fix a couple of efficiency problems where newstr was double- calling expensive routines. In at least one case, it wasn't guaranteed that they would always return the same result. Problem noted by Christophe Wolfhugel. Fix null pointer dereference in putoutmsg -- only on an error condition from a non-SMTP mailer. From Motonori Nakamura. Macro expand "C" line class definitions before scanning so that "CX $Z" works. Fix problem that caused error message to be sent while still trying to send the original message if the connection is closed during a DATA command after getting an error on an RCPT command (pretty obscure). Problem reported by John Myers of CMU. Fix reply to NOOP to be 250 instead of 200 -- this is a long term bug. Fix a nasty bug causing core dumps when returning the "warning: cannot deliver for N hours -- will keep trying" message; it only occurred if you had PostmasterCopy set and only on some architectures. Although sendmail would keep trying, it would send error messages on each queue interval. This is an important fix. Allow u and g options to take user and group names respectively. Don't do a chdir into the queue directory in -bt mode to make ruleset testing a bit easier. Don't allow users to turn off logging (using -oL) on the command line -- command line can only raise, not lower, logging level. Set $u to the original recipient on the SMTP transaction or on the command line. This is only done if there is exactly one recipient. Technically, this does not meet the specs, because it does not guarantee a domain on the address. Fix a problem that dumped error messages on bad addresses if you used the -t flag. Problem noted by Josh Smith of Harvey Mudd College. Given an address such as `` '', auto-quote the first ``'' part, giving ``"" ''. This is to avoid the problem of people who use angle brackets in their full name information. Fix a null pointer dereference if you set option "l", have an Errors-To: header in the message, and have Errors-To: defined in the config file H lines. From J.R. Oldroyd. Put YPCOMPAT on #ifdef NIS instead -- it's one less thing to get wrong when compiling. Suggested by Rick McCarty of TI. Fix a problem that could pass negative SIZE parameter if the df file got lost; this would cause servers to always give a temporary failure, making the problem even worse. Problem noted by Allan Johannesen of WPI. Add "ident" timeout (one of the "r" option selectors) for IDENT protocol timeouts (30s default). Requested by Murray Kucherawy of HookUp Communication Corp. to handle bogus PC TCP/IP implementations. Change $w default definition to be just the first component of the domain name on config level 5. The $j macro defaults to the FQDN; $m remains as before. This lets well-behaved config files use any of the short, long, or subdomain names. Add makesendmail script in src to try to automate multi-architecture builds. I know, this is sub-optimal, but it is still helpful. Fix very obscure race condition that can cause a queue run to get a queue file for an already completed job. This problem has existed for years. Problem noted by the long suffering Allan Johannesen of WPI. Fix a problem that caused the raw sender name to be passed to udbsender instead of the canonified name -- this caused it to sometimes miss records that it should have found. Relax check of name on HELO packet so that a program using -bs that claims to be itself works properly. Restore rewriting of $: part of address through 2, R, 4 in buildaddr -- this requires passing a lot of flags to get it right. Unlike old versions, this ONLY rewrites recipient addresses, not sender addresses. Fix a bug that caused core dumps in config files that cannot resolve /file/name style addresses. Fix from Jonathan Kamens of OpenVision Technologies. Fix problem with fcntl locking that can cause error returns to be lost if the lock is lost; this required fully queueing everything, dropping the envelope (so errors would get returned), and then re-reading the queue from scratch. Fix a problem that caused aliases that redefine an otherwise true address to still send to the original address if and only if the alias failed in certain bizarre ways (e.g, if they pointed at a list:; syntax address). Problem pointed out by Jonathan Kamens. Remove support for frozen configuration files. They caused more trouble than it was worth. Fix problem that can cause error messages to get ignored when using both -odb and -t flags. Problem noted by Rob McNicholas at U.C. Berkeley. Include all "normal" variations on hostname in $=w. For example, if the host name is vangogh.cs.berkeley.edu, $=w will contain vangogh, vangogh.cs, and vangogh.cs.berkeley.edu. Add "restrictqrun" privacy flag -- without this, anyone can run the queue. Reset SmtpPhase global on initial connection creation so that messages don't come out with stale information. Pass an "ext" argument to lockfile so that error/log messages will properly reflect the true filename being locked. Put all [...] address forms into $=w -- this eliminates the need for MAXIPADDR in conf.h. Suggested by John Gardiner Myers of CMU. Fix a bug that can cause qf files to be left around even after an SMTP RSET command. Problem and fix from Michael Corrigan. Don't send a PostmasterCopy to errors when the Precedence: is negative. Error reports still go to the envelope sender address. Add LA_SHORT for load averages. Lock sendmail.st file when posting statistics. Add "SendBufSize" and "RcvBufSize" suboptions to "O" option to set the size of the TCP send and receive buffers; if you run over a slow slip line you may need to set these down (although it would be better to fix the SLIP implementation so that it's not necessary to recompile every program that does bulk data transfer). Allow null defaults on $( ... $) lookups. Problem reported by Amir Plivatsky. Diagnose crufty S and V config lines. This resulted from an observation that some people were using the SITE macro without the SITECONFIG macro first, which was causing bogus config files that were not caught. Fix makemap -f flag to turn off case folding (it was turning it on instead). THIS IS A USER VISIBLE CHANGE!!! Fix a problem that caused multiple error messages to be sent if you used "sendmail -t -oem -odb", your system uses fcntl locking, and one of the recipient addresses is unknown. Reset uid earlier in include() so that recursive .forwards or :include:s don't use the wrong uid. If file descriptor 0, 1, or 2 was closed when sendmail was called, the code to recover the descriptor was broken. This sometimes (only sometimes) caused problems with the alias file. Fix from Motonori Nakamura. Fix a problem that caused aliaswait to go into infinite recursion if the @:@ metasymbol wasn't found in the alias file. Improve error message on newaliases if database files cannot be opened or if running with no database format defined. Do a better estimation of the size of error messages when NoReturn is set. Problem noted by P{r (Pell) Emanuelsson. Fix a problem causing the "c" option (don't connect to expensive mailers) to be ignored in SMTP. Problem noted and the solution suggested by Robert Elz of The University of Melbourne. Improve connection caching algorithm by passing "[host]" to hostsignature, which strips the square brackets and returns the real name. This allows mailertable entries to match regular entries. Re-enable Return-Receipt-To: -- people seem to want this stupid feature, even if it doesn't work right. Catch and log attempts to try the "wiz" command in server SMTP. This also ups the log level from LOG_NOTICE to LOG_CRIT. Be more generous at assigning $z to the home directory -- do this for programs that are specified through a .forward file. Fix from Andrew Chang of Sun Microsystems. Always save a fatal error message in preference to a non-fatal error message so that the "subject" line of return messages is the best possible. CONFIG: reduce the number of quotes needed to quote configuration parameters with commas: two quotes should work now, e.g., define(ALIAS_FILE, ``/etc/aliases,/etc/aliases.local''). CONFIG: class $=Z is a set of UUCP hosts that use uucp-dom connections (domain-ized UUCP). CONFIG: fix bug in default maps (-o must be before database file name). Pointed out by Christophe Wolfhugel. CONFIG: add FEATURE(nodns) to state that we are not relying on DNS. This would presumably be used in UUCP islands. CONFIG: add OSTYPE(nextstep) and OSTYPE(linux). CONFIG: log $u in Received: line. This is in technical violation of the standards, since it doesn't guarantee a domain on the address. CONFIG: don't assume "m" in local mailer flags -- this means that if you redefine LOCAL_MAILER_FLAGS you will have to include the "m" flag should you want it. Apparently some Solaris 2.2 installations can't handle multiple local recipients. Problem noted by Josh Smith. CONFIG: add confDOMAIN_NAME to set $j (if undefined, $j defaults). CONFIG: change default version level from 4 to 5. CONFIG: add FEATURE(nullclient) to create a config file that forwards all mail to a hub without ever looking at the addresses in any detail. CONFIG: properly strip mailer: information off of relays when used to change .BITNET form into %-hack form. CONFIG: fix a problem that caused infinite loops if presented with an address such as "!foo". CONFIG: check for self literal (e.g., [128.32.131.12]) even if the reverse "PTR" mapping is broken. There's a better way to do this, but the change is fairly major and I want to hold it for another release. Problem noted by Bret Marquis. 8.5/8.5 1993/07/23 Serious bug: if you used a command line recipient that was unknown sendmail would not send a return message (it was treating everything as though it had an SMTP-style client that would do the return itself). Problem noted by Josh Smith. Change "trymx" option in getcanonname() to ignore all MX data, even during a T_ANY query. This actually didn't break anything, because the only time you called getcanonname with !trymx was if you already knew there were no MX records, but it is somewhat cleaner. From Motonori Nakamura. Don't call getcanonname from getmxrr if you already know there are no DNS records matching the name. Fix a problem causing error messages to always include "The original message was received ... from localhost". The correct original host information is now included. Previous change to cf/sh/makeinfo.sh doesn't port to Ultrix (their version of "test" doesn't have the -x flag). Change it to use -f instead. From John Myers. CONFIG: 8.4 mistakenly set the default SMTP-style mailer to esmtp -- it should be smtp. CONFIG: send all relayed mail using confRELAY_MAILER (defaults to "relay" (a variant of "smtp") if MAILER(smtp) is used, else "suucp" if MAILER(uucp) is used, else "unknown"); this cleans up the configs somewhat. This fixes a serious problem that caused route-addrs to get mistaken as relays, pointed out by John Myers. WARNING: this also causes the default on SMART_HOST to change from "suucp" to "relay" if you have MAILER(smtp) specified. 8.4/8.4 1993/07/22 Add option `w'. If you receive a message that comes to you because you are the best (lowest preference) target of an MX, and you haven't explicitly recognized the source MX host in your .cf file, this option will cause you to try the target host directly (as if there were no MX for it at all). If `w' is not set, this case is a configuration error. Beware: if `w' is set, senders may get bogus errors like "message timed out" or "host unknown" for problems that are really configuration errors. This option is disrecommended, provided only for compatibility with UIUC sendmail. Fix a problem that caused the incoming socket to be left open when sendmail forks after the DATA command. This caused calling systems to wait in FIN_WAIT_2 state until the entire list was processed and the child closed -- a potentially prodigious amount of time. Problem noted by Neil Rickert. Fix problem (created in 6.64) that caused mail sent to multiple addresses, one of which was a bad address, to completely suppress the sending of the message. This changes handling of EF_FATALERRS somewhat, and adds an EF_GLOBALERRS flag. This also fixes a potential problem with duplicate error messages if there is a syntax error in the header of a message that isn't noticed until late in processing. Original problem pointed out by Josh Smith of Harvey Mudd College. This release includes quite a bit of dickering with error handling (see below). Back out SMTP transaction if MAIL gets nested 501 error. This will only hurt already-broken software and should help humans. Fix a problem that broke aliases when neither NDBM nor NEWDB were compiled in. It would never read the alias file. Repair unbalanced `)' and `>' (the "open" versions are already repaired). Logging of "done" in dropenvelope() was incorrect: it would log this even when the queue file still existed. Change this to only log "done" (at log level 11) when the queue file is actually removed. From John Myers. Log "lost connection" in server SMTP at log level 20 if there is no pending transaction. Some senders just close the connection rather than sending QUIT. Fix a bug causing getmxrr to add a dot to the end of unqualified domains that do not have MX records -- this would cause the subsequent host name lookup to fail. The problem only occurred if you had FEATURE(nocanonify) set. Problem noted by Rick McCarty of Texas Instruments. Fix invocation of setvbuf when passed a -X flag -- I had unwittingly used an ANSI C extension, and this caused core dumps on some machines. Diagnose self-destructive alias loops on RCPT as well as EXPN. Previously it just gave an empty send queue, which then gave either "Need RCPT (recipient)" at the DATA (confusing, since you had given an RCPT command which returned 250) or just dropped the email, depending on whether you were running VERBose mode. Now it usually diagnoses this case as "aliasing/forwarding loop broken". Unfortunately, it still doesn't adequately diagnose some true error conditions. Add internal concept of "warning messages" using 6xx codes. These are not reported only to Postmaster. Unbalanced parens, brackets, and quotes are printed as 653 codes. They are always mapped to 5xx codes before use in SMTP. Clean up error messages to tell both the actual address that failed and the alias they arose from. This makes it somewhat easier to diagnose problems. Difficulty noted by Motonori Nakamura. Fix a problem that inappropriately added a ctladdr to addresses that shouldn't have had one during a queue run. This caused error messages to be handled differently during a queue run than a direct run. Don't print the qf name and line number if you get errors during the direct run of the queue from srvrsmtp -- this was just extra stuff for users to crawl through. Put command line flags on second line of pid file so you can auto-restart the daemon with all appropriate arguments. Use "kill `head -1 /etc/sendmail.pid`" to stop the daemon, and "eval `tail -1 /etc/sendmail.pid`" to restart it. Remove the ``setuid(getuid())'' in main -- this caused the IDENT daemon to screw up. This required that I change HASSETEUID to HASSETREUID and complicate the mode changing somewhat because both Ultrix and SunOS seem to have a bug causing seteuid() to set the saved uid as well as the effective. The program test/t_setreuid.c will test to see if your implementation of setreuid(2) is appropriately functional. The FallBackMX (option V) handling failed to properly identify fallback to yourself -- most of the code was there, but it wasn't being enabled. Problem noted by Murray Kucherawy of the University of Waterloo. Change :include: open timeout from ETIMEDOUT to an internal code EOPENTIMEOUT; this avoids adding "during SmtpPhase with CurHostName" in error messages, which can be confusing. Reported by Jonathan Kamens of OpenVision Technologies. Back out setpgrp (setpgid on POSIX systems) call to reset the process group id. The original fix was to get around some problems with recalcitrant MUAs, but it breaks any call from a shell that creates a process group id different from the process id. I could try to fix this by diddling the tty owner (using tcsetpgrp or equivalent) but this is too likely to break other things. Portability changes: Support -M as equivalent to -oM on Ultrix -- apparently DECnet calls sendmail with -MrDECnet -Ms -bs instead of using standard flags. Oh joy. This behavior reported by Jon Giltner of University of Colorado. SGI IRIX -- this includes several changes that should help other strict ANSI compilers. SCO Unix -- from Murray Kucherawy of HookUp Communication Corporation. Solaris running the Sun C compiler (which despite the documentation apparently doesn't define __STDC__ by default). ConvexOS from Eric Schnoebelen of Convex. Sony NEWS workstations and Omron LUNA workstations from Motonori Nakamura. CONFIG: add confTRY_NULL_MX_LIST to set option `w'. CONFIG: delete `C' and `e' from default SMTP mailers flags; several people have made a good argument that this creates more problems than it solves (although this may prove painful in the short run). CONFIG: generalize all the relays to accept a "mailer:host" format. CONFIG: move local processing in ruleset 0 into a new ruleset 98 (8 on old sendmail). Domain literal [a.b.c.d] addresses are also passed through this ruleset. CONFIG: if neither SMART_HOST nor MAILER(smtp) were defined, internet-style addresses would "fall off the end" of ruleset zero and be interpreted as local -- however, the angle brackets confused the recursive call. These are now diagnosed as "Unrecognized host name". CONFIG: USENET rules weren't included in S0 because of a mistaken ifdef(`_MAILER_USENET_') instead of ifdef(`_MAILER_usenet_'). Problem found by Rein Tollevik of SINTEF RUNIT, Oslo. CONFIG: move up LOCAL_RULE_0 processing so that it happens very early in ruleset 0; this allows .mc authors to bypass things like the "short circuit" code for local addresses. Prompted by a comment by Bill Wisner of The Well. CONFIG: add confSMTP_MAILER to define the mailer used (smtp or esmtp) to send SMTP mail. This allows you to default to esmtp but use a mailertable or other override to deal with broken servers. This logic was pointed out to me by Bill Wisner. Ditto for confLOCAL_MAILER. Changes to cf/sh/makeinfo.sh to make it portable to SVR4 environments. Ugly as sin. 8.3/8.3 1993/07/13 Fix setuid problems introduced in 8.2 that caused messages like "Cannot create qfXXXXXX: Invalid argument" or "Cannot reopen dfXXXXXX: Permission denied". This involved a new compile flag "HASSETEUID" that takes the place of the old _POSIX_SAVED_IDS -- it turns out that the POSIX interface is broken enough to break some systems badly. This includes some fixes for HP-UX. Also fixes problems where the real uid is not reset properly on startup (from Neil Rickert). Fix a problem that caused timed out messages to not report the addresses that timed out. Error messages are also more "user friendly". Drop required bandwidth on connections from 64 bytes/sec to 16 bytes/sec. Further Solaris portability changes -- doesn't require the BSD compatibility library. This also adds a new "HASGETDTABLESIZE" compile flag which can be used if you want to use getdtablesize(2) instead of sysconf(2). These are loosely based on changes from David Meyer at University of Oregon. This now seems to work, at least for quick test cases. Fix a problem that can cause duplicate error messages to be sent if you are in SMTP, you send to multiple addresses, and at least one of those addresses is good and points to an account that has a .forward file (whew!). Fix a problem causing messages to be discarded if checkcompat() returned EX_TEMPFAIL (because it didn't properly mark the "to" address). Problem noted by John Myers. Fix dfopen to return NULL if the open failed; I was depending on fdopen(-1) returning NULL, which isn't the case. This isn't serious, but does result in weird error diagnoses. From Michael Corrigan. CONFIG: add UUCP_MAX_SIZE M4 macro to set the maximum size of messages sent through UUCP-family mailers. Suggested by Bill Wisner of The Well. CONFIG: if both MAILER(uucp) and MAILER(smtp) are specified, include a "uucp-dom" mailer that uses domain-style addressing. Suggested by Bill Wisner. CONFIG: Add LOCAL_SHELL_FLAGS and LOCAL_SHELL_ARGS to match LOCAL_MAILER_FLAGS and LOCAL_MAILER_ARGS. Suggested by Christophe Wolfhugel. CONFIG: Add OSTYPE(aix3). From Christophe Wolfhugel. 8.2/8.2 1993/07/11 Don't drop out on config file parse errors in -bt mode. On older configuration files, assume option "l" (use Errors-To header) for back compatibility. NOTE: this DOES NOT imply an endorsement of the Errors-To: header in any way. Accept -x flag on AIX-3 as well as OSF/1. Why, why, why??? Don't log errors on EHLO -- it isn't a "real" error for an old SMTP server to give an error on this command, and logging it in the transcript can be confusing. Fix from Bill Wisner. IRIX compatibility changes provided by Dan Rich . Solaris 2 compatibility changes. Provided by Bob Cunningham , John Oleynick Debugging: -d17 was overloaded (hostsignature and usersmtp.c); move usersmtp (smtpinit and smtpmailfrom) to -d18 to match the other flags in that file. Flush transcript before fork in mailfile(). From Eric Wassenaar. Save h_errno in mci struct and improve error message display. Changes from Eric Wassenaar. Open /dev/null for the transcript if the create of the xf file failed; this avoids at least one possible null pointer reference in very weird cases. From Eric Wassenaar. Clean up statistics gathering; it was over-reporting because of forks. From Eric Wassenaar. Fix problem that causes old Return-Path: line to override new Return-Path: line (conf.c needs H_FORCE to avoid re-using old value). From Motonori Nakamura. Fix broken -m flag in K definition -- even if -m (match only) was specified, it would still replace the key with the value. Noted by Rick McCarty of Texas Instruments. If the name server timed out over several days, no "timed out" message would ever be sent back. The timeout code has been moved from markfailure() to dropenvelope() so that all such failures should be diagnosed. Pointed out by Christophe Wolfhugel and others. Relax safefile() constraints: directories in an include or forward path must be readable by self if the controlling user owns the entry, readable by all otherwise (e.g., when reading your .forward file, you have to own and have X permission in it; everyone needs X permission in the root and directories leading up to your home); include files must be readable by anyone, but need not be owned by you. If _POSIX_SAVED_IDS is defined, setuid to the owner before reading a .forward file; this gets around some problems on NFS mounts if root permission is not exported and the user's home directory isn't x'able. Additional NeXT portability enhancements from Axel Zinser. Additional HP-UX portability enhancements from Brian Bullen. Add a timeout around SMTP message writes; this assumes you can get throughput of at least 64 bytes/second. Note that this does not impact the "datafinal" default, which is separate; this is just intended to work around network clogs that will occur before the final dot is sent. From Eric Wassenaar. Change map code to set the "include null" flag adaptively -- it initially tries both, but if it finds anything matching without a null it never tries again with a null and vice versa. If -N is specified, it never tries without the null and creates new maps with a null byte. If -O is specified, it never tries with the null (for efficiency). If -N and -O are specified, you get -NO (get it?) lookup at all, so this would be a bad idea. If you don't specify either -N or -O, it adapts. Fix recognition of "same from address" so that MH submissions will insert the appropriate full name information; this used to work and got broken somewhere along the way. Some changes to eliminate some unnecessary SYSERRs in the log. For example, if you lost a connection, don't bother reporting that fact on the connection you lost. Add some "extended debugging" flags to try to track down why we get occasional problems with file descriptor one being closed when execing a mailer; it seems to only happen when there has been another error in the same transaction. This requires XDEBUG, defined by default in conf.h. Add "-X filename" command line flag, which logs both sides of all SMTP transactions. This is intended ONLY for debugging bad implementations of other mailers; start it up, send a message from a mailer that is failing, and then kill it off and examine the indicated log. This output is not intended to be particularly human readable. This also adds the HASSETVBUF compile flag, defaulted on if your compiler defines __STDC__. CONFIG: change SMART_HOST to override an SMTP mailer. If you have a local net that should get direct connects, you will need to use LOCAL_NET_CONFIG to catch these hosts. See cf/README for an example. CONFIG: add LOCAL_MAILER_ARGS (default: `mail -d $u') to handle sites that don't use the -d flag. CONFIG: hide recipient addresses as well as sender addresses behind $M if FEATURE(allmasquerade) is specified; this has been requested by several people, but can break local aliases. For example, if you mail to "localalias" this will be rewritten as "localalias@masqueradehost"; although initial delivery will work, replies will be broken. Use it sparingly. CONFIG: add FEATURE(domaintable). This maps unqualified domains to qualified domains in headers. I believe this is largely equivalent to the IDA feature of the same name. CONFIG: use $U as UUCP name instead of $k. This permits you to override the "system name" as your UUCP name -- in particular, to use domain-ized UUCP names. From Bill Wisner of The Well. CONFIG: create new mailer "esmtp" that always tries EHLO first. This is currently unused in the config files, but could be used in a mailertable entry. 8.1C/8.1B 1993/06/27 Serious security bug fix: it was possible to read any file on the system, regardless of ownership and permissions. If a subroutine returns a fully qualified address, return it immediately instead of feeding it back into rewriting. This fixes a problem with mailertable lookups. CONFIG: fix some M4 frotz (concat => CONCAT) 8.1B/8.1A 1993/06/12 Serious bug fix: pattern matching backup algorithm stepped by two tokens in classes instead of one. Found by Claus Assmann at University of Kiel, Germany. 8.1A/8.1A 1993/06/08 Another mailertable fix.... 8.1/8.1 1993/06/07 4.4BSD freeze. No semantic changes. Index: head/contrib/sendmail/cf/cf/submit.cf =================================================================== --- head/contrib/sendmail/cf/cf/submit.cf (revision 249728) +++ head/contrib/sendmail/cf/cf/submit.cf (revision 249729) @@ -1,1468 +1,1468 @@ # # Copyright (c) 1998-2004, 2009, 2010 Sendmail, Inc. and its suppliers. # All rights reserved. # Copyright (c) 1983, 1995 Eric P. Allman. All rights reserved. # Copyright (c) 1988, 1993 # The Regents of the University of California. All rights reserved. # # By using this file, you agree to the terms and conditions set # forth in the LICENSE file which can be found at the top level of # the sendmail distribution. # # ###################################################################### ###################################################################### ##### ##### SENDMAIL CONFIGURATION FILE ##### -##### built by ca@wiz.smi.sendmail.com on Fri Dec 21 10:45:15 PST 2012 -##### in /extra/home/ca/sm-8.14.6/OpenSource/sendmail-8.14.6/cf/cf +##### built by ca@wiz.smi.sendmail.com on Fri Apr 19 08:04:44 PDT 2013 +##### in /extra/home/ca/sm-8.14.7/OpenSource/sendmail-8.14.7/cf/cf ##### using ../ as configuration include directory ##### ###################################################################### ##### ##### DO NOT EDIT THIS FILE! Only edit the source .mc file. ##### ###################################################################### ###################################################################### ##### $Id: cfhead.m4,v 8.121 2010/01/07 18:20:19 ca Exp $ ##### ##### $Id: cf.m4,v 8.32 1999/02/07 07:26:14 gshapiro Exp $ ##### ##### $Id: submit.mc,v 8.14 2006/04/05 05:54:41 ca Exp $ ##### ##### $Id: msp.m4,v 1.33 2004/02/09 22:32:38 ca Exp $ ##### ##### $Id: no_default_msa.m4,v 8.2 2001/02/14 05:03:22 gshapiro Exp $ ##### ##### $Id: proto.m4,v 8.760 2012/09/07 16:30:15 ca Exp $ ##### # level 10 config file format V10/Berkeley # override file safeties - setting this option compromises system security, # addressing the actual file configuration problem is preferred # need to set this before any file actions are encountered in the cf file #O DontBlameSendmail=safe # default LDAP map specification # need to set this now before any LDAP maps are defined #O LDAPDefaultSpec=-h localhost ################## # local info # ################## # my LDAP cluster # need to set this before any LDAP lookups are done (including classes) #D{sendmailMTACluster}$m Cwlocalhost # my official domain name # ... define this only if sendmail cannot automatically determine your domain #Dj$w.Foo.COM # host/domain names ending with a token in class P are canonical CP. # "Smart" relay host (may be null) DS # operators that cannot be in local usernames (i.e., network indicators) CO @ % ! # a class with just dot (for identifying canonical names) C.. # a class with just a left bracket (for identifying domain literals) C[[ # Resolve map (to check if a host exists in check_mail) Kresolve host -a -T C{ResOk}OKR # Hosts for which relaying is permitted ($=R) FR-o /etc/mail/relay-domains # arithmetic map Karith arith # dequoting map Kdequote dequote # class E: names that should be exposed as from this host, even if we masquerade # class L: names that should be delivered locally, even if we have a relay # class M: domains that should be converted to $M # class N: domains that should not be converted to $M #CL root # my name for error messages DnMAILER-DAEMON D{MTAHost}[127.0.0.1] # Configuration version number -DZ8.14.6/Submit +DZ8.14.7/Submit ############### # Options # ############### # strip message body to 7 bits on input? O SevenBitInput=False # 8-bit data handling #O EightBitMode=pass8 # wait for alias file rebuild (default units: minutes) O AliasWait=10 # location of alias file #O AliasFile=/etc/mail/aliases # minimum number of free blocks on filesystem O MinFreeBlocks=100 # maximum message size #O MaxMessageSize=0 # substitution for space (blank) characters O BlankSub=. # avoid connecting to "expensive" mailers on initial submission? O HoldExpensive=False # checkpoint queue runs after every N successful deliveries #O CheckpointInterval=10 # default delivery mode O DeliveryMode=i # error message header/file #O ErrorHeader=/etc/mail/error-header # error mode #O ErrorMode=print # save Unix-style "From_" lines at top of header? #O SaveFromLine=False # queue file mode (qf files) O QueueFileMode=0660 # temporary file mode O TempFileMode=0600 # match recipients against GECOS field? #O MatchGECOS=False # maximum hop count #O MaxHopCount=25 # location of help file O HelpFile=/etc/mail/helpfile # ignore dots as terminators in incoming messages? #O IgnoreDots=False # name resolver options #O ResolverOptions=+AAONLY # deliver MIME-encapsulated error messages? O SendMimeErrors=True # Forward file search path O ForwardPath # open connection cache size O ConnectionCacheSize=2 # open connection cache timeout O ConnectionCacheTimeout=5m # persistent host status directory #O HostStatusDirectory=.hoststat # single thread deliveries (requires HostStatusDirectory)? #O SingleThreadDelivery=False # use Errors-To: header? O UseErrorsTo=False # log level O LogLevel=9 # send to me too, even in an alias expansion? #O MeToo=True # verify RHS in newaliases? O CheckAliases=False # default messages to old style headers if no special punctuation? O OldStyleHeaders=True # SMTP daemon options O DaemonPortOptions=Name=NoMTA, Addr=127.0.0.1, M=E # SMTP client options #O ClientPortOptions=Family=inet, Address=0.0.0.0 # Modifiers to define {daemon_flags} for direct submissions #O DirectSubmissionModifiers # Use as mail submission program? See sendmail/SECURITY O UseMSP=True # privacy flags O PrivacyOptions=goaway,noetrn,restrictqrun # who (if anyone) should get extra copies of error messages #O PostmasterCopy=Postmaster # slope of queue-only function #O QueueFactor=600000 # limit on number of concurrent queue runners #O MaxQueueChildren # maximum number of queue-runners per queue-grouping with multiple queues #O MaxRunnersPerQueue=1 # priority of queue runners (nice(3)) #O NiceQueueRun # shall we sort the queue by hostname first? #O QueueSortOrder=priority # minimum time in queue before retry #O MinQueueAge=30m # how many jobs can you process in the queue? #O MaxQueueRunSize=0 # perform initial split of envelope without checking MX records #O FastSplit=1 # queue directory O QueueDirectory=/var/spool/clientmqueue # key for shared memory; 0 to turn off, -1 to auto-select #O SharedMemoryKey=0 # file to store auto-selected key for shared memory (SharedMemoryKey = -1) #O SharedMemoryKeyFile # timeouts (many of these) #O Timeout.initial=5m #O Timeout.connect=5m #O Timeout.aconnect=0s #O Timeout.iconnect=5m #O Timeout.helo=5m #O Timeout.mail=10m #O Timeout.rcpt=1h #O Timeout.datainit=5m #O Timeout.datablock=1h #O Timeout.datafinal=1h #O Timeout.rset=5m #O Timeout.quit=2m #O Timeout.misc=2m #O Timeout.command=1h #O Timeout.ident=5s #O Timeout.fileopen=60s #O Timeout.control=2m O Timeout.queuereturn=5d #O Timeout.queuereturn.normal=5d #O Timeout.queuereturn.urgent=2d #O Timeout.queuereturn.non-urgent=7d #O Timeout.queuereturn.dsn=5d O Timeout.queuewarn=4h #O Timeout.queuewarn.normal=4h #O Timeout.queuewarn.urgent=1h #O Timeout.queuewarn.non-urgent=12h #O Timeout.queuewarn.dsn=4h #O Timeout.hoststatus=30m #O Timeout.resolver.retrans=5s #O Timeout.resolver.retrans.first=5s #O Timeout.resolver.retrans.normal=5s #O Timeout.resolver.retry=4 #O Timeout.resolver.retry.first=4 #O Timeout.resolver.retry.normal=4 #O Timeout.lhlo=2m #O Timeout.auth=10m #O Timeout.starttls=1h # time for DeliverBy; extension disabled if less than 0 #O DeliverByMin=0 # should we not prune routes in route-addr syntax addresses? #O DontPruneRoutes=False # queue up everything before forking? O SuperSafe=True # status file O StatusFile=/var/spool/clientmqueue/sm-client.st # time zone handling: # if undefined, use system default # if defined but null, use TZ envariable passed in # if defined and non-null, use that info O TimeZoneSpec= # default UID (can be username or userid:groupid) #O DefaultUser=mailnull # list of locations of user database file (null means no lookup) #O UserDatabaseSpec=/etc/mail/userdb # fallback MX host #O FallbackMXhost=fall.back.host.net # fallback smart host #O FallbackSmartHost=fall.back.host.net # if we are the best MX host for a site, try it directly instead of config err #O TryNullMXList=False # load average at which we just queue messages #O QueueLA=8 # load average at which we refuse connections #O RefuseLA=12 # log interval when refusing connections for this long #O RejectLogInterval=3h # load average at which we delay connections; 0 means no limit #O DelayLA=0 # maximum number of children we allow at one time #O MaxDaemonChildren=0 # maximum number of new connections per second #O ConnectionRateThrottle=0 # Width of the window #O ConnectionRateWindowSize=60s # work recipient factor #O RecipientFactor=30000 # deliver each queued job in a separate process? #O ForkEachJob=False # work class factor #O ClassFactor=1800 # work time factor #O RetryFactor=90000 # default character set #O DefaultCharSet=unknown-8bit # service switch file (name hardwired on Solaris, Ultrix, OSF/1, others) #O ServiceSwitchFile=/etc/mail/service.switch # hosts file (normally /etc/hosts) #O HostsFile=/etc/hosts # dialup line delay on connection failure #O DialDelay=0s # action to take if there are no recipients in the message #O NoRecipientAction=none # chrooted environment for writing to files #O SafeFileEnvironment # are colons OK in addresses? #O ColonOkInAddr=True # shall I avoid expanding CNAMEs (violates protocols)? #O DontExpandCnames=False # SMTP initial login message (old $e macro) O SmtpGreetingMessage=$j Sendmail $v/$Z; $b # UNIX initial From header format (old $l macro) O UnixFromLine=From $g $d # From: lines that have embedded newlines are unwrapped onto one line #O SingleLineFromHeader=False # Allow HELO SMTP command that does not include a host name #O AllowBogusHELO=False # Characters to be quoted in a full name phrase (@,;:\()[] are automatic) #O MustQuoteChars=. # delimiter (operator) characters (old $o macro) O OperatorChars=.:%@!^/[]+ # shall I avoid calling initgroups(3) because of high NIS costs? O DontInitGroups=True # are group-writable :include: and .forward files (un)trustworthy? # True (the default) means they are not trustworthy. #O UnsafeGroupWrites=True # where do errors that occur when sending errors get sent? #O DoubleBounceAddress=postmaster # issue temporary errors (4xy) instead of permanent errors (5xy)? #O SoftBounce=False # where to save bounces if all else fails #O DeadLetterDrop=/var/tmp/dead.letter # what user id do we assume for the majority of the processing? O RunAsUser=smmsp # maximum number of recipients per SMTP envelope #O MaxRecipientsPerMessage=0 # limit the rate recipients per SMTP envelope are accepted # once the threshold number of recipients have been rejected #O BadRcptThrottle=0 # shall we get local names from our installed interfaces? O DontProbeInterfaces=True # Return-Receipt-To: header implies DSN request #O RrtImpliesDsn=False # override connection address (for testing) #O ConnectOnlyTo=0.0.0.0 # Trusted user for file ownership and starting the daemon O TrustedUser=smmsp # Control socket for daemon management #O ControlSocketName=/var/spool/mqueue/.control # Maximum MIME header length to protect MUAs #O MaxMimeHeaderLength=0/0 # Maximum length of the sum of all headers #O MaxHeadersLength=32768 # Maximum depth of alias recursion #O MaxAliasRecursion=10 # location of pid file O PidFile=/var/spool/clientmqueue/sm-client.pid # Prefix string for the process title shown on 'ps' listings #O ProcessTitlePrefix=prefix # Data file (df) memory-buffer file maximum size #O DataFileBufferSize=4096 # Transcript file (xf) memory-buffer file maximum size #O XscriptFileBufferSize=4096 # lookup type to find information about local mailboxes #O MailboxDatabase=pw # override compile time flag REQUIRES_DIR_FSYNC #O RequiresDirfsync=true # list of authentication mechanisms #O AuthMechanisms=EXTERNAL GSSAPI KERBEROS_V4 DIGEST-MD5 CRAM-MD5 # Authentication realm #O AuthRealm # default authentication information for outgoing connections #O DefaultAuthInfo=/etc/mail/default-auth-info # SMTP AUTH flags #O AuthOptions # SMTP AUTH maximum encryption strength #O AuthMaxBits # SMTP STARTTLS server options #O TLSSrvOptions # Input mail filters #O InputMailFilters # CA directory #O CACertPath # CA file #O CACertFile # Server Cert #O ServerCertFile # Server private key #O ServerKeyFile # Client Cert #O ClientCertFile # Client private key #O ClientKeyFile # File containing certificate revocation lists #O CRLFile # DHParameters (only required if DSA/DH is used) #O DHParameters # Random data source (required for systems without /dev/urandom under OpenSSL) #O RandFile # Maximum number of "useless" commands before slowing down #O MaxNOOPCommands=20 # Name to use for EHLO (defaults to $j) #O HeloName ############################ # QUEUE GROUP DEFINITIONS # ############################ ########################### # Message precedences # ########################### Pfirst-class=0 Pspecial-delivery=100 Plist=-30 Pbulk=-60 Pjunk=-100 ##################### # Trusted users # ##################### # this is equivalent to setting class "t" #Ft/etc/mail/trusted-users Troot Tdaemon Tuucp ######################### # Format of headers # ######################### H?P?Return-Path: <$g> HReceived: $?sfrom $s $.$?_($?s$|from $.$_) $.$?{auth_type}(authenticated$?{auth_ssf} bits=${auth_ssf}$.) $.by $j ($v/$Z)$?r with $r$. id $i$?{tls_version} (version=${tls_version} cipher=${cipher} bits=${cipher_bits} verify=${verify})$.$?u for $u; $|; $.$b H?D?Resent-Date: $a H?D?Date: $a H?F?Resent-From: $?x$x <$g>$|$g$. H?F?From: $?x$x <$g>$|$g$. H?x?Full-Name: $x # HPosted-Date: $a # H?l?Received-Date: $b H?M?Resent-Message-Id: <$t.$i@$j> H?M?Message-Id: <$t.$i@$j> # ###################################################################### ###################################################################### ##### ##### REWRITING RULES ##### ###################################################################### ###################################################################### ############################################ ### Ruleset 3 -- Name Canonicalization ### ############################################ Scanonify=3 # handle null input (translate to <@> special case) R$@ $@ <@> # strip group: syntax (not inside angle brackets!) and trailing semicolon R$* $: $1 <@> mark addresses R$* < $* > $* <@> $: $1 < $2 > $3 unmark R@ $* <@> $: @ $1 unmark @host:... R$* [ IPv6 : $+ ] <@> $: $1 [ IPv6 : $2 ] unmark IPv6 addr R$* :: $* <@> $: $1 :: $2 unmark node::addr R:include: $* <@> $: :include: $1 unmark :include:... R$* : $* [ $* ] $: $1 : $2 [ $3 ] <@> remark if leading colon R$* : $* <@> $: $2 strip colon if marked R$* <@> $: $1 unmark R$* ; $1 strip trailing semi R$* < $+ :; > $* $@ $2 :; <@> catch R$* < $* ; > $1 < $2 > bogus bracketed semi # null input now results from list:; syntax R$@ $@ :; <@> # strip angle brackets -- note RFC733 heuristic to get innermost item R$* $: < $1 > housekeeping <> R$+ < $* > < $2 > strip excess on left R< $* > $+ < $1 > strip excess on right R<> $@ < @ > MAIL FROM:<> case R< $+ > $: $1 remove housekeeping <> # strip route address <@a,@b,@c:user@d> -> R@ $+ , $+ $2 R@ [ $* ] : $+ $2 R@ $+ : $+ $2 # find focus for list syntax R $+ : $* ; @ $+ $@ $>Canonify2 $1 : $2 ; < @ $3 > list syntax R $+ : $* ; $@ $1 : $2; list syntax # find focus for @ syntax addresses R$+ @ $+ $: $1 < @ $2 > focus on domain R$+ < $+ @ $+ > $1 $2 < @ $3 > move gaze right R$+ < @ $+ > $@ $>Canonify2 $1 < @ $2 > already canonical # convert old-style addresses to a domain-based address R$- ! $+ $@ $>Canonify2 $2 < @ $1 .UUCP > resolve uucp names R$+ . $- ! $+ $@ $>Canonify2 $3 < @ $1 . $2 > domain uucps R$+ ! $+ $@ $>Canonify2 $2 < @ $1 .UUCP > uucp subdomains # convert node::user addresses into a domain-based address R$- :: $+ $@ $>Canonify2 $2 < @ $1 .DECNET > resolve DECnet names R$- . $- :: $+ $@ $>Canonify2 $3 < @ $1.$2 .DECNET > numeric DECnet addr # if we have % signs, take the rightmost one R$* % $* $1 @ $2 First make them all @s. R$* @ $* @ $* $1 % $2 @ $3 Undo all but the last. R$* @ $* $@ $>Canonify2 $1 < @ $2 > Insert < > and finish # else we must be a local name R$* $@ $>Canonify2 $1 ################################################ ### Ruleset 96 -- bottom half of ruleset 3 ### ################################################ SCanonify2=96 # handle special cases for local names R$* < @ localhost > $* $: $1 < @ $j . > $2 no domain at all R$* < @ localhost . $m > $* $: $1 < @ $j . > $2 local domain R$* < @ localhost . UUCP > $* $: $1 < @ $j . > $2 .UUCP domain # check for IPv4/IPv6 domain literal R$* < @ [ $+ ] > $* $: $1 < @@ [ $2 ] > $3 mark [addr] R$* < @@ $=w > $* $: $1 < @ $j . > $3 self-literal R$* < @@ $+ > $* $@ $1 < @ $2 > $3 canon IP addr # if really UUCP, handle it immediately # try UUCP traffic as a local address R$* < @ $+ . UUCP > $* $: $1 < @ $[ $2 $] . UUCP . > $3 R$* < @ $+ . . UUCP . > $* $@ $1 < @ $2 . > $3 # hostnames ending in class P are always canonical R$* < @ $* $=P > $* $: $1 < @ $2 $3 . > $4 R$* < @ $* $~P > $* $: $&{daemon_flags} $| $1 < @ $2 $3 > $4 R$* CC $* $| $* < @ $+.$+ > $* $: $3 < @ $4.$5 . > $6 R$* CC $* $| $* $: $3 # pass to name server to make hostname canonical R$* $| $* < @ $* > $* $: $2 < @ $[ $3 $] > $4 R$* $| $* $: $2 # local host aliases and pseudo-domains are always canonical R$* < @ $=w > $* $: $1 < @ $2 . > $3 R$* < @ $=M > $* $: $1 < @ $2 . > $3 R$* < @ $* . . > $* $1 < @ $2 . > $3 ################################################## ### Ruleset 4 -- Final Output Post-rewriting ### ################################################## Sfinal=4 R$+ :; <@> $@ $1 : handle R$* <@> $@ handle <> and list:; # strip trailing dot off possibly canonical name R$* < @ $+ . > $* $1 < @ $2 > $3 # eliminate internal code R$* < @ *LOCAL* > $* $1 < @ $j > $2 # externalize local domain info R$* < $+ > $* $1 $2 $3 defocus R@ $+ : @ $+ : $+ @ $1 , @ $2 : $3 canonical R@ $* $@ @ $1 ... and exit # UUCP must always be presented in old form R$+ @ $- . UUCP $2!$1 u@h.UUCP => h!u # put DECnet back in :: form R$+ @ $+ . DECNET $2 :: $1 u@h.DECNET => h::u # delete duplicate local names R$+ % $=w @ $=w $1 @ $2 u%host@host => u@host ############################################################## ### Ruleset 97 -- recanonicalize and call ruleset zero ### ### (used for recursive calls) ### ############################################################## SRecurse=97 R$* $: $>canonify $1 R$* $@ $>parse $1 ###################################### ### Ruleset 0 -- Parse Address ### ###################################### Sparse=0 R$* $: $>Parse0 $1 initial parsing R<@> $#local $: <@> special case error msgs R$* $: $>ParseLocal $1 handle local hacks R$* $: $>Parse1 $1 final parsing # # Parse0 -- do initial syntax checking and eliminate local addresses. # This should either return with the (possibly modified) input # or return with a #error mailer. It should not return with a # #mailer other than the #error mailer. # SParse0 R<@> $@ <@> special case error msgs R$* : $* ; <@> $#error $@ 5.1.3 $: "553 List:; syntax illegal for recipient addresses" R@ <@ $* > < @ $1 > catch "@@host" bogosity R<@ $+> $#error $@ 5.1.3 $: "553 User address required" R$+ <@> $#error $@ 5.1.3 $: "553 Hostname required" R$* $: <> $1 R<> $* < @ [ $* ] : $+ > $* $1 < @ [ $2 ] : $3 > $4 R<> $* < @ [ $* ] , $+ > $* $1 < @ [ $2 ] , $3 > $4 R<> $* < @ [ $* ] $+ > $* $#error $@ 5.1.2 $: "553 Invalid address" R<> $* < @ [ $+ ] > $* $1 < @ [ $2 ] > $3 R<> $* <$* : $* > $* $#error $@ 5.1.3 $: "553 Colon illegal in host name part" R<> $* $1 R$* < @ . $* > $* $#error $@ 5.1.2 $: "553 Invalid host name" R$* < @ $* .. $* > $* $#error $@ 5.1.2 $: "553 Invalid host name" R$* < @ $* @ > $* $#error $@ 5.1.2 $: "553 Invalid route address" R$* @ $* < @ $* > $* $#error $@ 5.1.3 $: "553 Invalid route address" R$* , $~O $* $#error $@ 5.1.3 $: "553 Invalid route address" # now delete the local info -- note $=O to find characters that cause forwarding R$* < @ > $* $@ $>Parse0 $>canonify $1 user@ => user R< @ $=w . > : $* $@ $>Parse0 $>canonify $2 @here:... -> ... R$- < @ $=w . > $: $(dequote $1 $) < @ $2 . > dequote "foo"@here R< @ $+ > $#error $@ 5.1.3 $: "553 User address required" R$* $=O $* < @ $=w . > $@ $>Parse0 $>canonify $1 $2 $3 ...@here -> ... R$- $: $(dequote $1 $) < @ *LOCAL* > dequote "foo" R< @ *LOCAL* > $#error $@ 5.1.3 $: "553 User address required" R$* $=O $* < @ *LOCAL* > $@ $>Parse0 $>canonify $1 $2 $3 ...@*LOCAL* -> ... R$* < @ *LOCAL* > $: $1 # # Parse1 -- the bottom half of ruleset 0. # SParse1 # handle numeric address spec R$* < @ [ $+ ] > $* $: $>ParseLocal $1 < @ [ $2 ] > $3 numeric internet spec R$* < @ [ $+ ] > $* $: $1 < @ [ $2 ] : $S > $3 Add smart host to path R$* < @ [ $+ ] : > $* $#esmtp $@ [$2] $: $1 < @ [$2] > $3 no smarthost: send R$* < @ [ $+ ] : $- : $*> $* $#$3 $@ $4 $: $1 < @ [$2] > $5 smarthost with mailer R$* < @ [ $+ ] : $+ > $* $#esmtp $@ $3 $: $1 < @ [$2] > $4 smarthost without mailer # short circuit local delivery so forwarded email works R$=L < @ $=w . > $#local $: @ $1 special local names R$+ < @ $=w . > $#local $: $1 regular local name # resolve remotely connected UUCP links (if any) # resolve fake top level domains by forwarding to other hosts # pass names that still have a host to a smarthost (if defined) R$* < @ $* > $* $: $>MailerToTriple < $S > $1 < @ $2 > $3 glue on smarthost name # deal with other remote names R$* < @$* > $* $#esmtp $@ $2 $: $1 < @ $2 > $3 user@host.domain # handle locally delivered names R$=L $#local $: @ $1 special local names R$+ $#local $: $1 regular local names ########################################################################### ### Ruleset 5 -- special rewriting after aliases have been expanded ### ########################################################################### SLocal_localaddr Slocaladdr=5 R$+ $: $1 $| $>"Local_localaddr" $1 R$+ $| $#ok $@ $1 no change R$+ $| $#$* $#$2 R$+ $| $* $: $1 # deal with plussed users so aliases work nicely R$+ + * $#local $@ $&h $: $1 R$+ + $* $#local $@ + $2 $: $1 + * # prepend an empty "forward host" on the front R$+ $: <> $1 R< > $+ $: < > < $1 <> $&h > nope, restore +detail R< > < $+ <> + $* > $: < > < $1 + $2 > check whether +detail R< > < $+ <> $* > $: < > < $1 > else discard R< > < $+ + $* > $* < > < $1 > + $2 $3 find the user part R< > < $+ > + $* $#local $@ $2 $: @ $1 strip the extra + R< > < $+ > $@ $1 no +detail R$+ $: $1 <> $&h add +detail back in R$+ <> + $* $: $1 + $2 check whether +detail R$+ <> $* $: $1 else discard R< local : $* > $* $: $>MailerToTriple < local : $1 > $2 no host extension R< error : $* > $* $: $>MailerToTriple < error : $1 > $2 no host extension R< $~[ : $+ > $+ $: $>MailerToTriple < $1 : $2 > $3 < @ $2 > R< $+ > $+ $@ $>MailerToTriple < $1 > $2 < @ $1 > ################################################################### ### Ruleset 95 -- canonify mailer:[user@]host syntax to triple ### ################################################################### SMailerToTriple=95 R< > $* $@ $1 strip off null relay R< error : $-.$-.$- : $+ > $* $#error $@ $1.$2.$3 $: $4 R< error : $- : $+ > $* $#error $@ $(dequote $1 $) $: $2 R< error : $+ > $* $#error $: $1 R< local : $* > $* $>CanonLocal < $1 > $2 R< $~[ : $+ @ $+ > $*<$*>$* $# $1 $@ $3 $: $2<@$3> use literal user R< $~[ : $+ > $* $# $1 $@ $2 $: $3 try qualified mailer R< $=w > $* $@ $2 delete local host R< $+ > $* $#relay $@ $1 $: $2 use unqualified mailer ################################################################### ### Ruleset CanonLocal -- canonify local: syntax ### ################################################################### SCanonLocal # strip local host from routed addresses R< $* > < @ $+ > : $+ $@ $>Recurse $3 R< $* > $+ $=O $+ < @ $+ > $@ $>Recurse $2 $3 $4 # strip trailing dot from any host name that may appear R< $* > $* < @ $* . > $: < $1 > $2 < @ $3 > # handle local: syntax -- use old user, either with or without host R< > $* < @ $* > $* $#local $@ $1@$2 $: $1 R< > $+ $#local $@ $1 $: $1 # handle local:user@host syntax -- ignore host part R< $+ @ $+ > $* < @ $* > $: < $1 > $3 < @ $4 > # handle local:user syntax R< $+ > $* <@ $* > $* $#local $@ $2@$3 $: $1 R< $+ > $* $#local $@ $2 $: $1 ################################################################### ### Ruleset 93 -- convert header names to masqueraded form ### ################################################################### SMasqHdr=93 # do not masquerade anything in class N R$* < @ $* $=N . > $@ $1 < @ $2 $3 . > R$* < @ *LOCAL* > $@ $1 < @ $j . > ################################################################### ### Ruleset 94 -- convert envelope names to masqueraded form ### ################################################################### SMasqEnv=94 R$* < @ *LOCAL* > $* $: $1 < @ $j . > $2 ################################################################### ### Ruleset 98 -- local part of ruleset zero (can be null) ### ################################################################### SParseLocal=98 ###################################################################### ### CanonAddr -- Convert an address into a standard form for ### relay checking. Route address syntax is ### crudely converted into a %-hack address. ### ### Parameters: ### $1 -- full recipient address ### ### Returns: ### parsed address, not in source route form ###################################################################### SCanonAddr R$* $: $>Parse0 $>canonify $1 make domain canonical ###################################################################### ### ParseRecipient -- Strip off hosts in $=R as well as possibly ### $* $=m or the access database. ### Check user portion for host separators. ### ### Parameters: ### $1 -- full recipient address ### ### Returns: ### parsed, non-local-relaying address ###################################################################### SParseRecipient R$* $: $>CanonAddr $1 R $* < @ $* . > $1 < @ $2 > strip trailing dots R $- < @ $* > $: $(dequote $1 $) < @ $2 > dequote local part # if no $=O character, no host in the user portion, we are done R $* $=O $* < @ $* > $: $1 $2 $3 < @ $4> R $* $@ $1 R $* < @ $* $=R > $: $1 < @ $2 $3 > R $* < @ $* > $@ $>ParseRecipient $1 R<$+> $* $@ $2 ###################################################################### ### check_relay -- check hostname/address on SMTP startup ###################################################################### SLocal_check_relay Scheck_relay R$* $: $1 $| $>"Local_check_relay" $1 R$* $| $* $| $#$* $#$3 R$* $| $* $| $* $@ $>"Basic_check_relay" $1 $| $2 SBasic_check_relay # check for deferred delivery mode R$* $: < $&{deliveryMode} > $1 R< d > $* $@ deferred R< $* > $* $: $2 ###################################################################### ### check_mail -- check SMTP `MAIL FROM:' command argument ###################################################################### SLocal_check_mail Scheck_mail R$* $: $1 $| $>"Local_check_mail" $1 R$* $| $#$* $#$2 R$* $| $* $@ $>"Basic_check_mail" $1 SBasic_check_mail # check for deferred delivery mode R$* $: < $&{deliveryMode} > $1 R< d > $* $@ deferred R< $* > $* $: $2 # authenticated? R$* $: $1 $| $>"tls_client" $&{verify} $| MAIL R$* $| $#$+ $#$2 R$* $| $* $: $1 R<> $@ we MUST accept <> (RFC 1123) R$+ $: $1 R<$+> $: <@> <$1> R$+ $: <@> <$1> R$* $: $&{daemon_flags} $| $1 R$* f $* $| <@> < $* @ $- > $: < ? $&{client_name} > < $3 @ $4 > R$* u $* $| <@> < $* > $: < $3 > R$* $| $* $: $2 # handle case of @localhost on address R<@> < $* @ localhost > $: < ? $&{client_name} > < $1 @ localhost > R<@> < $* @ [127.0.0.1] > $: < ? $&{client_name} > < $1 @ [127.0.0.1] > R<@> < $* @ localhost.$m > $: < ? $&{client_name} > < $1 @ localhost.$m > R<@> < $* @ localhost.UUCP > $: < ? $&{client_name} > < $1 @ localhost.UUCP > R<@> $* $: $1 no localhost as domain R $* $: $2 local client: ok R <$+> $#error $@ 5.5.4 $: "553 Real domain name required for sender address" R $* $: $1 R$* $: $>CanonAddr $1 canonify sender address and mark it R $* < @ $+ . > $1 < @ $2 > strip trailing dots # handle non-DNS hostnames (*.bitnet, *.decnet, *.uucp, etc) R $* < @ $* $=P > $: $1 < @ $2 $3 > R $* < @ $j > $: $1 < @ $j > R $* < @ $+ > $: $) > $1 < @ $2 > R> $* < @ $+ > $: <$2> $3 < @ $4 > # handle case of no @domain on address R $* $: $&{daemon_flags} $| $1 R$* u $* $| $* $: $3 R$* $| $* $: $2 R $* $: < ? $&{client_addr} > $1 R $* $@ ...local unqualed ok R $* $#error $@ 5.5.4 $: "553 Domain name required for sender address " $&f ...remote is not # check results R $* $: @ $1 mark address: nothing known about it R<$={ResOk}> $* $: @ $2 domain ok R $* $#error $@ 4.1.8 $: "451 Domain of sender address " $&f " does not resolve" R $* $#error $@ 5.1.8 $: "553 Domain of sender address " $&f " does not exist" ###################################################################### ### check_rcpt -- check SMTP `RCPT TO:' command argument ###################################################################### SLocal_check_rcpt Scheck_rcpt R$* $: $1 $| $>"Local_check_rcpt" $1 R$* $| $#$* $#$2 R$* $| $* $@ $>"Basic_check_rcpt" $1 SBasic_check_rcpt # empty address? R<> $#error $@ nouser $: "553 User address required" R$@ $#error $@ nouser $: "553 User address required" # check for deferred delivery mode R$* $: < $&{deliveryMode} > $1 R< d > $* $@ deferred R< $* > $* $: $2 ###################################################################### R$* $: $1 $| @ $>"Rcpt_ok" $1 R$* $| @ $#TEMP $+ $: $1 $| T $2 R$* $| @ $#$* $#$2 R$* $| @ RELAY $@ RELAY R$* $| @ $* $: O $| $>"Relay_ok" $1 R$* $| T $+ $: T $2 $| $>"Relay_ok" $1 R$* $| $#TEMP $+ $#error $2 R$* $| $#$* $#$2 R$* $| RELAY $@ RELAY R T $+ $| $* $#error $1 # anything else is bogus R$* $#error $@ 5.7.1 $: "550 Relaying denied" ###################################################################### ### Rcpt_ok: is the recipient ok? ###################################################################### SRcpt_ok R$* $: $>ParseRecipient $1 strip relayable hosts # authenticated via TLS? R$* $: $1 $| $>RelayTLS client authenticated? R$* $| $# $+ $# $2 error/ok? R$* $| $* $: $1 no R$* $: $1 $| $>"Local_Relay_Auth" $&{auth_type} R$* $| $# $* $# $2 R$* $| NO $: $1 R$* $| $* $: $1 $| $&{auth_type} R$* $| $: $1 R$* $| $={TrustAuthMech} $# RELAY R$* $| $* $: $1 # anything terminating locally is ok R$+ < @ $=w > $@ RELAY R$+ < @ $* $=R > $@ RELAY # check for local user (i.e. unqualified address) R$* $: $1 R $* < @ $+ > $: $1 < @ $2 > # local user is ok R $+ $@ RELAY R<$+> $* $: $2 ###################################################################### ### Relay_ok: is the relay/sender ok? ###################################################################### SRelay_ok # anything originating locally is ok # check IP address R$* $: $&{client_addr} R$@ $@ RELAY originated locally R0 $@ RELAY originated locally R127.0.0.1 $@ RELAY originated locally RIPv6:::1 $@ RELAY originated locally R$=R $* $@ RELAY relayable IP address R$* $: [ $1 ] put brackets around it... R$=w $@ RELAY ... and see if it is local # check client name: first: did it resolve? R$* $: < $&{client_resolve} > R $#TEMP $@ 4.4.0 $: "450 Relaying temporarily denied. Cannot resolve PTR record for " $&{client_addr} R $#error $@ 5.7.1 $: "550 Relaying denied. IP name possibly forged " $&{client_name} R $#error $@ 5.7.1 $: "550 Relaying denied. IP name lookup failed " $&{client_name} R$* $: <@> $&{client_name} # pass to name server to make hostname canonical R<@> $* $=P $: $1 $2 R<@> $+ $: $[ $1 $] R$* . $1 strip trailing dots R $=w $@ RELAY R $* $=R $@ RELAY ###################################################################### ### trust_auth: is user trusted to authenticate as someone else? ### ### Parameters: ### $1: AUTH= parameter from MAIL command ###################################################################### SLocal_trust_auth Strust_auth R$* $: $&{auth_type} $| $1 # required by RFC 2554 section 4. R$@ $| $* $#error $@ 5.7.1 $: "550 not authenticated" R$* $| $&{auth_authen} $@ identical R$* $| <$&{auth_authen}> $@ identical R$* $| $* $: $1 $| $>"Local_trust_auth" $2 R$* $| $#$* $#$2 R$* $#error $@ 5.7.1 $: "550 " $&{auth_authen} " not allowed to act as " $&{auth_author} ###################################################################### ### Relay_Auth: allow relaying based on authentication? ### ### Parameters: ### $1: ${auth_type} ###################################################################### SLocal_Relay_Auth ###################################################################### ### srv_features: which features to offer to a client? ### (done in server) ###################################################################### Ssrv_features ###################################################################### ### try_tls: try to use STARTTLS? ### (done in client) ###################################################################### Stry_tls ###################################################################### ### tls_rcpt: is connection with server "good" enough? ### (done in client, per recipient) ### ### Parameters: ### $1: recipient ###################################################################### Stls_rcpt ###################################################################### ### tls_client: is connection with client "good" enough? ### (done in server) ### ### Parameters: ### ${verify} $| (MAIL|STARTTLS) ###################################################################### Stls_client R$* $| $* $@ $>"TLS_connection" $1 ###################################################################### ### tls_server: is connection with server "good" enough? ### (done in client) ### ### Parameter: ### ${verify} ###################################################################### Stls_server R$* $@ $>"TLS_connection" $1 ###################################################################### ### TLS_connection: is TLS connection "good" enough? ### ### Parameters: ### ${verify} ### Requirement: RHS from access map, may be ? for none. ###################################################################### STLS_connection RSOFTWARE $#error $@ 4.7.0 $: "403 TLS handshake." ###################################################################### ### RelayTLS: allow relaying based on TLS authentication ### ### Parameters: ### none ###################################################################### SRelayTLS # authenticated? ###################################################################### ### authinfo: lookup authinfo in the access map ### ### Parameters: ### $1: {server_name} ### $2: {server_addr} ###################################################################### Sauthinfo SLocal_localaddr R$+ $: $>ParseRecipient $1 R$* < @ $+ > $* $#relay $@ ${MTAHost} $: $1 < @ $2 > $3 # DECnet R$+ :: $+ $#relay $@ ${MTAHost} $: $1 :: $2 R$* $#relay $@ ${MTAHost} $: $1 < @ $j > # ###################################################################### ###################################################################### ##### ##### MAIL FILTER DEFINITIONS ##### ###################################################################### ###################################################################### # ###################################################################### ###################################################################### ##### ##### MAILER DEFINITIONS ##### ###################################################################### ###################################################################### ################################################## ### Local and Program Mailer specification ### ################################################## ##### $Id: local.m4,v 8.59 2004/11/23 00:37:25 ca Exp $ ##### # # Envelope sender rewriting # SEnvFromL R<@> $n errors to mailer-daemon R@ <@ $*> $n temporarily bypass Sun bogosity R$+ $: $>AddDomain $1 add local domain if needed R$* $: $>MasqEnv $1 do masquerading # # Envelope recipient rewriting # SEnvToL R$+ < @ $* > $: $1 strip host part R$+ + $* $: < $&{addr_type} > $1 + $2 mark with addr type R $+ + $* $: $1 remove +detail for sender R< $* > $+ $: $2 else remove mark # # Header sender rewriting # SHdrFromL R<@> $n errors to mailer-daemon R@ <@ $*> $n temporarily bypass Sun bogosity R$+ $: $>AddDomain $1 add local domain if needed R$* $: $>MasqHdr $1 do masquerading # # Header recipient rewriting # SHdrToL R$+ $: $>AddDomain $1 add local domain if needed R$* < @ *LOCAL* > $* $: $1 < @ $j . > $2 # # Common code to add local domain name (only if always-add-domain) # SAddDomain Mlocal, P=[IPC], F=lmDFMuXkw5, S=EnvFromL/HdrFromL, R=EnvToL/HdrToL, T=DNS/RFC822/SMTP, A=TCP $h Mprog, P=[IPC], F=lmDFMuXk5, S=EnvFromL/HdrFromL, R=EnvToL/HdrToL, D=$z:/, T=X-Unix/X-Unix/X-Unix, A=TCP $h ##################################### ### SMTP Mailer specification ### ##################################### ##### $Id: smtp.m4,v 8.65 2006/07/12 21:08:10 ca Exp $ ##### # # common sender and masquerading recipient rewriting # SMasqSMTP R$* < @ $* > $* $@ $1 < @ $2 > $3 already fully qualified R$+ $@ $1 < @ *LOCAL* > add local qualification # # convert pseudo-domain addresses to real domain addresses # SPseudoToReal # pass s through R< @ $+ > $* $@ < @ $1 > $2 resolve # output fake domains as user%fake@relay # do UUCP heuristics; note that these are shared with UUCP mailers R$+ < @ $+ .UUCP. > $: < $2 ! > $1 convert to UUCP form R$+ < @ $* > $* $@ $1 < @ $2 > $3 not UUCP form # leave these in .UUCP form to avoid further tampering R< $&h ! > $- ! $+ $@ $2 < @ $1 .UUCP. > R< $&h ! > $-.$+ ! $+ $@ $3 < @ $1.$2 > R< $&h ! > $+ $@ $1 < @ $&h .UUCP. > R< $+ ! > $+ $: $1 ! $2 < @ $Y > use UUCP_RELAY R$+ < @ $~[ $* : $+ > $@ $1 < @ $4 > strip mailer: part R$+ < @ > $: $1 < @ *LOCAL* > if no UUCP_RELAY # # envelope sender rewriting # SEnvFromSMTP R$+ $: $>PseudoToReal $1 sender/recipient common R$* :; <@> $@ list:; special case R$* $: $>MasqSMTP $1 qualify unqual'ed names R$+ $: $>MasqEnv $1 do masquerading # # envelope recipient rewriting -- # also header recipient if not masquerading recipients # SEnvToSMTP R$+ $: $>PseudoToReal $1 sender/recipient common R$+ $: $>MasqSMTP $1 qualify unqual'ed names R$* < @ *LOCAL* > $* $: $1 < @ $j . > $2 # # header sender and masquerading header recipient rewriting # SHdrFromSMTP R$+ $: $>PseudoToReal $1 sender/recipient common R:; <@> $@ list:; special case # do special header rewriting R$* <@> $* $@ $1 <@> $2 pass null host through R< @ $* > $* $@ < @ $1 > $2 pass route-addr through R$* $: $>MasqSMTP $1 qualify unqual'ed names R$+ $: $>MasqHdr $1 do masquerading # # relay mailer header masquerading recipient rewriting # SMasqRelay R$+ $: $>MasqSMTP $1 R$+ $: $>MasqHdr $1 Msmtp, P=[IPC], F=mDFMuXk5, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990, T=DNS/RFC822/SMTP, A=TCP $h Mesmtp, P=[IPC], F=mDFMuXak5, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990, T=DNS/RFC822/SMTP, A=TCP $h Msmtp8, P=[IPC], F=mDFMuX8k5, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990, T=DNS/RFC822/SMTP, A=TCP $h Mdsmtp, P=[IPC], F=mDFMuXa%k5, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990, T=DNS/RFC822/SMTP, A=TCP $h Mrelay, P=[IPC], F=mDFMuXa8k, S=EnvFromSMTP/HdrFromSMTP, R=MasqSMTP, E=\r\n, L=2040, T=DNS/RFC822/SMTP, A=TCP $h ### submit.mc ### # divert(-1) # # # # Copyright (c) 2001-2003 Sendmail, Inc. and its suppliers. # # All rights reserved. # # # # By using this file, you agree to the terms and conditions set # # forth in the LICENSE file which can be found at the top level of # # the sendmail distribution. # # # # # # # # # This is the prototype file for a set-group-ID sm-msp sendmail that # # acts as a initial mail submission program. # # # # divert(0)dnl # VERSIONID(`$Id: submit.mc,v 8.14 2006/04/05 05:54:41 ca Exp $') # define(`confCF_VERSION', `Submit')dnl # define(`__OSTYPE__',`')dnl dirty hack to keep proto.m4 from complaining # define(`_USE_DECNET_SYNTAX_', `1')dnl support DECnet # define(`confTIME_ZONE', `USE_TZ')dnl # define(`confDONT_INIT_GROUPS', `True')dnl # dnl # dnl If you use IPv6 only, change [127.0.0.1] to [IPv6:::1] # FEATURE(`msp', `[127.0.0.1]')dnl Index: head/contrib/sendmail/cf/m4/version.m4 =================================================================== --- head/contrib/sendmail/cf/m4/version.m4 (revision 249728) +++ head/contrib/sendmail/cf/m4/version.m4 (revision 249729) @@ -1,18 +1,18 @@ divert(-1) # -# Copyright (c) 1998-2012 Sendmail, Inc. and its suppliers. +# Copyright (c) 1998-2013 Sendmail, Inc. and its suppliers. # All rights reserved. # Copyright (c) 1983 Eric P. Allman. All rights reserved. # Copyright (c) 1988, 1993 # The Regents of the University of California. All rights reserved. # # By using this file, you agree to the terms and conditions set # forth in the LICENSE file which can be found at the top level of # the sendmail distribution. # # -VERSIONID(`$Id: version.m4,v 8.222 2012/12/19 05:11:43 ca Exp $') +VERSIONID(`$Id: version.m4,v 8.230 2013/04/18 15:07:16 ca Exp $') # divert(0) # Configuration version number -DZ8.14.6`'ifdef(`confCF_VERSION', `/confCF_VERSION') +DZ8.14.7`'ifdef(`confCF_VERSION', `/confCF_VERSION') Index: head/contrib/sendmail/contrib/etrn.pl =================================================================== --- head/contrib/sendmail/contrib/etrn.pl (revision 249728) +++ head/contrib/sendmail/contrib/etrn.pl (revision 249729) @@ -1,218 +1,273 @@ -#!/usr/local/bin/perl -w +#!/usr/perl5/bin/perl -w # +# CDDL HEADER START +# +# The contents of this file are subject to the terms of the +# Common Development and Distribution License (the "License"). +# You may not use this file except in compliance with the License. +# +# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE +# or http://www.opensolaris.org/os/licensing. +# See the License for the specific language governing permissions +# and limitations under the License. +# +# When distributing Covered Code, include this CDDL HEADER in each +# file and include the License file at usr/src/OPENSOLARIS.LICENSE. +# If applicable, add the following below this CDDL HEADER, with the +# fields enclosed by brackets "[]" replaced with your own identifying +# information: Portions Copyright [yyyy] [name of copyright owner] +# +# CDDL HEADER END +# +# # Copyright (c) 1996-2000 by John T. Beck # All rights reserved. # -# Copyright (c) 2000 by Sun Microsystems, Inc. -# All rights reserved. +# Copyright 2008 Sun Microsystems, Inc. All rights reserved. +# Use is subject to license terms. # -#ident "@(#)etrn.pl 1.1 00/09/06 SMI" -require 5.005; # minimal Perl version required +require 5.8.4; # minimal Perl version required use strict; +use warnings; use English; -# hardcoded constants, should work fine for BSD-based systems use Socket; use Getopt::Std; -use vars qw($opt_v); -my $sockaddr = 'S n a4 x8'; +our ($opt_v, $opt_b); # system requirements: # must have 'hostname' program. my $port = 'smtp'; select(STDERR); chop(my $name = `hostname || uname -n`); -(my $hostname, my $aliases, my $type, my $len, undef) = gethostbyname($name); +my ($hostname) = (gethostbyname($name))[0]; -my $usage = "Usage: $PROGRAM_NAME [-v] host [args]"; -getopts('v'); +my $usage = "Usage: $PROGRAM_NAME [-bv] host [args]"; +getopts('bv'); my $verbose = $opt_v; +my $boot_check = $opt_b; my $server = shift(@ARGV); my @hosts = @ARGV; die $usage unless $server; my @cwfiles = (); my $alarm_action = ""; if (!@hosts) { push(@hosts, $hostname); open(CF, "){ # look for a line starting with "Fw" if (/^Fw.*$/) { my $cwfile = $ARG; chop($cwfile); my $optional = /^Fw-o/; # extract the file name $cwfile =~ s,^Fw[^/]*,,; # strip the options after the filename $cwfile =~ s/ [^ ]+$//; if (-r $cwfile) { push (@cwfiles, $cwfile); } else { die "$cwfile is not readable" unless $optional; } } # look for a line starting with "Cw" if (/^Cw(.*)$/) { my @cws = split (' ', $1); while (@cws) { my $thishost = shift(@cws); push(@hosts, $thishost) unless $thishost =~ "$hostname|localhost"; } } } close(CF); for my $cwfile (@cwfiles) { if (open(CW, "<$cwfile")) { while () { next if /^\#/; my $thishost = $ARG; chop($thishost); push(@hosts, $thishost) unless $thishost =~ $hostname; } close(CW); } else { die "open $cwfile: $ERRNO"; } } + # Do this automatically if no client hosts are specified. + $boot_check = "yes"; } -($name, $aliases, my $proto) = getprotobyname('tcp'); -($name, $aliases, $port) = getservbyname($port, 'tcp') +my ($proto) = (getprotobyname('tcp'))[2]; +($port) = (getservbyname($port, 'tcp'))[2] unless $port =~ /^\d+/; +if ($boot_check) { + # first connect to localhost to verify that we can accept connections + print "verifying that localhost is accepting SMTP connections\n" + if ($verbose); + my $localhost_ok = 0; + ($name, my $laddr) = (gethostbyname('localhost'))[0, 4]; + (!defined($name)) && die "gethostbyname failed, unknown host localhost"; + + # get a connection + my $sinl = sockaddr_in($port, $laddr); + my $save_errno = 0; + for (my $num_tries = 1; $num_tries < 5; $num_tries++) { + socket(S, &PF_INET, &SOCK_STREAM, $proto) + || die "socket: $ERRNO"; + if (connect(S, $sinl)) { + &alarm("sending 'quit' to $server"); + print S "quit\n"; + alarm(0); + $localhost_ok = 1; + close(S); + alarm(0); + last; + } + print STDERR "localhost connect failed ($num_tries)\n"; + $save_errno = $ERRNO; + sleep(1 << $num_tries); + close(S); + alarm(0); + } + if (! $localhost_ok) { + die "could not connect to localhost: $save_errno\n"; + } +} + # look it up -($name, $aliases, $type, $len, my $thataddr) = gethostbyname($server); +($name, my $thataddr) = (gethostbyname($server))[0, 4]; (!defined($name)) && die "gethostbyname failed, unknown host $server"; - + # get a connection -my $that = pack($sockaddr, &AF_INET, $port, $thataddr); -socket(S, &AF_INET, &SOCK_STREAM, $proto) +my $sinr = sockaddr_in($port, $thataddr); +socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $ERRNO"; print "server = $server\n" if (defined($verbose)); &alarm("connect to $server"); -if (! connect(S, $that)) { +if (! connect(S, $sinr)) { die "cannot connect to $server: $ERRNO\n"; } alarm(0); select((select(S), $OUTPUT_AUTOFLUSH = 1)[0]); # don't buffer output to S # read the greeting &alarm("greeting with $server"); while () { alarm(0); print if $verbose; if (/^(\d+)([- ])/) { # SMTP's initial greeting response code is 220. if ($1 != 220) { &alarm("giving up after bad response from $server"); &read_response($2, $verbose); alarm(0); print STDERR "$server: NOT 220 greeting: $ARG" if ($verbose); } last if ($2 eq " "); } else { print STDERR "$server: NOT 220 greeting: $ARG" if ($verbose); close(S); } &alarm("greeting with $server"); } alarm(0); &alarm("sending ehlo to $server"); &ps("ehlo $hostname"); my $etrn_support = 0; while () { if (/^250([- ])ETRN(.+)$/) { $etrn_support = 1; } print if $verbose; last if /^\d+ /; } alarm(0); if ($etrn_support) { print "ETRN supported\n" if ($verbose); &alarm("sending etrn to $server"); while (@hosts) { $server = shift(@hosts); &ps("etrn $server"); while () { print if $verbose; last if /^\d+ /; } sleep(1); } } else { print "\nETRN not supported\n\n" } &alarm("sending 'quit' to $server"); &ps("quit"); while () { print if $verbose; last if /^\d+ /; } close(S); alarm(0); select(STDOUT); exit(0); # print to the server (also to stdout, if -v) sub ps { my ($p) = @_; print ">>> $p\n" if $verbose; print S "$p\n"; } sub alarm { ($alarm_action) = @_; alarm(10); $SIG{ALRM} = 'handle_alarm'; } sub handle_alarm { &giveup($alarm_action); } sub giveup { my $reason = @_; (my $pk, my $file, my $line); ($pk, $file, $line) = caller; print "Timed out during $reason\n" if $verbose; exit(1); } # read the rest of the current smtp daemon's response (and toss it away) sub read_response { (my $done, $verbose) = @_; (my @resp); print my $s if $verbose; while (($done eq "-") && ($s = ) && ($s =~ /^\d+([- ])/)) { print $s if $verbose; $done = $1; push(@resp, $s); } return @resp; } Index: head/contrib/sendmail/doc/op/op.me =================================================================== --- head/contrib/sendmail/doc/op/op.me (revision 249728) +++ head/contrib/sendmail/doc/op/op.me (revision 249729) @@ -1,11504 +1,11511 @@ .\" Copyright (c) 1998-2005 Sendmail, Inc. and its suppliers. .\" All rights reserved. .\" Copyright (c) 1983, 1995 Eric P. Allman. All rights reserved. .\" Copyright (c) 1983, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" By using this file, you agree to the terms and conditions set .\" forth in the LICENSE file which can be found at the top level of .\" the sendmail distribution. .\" .\" -.\" $Id: op.me,v 8.749 2012/03/02 22:37:11 ca Exp $ +.\" $Id: op.me,v 8.751 2013/04/08 21:41:25 ca Exp $ .\" .\" eqn op.me | pic | troff -me .\" .\" Define \(sc if not defined (for text output) .\" .if !c \(sc .char \(sc S .\" .\" Define \(dg as "*" for text output and create a new .DG macro .\" which describes the symbol. .\" .if n .ds { [ .if n .ds } ] .ie !c \(dg \{\ .char \(dg * .de DG an asterick .. .\} .el \{\ .de DG a dagger .. .\} .\" .\" Define \(dd as "#" for text output and create a new .DD macro .\" which describes the symbol. .\" .ie !c \(dd \{\ .char \(dd # .de DD a pound sign .. .\} .el \{\ .de DD a double dagger .. .\} .eh 'SMM:08-%''Sendmail Installation and Operation Guide' .oh 'Sendmail Installation and Operation Guide''SMM:08-%' .\" SD is lib if sendmail is installed in /usr/lib, sbin if in /usr/sbin .ds SD sbin .\" SB is bin if newaliases/mailq are installed in /usr/bin, ucb if in /usr/ucb .ds SB bin .nr si 3n .de $0 .(x .in \\$3u*3n .ti -3n \\$2. \\$1 .)x .. .de $C .(x .in 0 \\$1 \\$2. \\$3 .)x .. .+c .(l C .sz 16 .b SENDMAIL\u\s-6TM\s0\d .sz 12 .sp .b "INSTALLATION AND OPERATION GUIDE" .(f .b DISCLAIMER: This documentation is under modification. .)f .sz 10 .sp .r Eric Allman Claus Assmann Gregory Neil Shapiro Sendmail, Inc. .sp .de Ve Version \\$2 .. -.Ve $Revision: 8.749 $ +.Ve $Revision: 8.751 $ .rm Ve .sp For Sendmail Version 8.14 .)l .(f Sendmail is a trademark of Sendmail, Inc. US Patent Numbers 6865671, 6986037. .)f .sp 2 .pp .i Sendmail \u\s-2TM\s0\d implements a general purpose internetwork mail routing facility under the UNIX\(rg operating system. It is not tied to any one transport protocol \*- its function may be likened to a crossbar switch, relaying messages from one domain into another. In the process, it can do a limited amount of message header editing to put the message into a format that is appropriate for the receiving domain. All of this is done under the control of a configuration file. .pp Due to the requirements of flexibility for .i sendmail , the configuration file can seem somewhat unapproachable. However, there are only a few basic configurations for most sites, for which standard configuration files have been supplied. Most other configurations can be built by adjusting an existing configuration file incrementally. .pp .i Sendmail is based on RFC 821 (Simple Mail Transport Protocol), RFC 822 (Internet Mail Headers Format), RFC 974 (MX routing), RFC 1123 (Internet Host Requirements), RFC 1413 (Identification server), RFC 1652 (SMTP 8BITMIME Extension), RFC 1869 (SMTP Service Extensions), RFC 1870 (SMTP SIZE Extension), RFC 1891 (SMTP Delivery Status Notifications), RFC 1892 (Multipart/Report), RFC 1893 (Enhanced Mail System Status Codes), RFC 1894 (Delivery Status Notifications), RFC 1985 (SMTP Service Extension for Remote Message Queue Starting), RFC 2033 (Local Message Transmission Protocol), RFC 2034 (SMTP Service Extension for Returning Enhanced Error Codes), RFC 2045 (MIME), RFC 2476 (Message Submission), RFC 2487 (SMTP Service Extension for Secure SMTP over TLS), RFC 2554 (SMTP Service Extension for Authentication), RFC 2821 (Simple Mail Transfer Protocol), RFC 2822 (Internet Message Format), RFC 2852 (Deliver By SMTP Service Extension), and RFC 2920 (SMTP Service Extension for Command Pipelining). However, since .i sendmail is designed to work in a wider world, in many cases it can be configured to exceed these protocols. These cases are described herein. .pp Although .i sendmail is intended to run without the need for monitoring, it has a number of features that may be used to monitor or adjust the operation under unusual circumstances. These features are described. .pp Section one describes how to do a basic .i sendmail installation. Section two explains the day-to-day information you should know to maintain your mail system. If you have a relatively normal site, these two sections should contain sufficient information for you to install .i sendmail and keep it happy. Section three has information regarding the command line arguments. Section four describes some parameters that may be safely tweaked. Section five contains the nitty-gritty information about the configuration file. This section is for masochists and people who must write their own configuration file. Section six describes configuration that can be done at compile time. The appendixes give a brief but detailed explanation of a number of features not described in the rest of the paper. .bp 7 .sh 1 "BASIC INSTALLATION" .pp There are two basic steps to installing .i sendmail . First, you have to compile and install the binary. If .i sendmail has already been ported to your operating system that should be simple. Second, you must build a run-time configuration file. This is a file that .i sendmail reads when it starts up that describes the mailers it knows about, how to parse addresses, how to rewrite the message header, and the settings of various options. Although the configuration file can be quite complex, a configuration can usually be built using an M4-based configuration language. Assuming you have the standard .i sendmail distribution, see .i cf/README for further information. .pp The remainder of this section will describe the installation of .i sendmail assuming you can use one of the existing configurations and that the standard installation parameters are acceptable. All pathnames and examples are given from the root of the .i sendmail subtree, normally .i /usr/src/usr.\*(SD/sendmail on 4.4BSD-based systems. .pp Continue with the next section if you need/want to compile .i sendmail yourself. If you have a running binary already on your system, you should probably skip to section 1.2. .sh 2 "Compiling Sendmail" .pp All .i sendmail source is in the .i sendmail subdirectory. To compile sendmail, .q cd into the .i sendmail directory and type .(b \&./Build .)b This will leave the binary in an appropriately named subdirectory, e.g., obj.BSD-OS.2.1.i386. It works for multiple object versions compiled out of the same directory. .sh 3 "Tweaking the Build Invocation" .pp You can give parameters on the .i Build command. In most cases these are only used when the .i obj.* directory is first created. To restart from scratch, use .i -c . These commands include: .nr ii 0.5i .ip "\-L \fIlibdirs\fP" A list of directories to search for libraries. .ip "\-I \fIincdirs\fP" A list of directories to search for include files. .ip "\-E \fIenvar\fP=\fIvalue\fP" Set an environment variable to an indicated .i value before compiling. .ip "\-c" Create a new .i obj.* tree before running. .ip "\-f \fIsiteconfig\fP" Read the indicated site configuration file. If this parameter is not specified, .i Build includes .i all of the files .i $BUILDTOOLS/Site/site.$oscf.m4 and .i $BUILDTOOLS/Site/site.config.m4 , where $BUILDTOOLS is normally .i \&../devtools and $oscf is the same name as used on the .i obj.* directory. See below for a description of the site configuration file. .ip "\-S" Skip auto-configuration. .i Build will avoid auto-detecting libraries if this is set. All libraries and map definitions must be specified in the site configuration file. .lp Most other parameters are passed to the .i make program; for details see .i $BUILDTOOLS/README . .sh 3 "Creating a Site Configuration File" .\"XXX .pp (This section is not yet complete. For now, see the file devtools/README for details.) See sendmail/README for various compilation flags that can be set. .sh 3 "Tweaking the Makefile" .pp .\" .b "XXX This should all be in the Site Configuration File section." .i Sendmail supports two different formats for the local (on disk) version of databases, notably the .i aliases database. At least one of these should be defined if at all possible. .nr ii 1i .ip NDBM The ``new DBM'' format, available on nearly all systems around today. This was the preferred format prior to 4.4BSD. It allows such complex things as multiple databases and closing a currently open database. .ip NEWDB The Berkeley DB package. If you have this, use it. It allows long records, multiple open databases, real in-memory caching, and so forth. You can define this in conjunction with .sm NDBM ; if you do, old alias databases are read, but when a new database is created it will be in NEWDB format. As a nasty hack, if you have NEWDB, NDBM, and NIS defined, and if the alias file name includes the substring .q /yp/ , .i sendmail will create both new and old versions of the alias file during a .i newalias command. This is required because the Sun NIS/YP system reads the DBM version of the alias file. It's ugly as sin, but it works. .lp If neither of these are defined, .i sendmail reads the alias file into memory on every invocation. This can be slow and should be avoided. There are also several methods for remote database access: .ip LDAP Lightweight Directory Access Protocol. .ip NIS Sun's Network Information Services (formerly YP). .ip NISPLUS Sun's NIS+ services. .ip NETINFO NeXT's NetInfo service. .ip HESIOD Hesiod service (from Athena). .lp Other compilation flags are set in .i conf.h and should be predefined for you unless you are porting to a new environment. For more options see .i sendmail/README . .sh 3 "Compilation and installation" .pp After making the local system configuration described above, You should be able to compile and install the system. The script .q Build is the best approach on most systems: .(b \&./Build .)b This will use .i uname (1) to create a custom Makefile for your environment. .pp If you are installing in the standard places, you should be able to install using .(b \&./Build install .)b This should install the binary in /usr/\*(SD and create links from /usr/\*(SB/newaliases and /usr/\*(SB/mailq to /usr/\*(SD/sendmail. On most systems it will also format and install man pages. Notice: as of version 8.12 .i sendmail will no longer be installed set-user-ID root by default. If you really want to use the old method, you can specify it as target: .(b \&./Build install-set-user-id .)b .sh 2 "Configuration Files" .pp .i Sendmail cannot operate without a configuration file. The configuration defines the mail delivery mechanisms understood at this site, how to access them, how to forward email to remote mail systems, and a number of tuning parameters. This configuration file is detailed in the later portion of this document. .pp The .i sendmail configuration can be daunting at first. The world is complex, and the mail configuration reflects that. The distribution includes an m4-based configuration package that hides a lot of the complexity. See .i cf/README for details. .pp Our configuration files are processed by .i m4 to facilitate local customization; the directory .i cf of the .i sendmail distribution directory contains the source files. This directory contains several subdirectories: .nr ii 1i .ip cf Both site-dependent and site-independent descriptions of hosts. These can be literal host names (e.g., .q ucbvax.mc ) when the hosts are gateways or more general descriptions (such as .q "generic-solaris2.mc" as a general description of an SMTP-connected host running Solaris 2.x. Files ending .b \&.mc (``M4 Configuration'') are the input descriptions; the output is in the corresponding .b \&.cf file. The general structure of these files is described below. .ip domain Site-dependent subdomain descriptions. These are tied to the way your organization wants to do addressing. For example, .b domain/CS.Berkeley.EDU.m4 is our description for hosts in the CS.Berkeley.EDU subdomain. These are referenced using the .sm DOMAIN .b m4 macro in the .b \&.mc file. .ip feature Definitions of specific features that some particular host in your site might want. These are referenced using the .sm FEATURE .b m4 macro. An example feature is use_cw_file (which tells .i sendmail to read an /etc/mail/local-host-names file on startup to find the set of local names). .ip hack Local hacks, referenced using the .sm HACK .b m4 macro. Try to avoid these. The point of having them here is to make it clear that they smell. .ip m4 Site-independent .i m4 (1) include files that have information common to all configuration files. This can be thought of as a .q #include directory. .ip mailer Definitions of mailers, referenced using the .sm MAILER .b m4 macro. The mailer types that are known in this distribution are fax, local, smtp, uucp, and usenet. For example, to include support for the UUCP-based mailers, use .q MAILER(uucp) . .ip ostype Definitions describing various operating system environments (such as the location of support files). These are referenced using the .sm OSTYPE .b m4 macro. .ip sh Shell files used by the .b m4 build process. You shouldn't have to mess with these. .ip siteconfig Local UUCP connectivity information. This directory has been supplanted by the mailertable feature; any new configurations should use that feature to do UUCP (and other) routing. The use of this directory is deprecated. .pp If you are in a new domain (e.g., a company), you will probably want to create a cf/domain file for your domain. This consists primarily of relay definitions and features you want enabled site-wide: for example, Berkeley's domain definition defines relays for BitNET and UUCP. These are specific to Berkeley, and should be fully-qualified internet-style domain names. Please check to make certain they are reasonable for your domain. .pp Subdomains at Berkeley are also represented in the cf/domain directory. For example, the domain CS.Berkeley.EDU is the Computer Science subdomain, EECS.Berkeley.EDU is the Electrical Engineering and Computer Sciences subdomain, and S2K.Berkeley.EDU is the Sequoia 2000 subdomain. You will probably have to add an entry to this directory to be appropriate for your domain. .pp You will have to use or create .b \&.mc files in the .i cf/cf subdirectory for your hosts. This is detailed in the cf/README file. .sh 2 "Details of Installation Files" .pp This subsection describes the files that comprise the .i sendmail installation. .sh 3 "/usr/\*(SD/sendmail" .pp The binary for .i sendmail is located in /usr/\*(SD\**. .(f \**This is usually /usr/sbin on 4.4BSD and newer systems; many systems install it in /usr/lib. I understand it is in /usr/ucblib on System V Release 4. .)f It should be set-group-ID smmsp as described in sendmail/SECURITY. For security reasons, /, /usr, and /usr/\*(SD should be owned by root, mode 0755\**. .(f \**Some vendors ship them owned by bin; this creates a security hole that is not actually related to .i sendmail . Other important directories that should have restrictive ownerships and permissions are /bin, /usr/bin, /etc, /etc/mail, /usr/etc, /lib, and /usr/lib. .)f .sh 3 "/etc/mail/sendmail.cf" .pp This is the main configuration file for .i sendmail \**. .(f \**Actually, the pathname varies depending on the operating system; /etc/mail is the preferred directory. Some older systems install it in .b /usr/lib/sendmail.cf , and I've also seen it in .b /usr/ucblib . If you want to move this file, add -D_PATH_SENDMAILCF=\e"/file/name\e" to the flags passed to the C compiler. Moving this file is not recommended: other programs and scripts know of this location. .)f This is one of the two non-library file names compiled into .i sendmail \**, the other is /etc/mail/submit.cf. .(f \**The system libraries can reference other files; in particular, system library subroutines that .i sendmail calls probably reference .i /etc/passwd and .i /etc/resolv.conf . .)f .pp The configuration file is normally created using the distribution files described above. If you have a particularly unusual system configuration you may need to create a special version. The format of this file is detailed in later sections of this document. .sh 3 "/etc/mail/submit.cf" .pp This is the configuration file for .i sendmail when it is used for initial mail submission, in which case it is also called ``Mail Submission Program'' (MSP) in contrast to ``Mail Transfer Agent'' (MTA). Starting with version 8.12, .i sendmail uses one of two different configuration files based on its operation mode (or the new .b \-A option). For initial mail submission, i.e., if one of the options .b \-bm (default), .b \-bs , or .b \-t is specified, submit.cf is used (if available), for other operations sendmail.cf is used. Details can be found in .i sendmail/SECURITY . submit.cf is shipped with sendmail (in cf/cf/) and is installed by default. If changes to the configuration need to be made, start with cf/cf/submit.mc and follow the instruction in cf/README. .sh 3 "/usr/\*(SB/newaliases" .pp The .i newaliases command should just be a link to .i sendmail : .(b rm \-f /usr/\*(SB/newaliases ln \-s /usr/\*(SD/sendmail /usr/\*(SB/newaliases .)b This can be installed in whatever search path you prefer for your system. .sh 3 "/usr/\*(SB/hoststat" .pp The .i hoststat command should just be a link to .i sendmail , in a fashion similar to .i newaliases . This command lists the status of the last mail transaction with all remote hosts. The .b \-v flag will prevent the status display from being truncated. It functions only when the .b HostStatusDirectory option is set. .sh 3 "/usr/\*(SB/purgestat" .pp This command is also a link to .i sendmail . It flushes expired (Timeout.hoststatus) information that is stored in the .b HostStatusDirectory tree. .sh 3 "/var/spool/mqueue" .pp The directory .i /var/spool/mqueue should be created to hold the mail queue. This directory should be mode 0700 and owned by root. .pp The actual path of this directory is defined by the .b QueueDirectory option of the .i sendmail.cf file. To use multiple queues, supply a value ending with an asterisk. For example, .i /var/spool/mqueue/qd* will use all of the directories or symbolic links to directories beginning with `qd' in .i /var/spool/mqueue as queue directories. Do not change the queue directory structure while sendmail is running. .pp If these directories have subdirectories or symbolic links to directories named `qf', `df', and `xf', then these will be used for the different queue file types. That is, the data files are stored in the `df' subdirectory, the transcript files are stored in the `xf' subdirectory, and all others are stored in the `qf' subdirectory. .pp If shared memory support is compiled in, .i sendmail stores the available diskspace in a shared memory segment to make the values readily available to all children without incurring system overhead. In this case, only the daemon updates the data; i.e., the sendmail daemon creates the shared memory segment and deletes it if it is terminated. To use this, .i sendmail must have been compiled with support for shared memory (-DSM_CONF_SHM) and the option .b SharedMemoryKey must be set. Notice: do not use the same key for .i sendmail invocations with different queue directories or different queue group declarations. Access to shared memory is not controlled by locks, i.e., there is a race condition when data in the shared memory is updated. However, since operation of .i sendmail does not rely on the data in the shared memory, this does not negatively influence the behavior. .sh 3 "/var/spool/clientmqueue" .pp The directory .i /var/spool/clientmqueue should be created to hold the mail queue. This directory should be mode 0770 and owned by user smmsp, group smmsp. .pp The actual path of this directory is defined by the .b QueueDirectory option of the .i submit.cf file. .sh 3 "/var/spool/mqueue/.hoststat" .pp This is a typical value for the .b HostStatusDirectory option, containing one file per host that this sendmail has chatted with recently. It is normally a subdirectory of .i mqueue . .sh 3 "/etc/mail/aliases*" .pp The system aliases are held in .q /etc/mail/aliases . A sample is given in .q sendmail/aliases which includes some aliases which .i must be defined: .(b cp sendmail/aliases /etc/mail/aliases .i "edit /etc/mail/aliases" .)b You should extend this file with any aliases that are apropos to your system. .pp Normally .i sendmail looks at a database version of the files, stored either in .q /etc/mail/aliases.dir and .q /etc/mail/aliases.pag or .q /etc/mail/aliases.db depending on which database package you are using. The actual path of this file is defined in the .b AliasFile option of the .i sendmail.cf file. .pp The permissions of the alias file and the database versions should be 0640 to prevent local denial of service attacks as explained in the top level .b README in the sendmail distribution. If the permissions 0640 are used, be sure that only trusted users belong to the group assigned to those files. Otherwise, files should not even be group readable. .sh 3 "/etc/rc or /etc/init.d/sendmail" .pp It will be necessary to start up the .i sendmail daemon when your system reboots. This daemon performs two functions: it listens on the SMTP socket for connections (to receive mail from a remote system) and it processes the queue periodically to insure that mail gets delivered when hosts come up. .pp If necessary, add the following lines to .q /etc/rc (or .q /etc/rc.local as appropriate) in the area where it is starting up the daemons on a BSD-base system, or on a System-V-based system in one of the startup files, typically .q /etc/init.d/sendmail : .(b if [ \-f /usr/\*(SD/sendmail \-a \-f /etc/mail/sendmail.cf ]; then (cd /var/spool/mqueue; rm \-f xf*) /usr/\*(SD/sendmail \-bd \-q30m & echo \-n ' sendmail' >/dev/console fi .)b The .q cd and .q rm commands insure that all transcript files have been removed; extraneous transcript files may be left around if the system goes down in the middle of processing a message. The line that actually invokes .i sendmail has two flags: .q \-bd causes it to listen on the SMTP port, and .q \-q30m causes it to run the queue every half hour. .pp Some people use a more complex startup script, removing zero length qf/hf/Qf files and df files for which there is no qf/hf/Qf file. Note this is not advisable. For example, see Figure 1 for an example of a complex script which does this clean up. .(z .hl #!/bin/sh # remove zero length qf/hf/Qf files for qffile in qf* hf* Qf* do if [ \-r $qffile ] then if [ ! \-s $qffile ] then echo \-n " " > /dev/console rm \-f $qffile fi fi done # rename tf files to be qf if the qf does not exist for tffile in tf* do qffile=`echo $tffile | sed 's/t/q/'` if [ \-r $tffile \-a ! \-f $qffile ] then echo \-n " " > /dev/console mv $tffile $qffile else if [ \-f $tffile ] then echo \-n " " > /dev/console rm \-f $tffile fi fi done # remove df files with no corresponding qf/hf/Qf files for dffile in df* do qffile=`echo $dffile | sed 's/d/q/'` hffile=`echo $dffile | sed 's/d/h/'` Qffile=`echo $dffile | sed 's/d/Q/'` if [ \-r $dffile \-a ! \-f $qffile \-a ! \-f $hffile \-a ! \-f $Qffile ] then echo \-n " " > /dev/console mv $dffile `echo $dffile | sed 's/d/D/'` fi done # announce files that have been saved during disaster recovery for xffile in [A-Z]f* do if [ \-f $xffile ] then echo \-n " " > /dev/console fi done .sp .ce Figure 1 \(em A complex startup script .hl .)z .sh 3 "/etc/mail/helpfile" .pp This is the help file used by the SMTP .b HELP command. It should be copied from .q sendmail/helpfile : .(b cp sendmail/helpfile /etc/mail/helpfile .)b The actual path of this file is defined in the .b HelpFile option of the .i sendmail.cf file. .sh 3 "/etc/mail/statistics" .pp If you wish to collect statistics about your mail traffic, you should create the file .q /etc/mail/statistics : .(b cp /dev/null /etc/mail/statistics chmod 0600 /etc/mail/statistics .)b This file does not grow. It is printed with the program .q mailstats/mailstats.c. The actual path of this file is defined in the .b S option of the .i sendmail.cf file. .sh 3 "/usr/\*(SB/mailq" .pp If .i sendmail is invoked as .q mailq, it will simulate the .b \-bp flag (i.e., .i sendmail will print the contents of the mail queue; see below). This should be a link to /usr/\*(SD/sendmail. .sh 3 "sendmail.pid" .pp .i sendmail stores its current pid in the file specified by the .b PidFile option (default is _PATH_SENDMAILPID). .i sendmail uses .b TempFileMode (which defaults to 0600) as the permissions of that file to prevent local denial of service attacks as explained in the top level .b README in the sendmail distribution. If the file already exists, then it might be necessary to change the permissions accordingly, e.g., .(b chmod 0600 /var/run/sendmail.pid .)b Note that as of version 8.13, this file is unlinked when .i sendmail exits. As a result of this change, a script such as the following, which may have worked prior to 8.13, will no longer work: .(b # stop & start sendmail PIDFILE=/var/run/sendmail.pid kill `head -1 $PIDFILE` `tail -1 $PIDFILE` .)b because it assumes that the pidfile will still exist even after killing the process to which it refers. Below is a script which will work correctly on both newer and older versions: .(b # stop & start sendmail PIDFILE=/var/run/sendmail.pid pid=`head -1 $PIDFILE` cmd=`tail -1 $PIDFILE` kill $pid $cmd .)b This is just an example script, it does not perform any error checks, e.g., whether the pidfile exists at all. .sh 3 "Map Files" .pp To prevent local denial of service attacks as explained in the top level .b README in the sendmail distribution, the permissions of map files created by .i makemap should be 0640. The use of 0640 implies that only trusted users belong to the group assigned to those files. If those files already exist, then it might be necessary to change the permissions accordingly, e.g., .(b cd /etc/mail chmod 0640 *.db *.pag *.dir .)b .sh 1 "NORMAL OPERATIONS" .sh 2 "The System Log" .pp The system log is supported by the .i syslogd \|(8) program. All messages from .i sendmail are logged under the .sm LOG_MAIL facility\**. .(f \**Except on Ultrix, which does not support facilities in the syslog. .)f .sh 3 "Format" .pp Each line in the system log consists of a timestamp, the name of the machine that generated it (for logging from several machines over the local area network), the word .q sendmail: , and a message\**. .(f \**This format may vary slightly if your vendor has changed the syntax. .)f Most messages are a sequence of .i name \c =\c .i value pairs. .pp The two most common lines are logged when a message is processed. The first logs the receipt of a message; there will be exactly one of these per message. Some fields may be omitted if they do not contain interesting information. Fields are: .ip from The envelope sender address. .ip size The size of the message in bytes. .ip class The class (i.e., numeric precedence) of the message. .ip pri The initial message priority (used for queue sorting). .ip nrcpts The number of envelope recipients for this message (after aliasing and forwarding). .ip msgid The message id of the message (from the header). .ip bodytype The message body type (7BIT or 8BITMIME), as determined from the envelope. .ip proto The protocol used to receive this message (e.g., ESMTP or UUCP) .ip daemon The daemon name from the .b DaemonPortOptions setting. .ip relay The machine from which it was received. .lp There is also one line logged per delivery attempt (so there can be several per message if delivery is deferred or there are multiple recipients). Fields are: .ip to A comma-separated list of the recipients to this mailer. .ip ctladdr The ``controlling user'', that is, the name of the user whose credentials we use for delivery. .ip delay The total delay between the time this message was received and the current delivery attempt. .ip xdelay The amount of time needed in this delivery attempt (normally indicative of the speed of the connection). .ip mailer The name of the mailer used to deliver to this recipient. .ip relay The name of the host that actually accepted (or rejected) this recipient. .ip dsn The enhanced error code (RFC 2034) if available. .ip stat The delivery status. .lp Not all fields are present in all messages; for example, the relay is usually not listed for local deliveries. .sh 3 "Levels" .pp If you have .i syslogd \|(8) or an equivalent installed, you will be able to do logging. There is a large amount of information that can be logged. The log is arranged as a succession of levels. At the lowest level only extremely strange situations are logged. At the highest level, even the most mundane and uninteresting events are recorded for posterity. As a convention, log levels under ten are considered generally .q useful; log levels above 64 are reserved for debugging purposes. Levels from 11\-64 are reserved for verbose information that some sites might want. .pp A complete description of the log levels is given in section ``Log Level''. .sh 2 "Dumping State" .pp You can ask .i sendmail to log a dump of the open files and the connection cache by sending it a .sm SIGUSR1 signal. The results are logged at .sm LOG_DEBUG priority. .sh 2 "The Mail Queues" .pp Mail messages may either be delivered immediately or be held for later delivery. Held messages are placed into a holding directory called a mail queue. .pp A mail message may be queued for these reasons: .bu If a mail message is temporarily undeliverable, it is queued and delivery is attempted later. If the message is addressed to multiple recipients, it is queued only for those recipients to whom delivery is not immediately possible. .bu If the SuperSafe option is set to true, all mail messages are queued while delivery is attempted. .bu If the DeliveryMode option is set to queue-only or defer, all mail is queued, and no immediate delivery is attempted. .bu If the load average becomes higher than the value of the QueueLA option and the .b QueueFactor (\c .b q ) option divided by the difference in the current load average and the .b QueueLA option plus one is less than the priority of the message, messages are queued rather than immediately delivered. .bu One or more addresses are marked as expensive and delivery is postponed until the next queue run or one or more address are marked as held via mailer which uses the hold mailer flag. .bu The mail message has been marked as quarantined via a mail filter or rulesets. .bu .sh 3 "Queue Groups and Queue Directories" .pp There are one or more mail queues. Each mail queue belongs to a queue group. There is always a default queue group that is called ``mqueue'' (which is where messages go by default unless otherwise specified). The directory or directories which comprise the default queue group are specified by the QueueDirectory option. There are zero or more additional named queue groups declared using the .b Q command in the configuration file. .pp By default, a queued message is placed in the queue group associated with the first recipient in the recipient list. A recipient address is mapped to a queue group as follows. First, if there is a ruleset called ``queuegroup'', and if this ruleset maps the address to a queue group name, then that queue group is chosen. That is, the argument for the ruleset is the recipient address and the result should be .b $# followed by the name of a queue group. Otherwise, if the mailer associated with the address specifies a queue group, then that queue group is chosen. Otherwise, the default queue group is chosen. .pp A message with multiple recipients will be split if different queue groups are chosen by the mapping of recipients to queue groups. .pp When a message is placed in a queue group, and the queue group has more than one queue, a queue is selected randomly. .pp If a message with multiple recipients is placed into a queue group with the 'r' option (maximum number of recipients per message) set to a positive value .i N , and if there are more than .i N recipients in the message, then the message will be split into multiple messages, each of which have at most .i N recipients. .pp Notice: if multiple queue groups are used, do .b not move queue files around, e.g., into a different queue directory. This may have weird effects and can cause mail not to be delivered. Queue files and directories should be treated as opaque and should not be manipulated directly. .sh 3 "Queue Runs" .pp .i sendmail has two different ways to process the queue(s). The first one is to start queue runners after certain intervals (``normal'' queue runners), the second one is to keep queue runner processes around (``persistent'' queue runners). How to select either of these types is discussed in the appendix ``COMMAND LINE FLAGS''. Persistent queue runners have the advantage that no new processes need to be spawned at certain intervals; they just sleep for a specified time after they finished a queue run. Another advantage of persistent queue runners is that only one process belonging to a workgroup (a workgroup is a set of queue groups) collects the data for a queue run and then multiple queue runner may go ahead using that data. This can significantly reduce the disk I/O necessary to read the queue files compared to starting multiple queue runners directly. Their disadvantage is that a new queue run is only started after all queue runners belonging to a group finished their tasks. In case one of the queue runners tries delivery to a slow recipient site at the end of a queue run, the next queue run may be substantially delayed. In general this should be smoothed out due to the distribution of those slow jobs, however, for sites with small number of queue entries this might introduce noticable delays. In general, persistent queue runners are only useful for sites with big queues. .sh 3 "Manual Intervention" .pp Under normal conditions the mail queue will be processed transparently. However, you may find that manual intervention is sometimes necessary. For example, if a major host is down for a period of time the queue may become clogged. Although .i sendmail ought to recover gracefully when the host comes up, you may find performance unacceptably bad in the meantime. In that case you want to check the content of the queue and manipulate it as explained in the next two sections. .sh 3 "Printing the queue" .pp The contents of the queue(s) can be printed using the .i mailq command (or by specifying the .b \-bp flag to .i sendmail ): .(b mailq .)b This will produce a listing of the queue id's, the size of the message, the date the message entered the queue, and the sender and recipients. If shared memory support is compiled in, the flag .b \-bP can be used to print the number of entries in the queue(s), provided a process updates the data. However, as explained earlier, the output might be slightly wrong, since access to the shared memory is not locked. For example, ``unknown number of entries'' might be shown. The internal counters are updated after each queue run to the correct value again. .sh 3 "Forcing the queue" .pp .i Sendmail should run the queue automatically at intervals. When using multiple queues, a separate process will by default be created to run each of the queues unless the queue run is initiated by a user with the verbose flag. The algorithm is to read and sort the queue, and then to attempt to process all jobs in order. When it attempts to run the job, .i sendmail first checks to see if the job is locked. If so, it ignores the job. .pp There is no attempt to insure that only one queue processor exists at any time, since there is no guarantee that a job cannot take forever to process (however, .i sendmail does include heuristics to try to abort jobs that are taking absurd amounts of time; technically, this violates RFC 821, but is blessed by RFC 1123). Due to the locking algorithm, it is impossible for one job to freeze the entire queue. However, an uncooperative recipient host or a program recipient that never returns can accumulate many processes in your system. Unfortunately, there is no completely general way to solve this. .pp In some cases, you may find that a major host going down for a couple of days may create a prohibitively large queue. This will result in .i sendmail spending an inordinate amount of time sorting the queue. This situation can be fixed by moving the queue to a temporary place and creating a new queue. The old queue can be run later when the offending host returns to service. .pp To do this, it is acceptable to move the entire queue directory: .(b cd /var/spool mv mqueue omqueue; mkdir mqueue; chmod 0700 mqueue .)b You should then kill the existing daemon (since it will still be processing in the old queue directory) and create a new daemon. .pp To run the old mail queue, issue the following command: .(b /usr/\*(SD/sendmail \-C /etc/mail/queue.cf \-q .)b The .b \-C flag specifies an alternate configuration file .b queue.cf which should refer to the moved queue directory .(b O QueueDirectory=/var/spool/omqueue .)b and the .b \-q flag says to just run every job in the queue. You can also specify the moved queue directory on the command line .(b /usr/\*(SD/sendmail \-oQ/var/spool/omqueue \-q .)b but this requires that you do not have queue groups in the configuration file, because those are not subdirectories of the moved directory. See the section about ``Queue Group Declaration'' for details; you most likely need a different configuration file to correctly deal with this problem. However, a proper configuration of queue groups should avoid filling up queue directories, so you shouldn't run into this problem. If you have a tendency toward voyeurism, you can use the .b \-v flag to watch what is going on. .pp When the queue is finally emptied, you can remove the directory: .(b rmdir /var/spool/omqueue .)b .sh 3 "Quarantined Queue Items" .pp It is possible to "quarantine" mail messages, otherwise known as envelopes. Envelopes (queue files) are stored but not considered for delivery or display unless the "quarantine" state of the envelope is undone or delivery or display of quarantined items is requested. Quarantined messages are tagged by using a different name for the queue file, 'hf' instead of 'qf', and by adding the quarantine reason to the queue file. .pp Delivery or display of quarantined items can be requested using the .b \-qQ flag to .i sendmail or .i mailq . Additionally, messages already in the queue can be quarantined or unquarantined using the new .b \-Q flag to sendmail. For example, .(b sendmail -Qreason -q[!][I|R|S][matchstring] .)b Quarantines the normal queue items matching the criteria specified by the .b "-q[!][I|R|S][matchstring]" using the reason given on the .b \-Q flag. Likewise, .(b sendmail -qQ -Q[reason] -q[!][I|R|S|Q][matchstring] .)b Change the quarantine reason for the quarantined items matching the criteria specified by the .b "-q[!][I|R|S|Q][matchstring]" using the reason given on the .b \-Q flag. If there is no reason, unquarantine the matching items and make them normal queue items. Note that the .b \-qQ flag tells sendmail to operate on quarantined items instead of normal items. .sh 2 "Disk Based Connection Information" .pp .i Sendmail stores a large amount of information about each remote system it has connected to in memory. It is possible to preserve some of this information on disk as well, by using the .b HostStatusDirectory option, so that it may be shared between several invocations of .i sendmail . This allows mail to be queued immediately or skipped during a queue run if there has been a recent failure in connecting to a remote machine. Note: information about a remote system is stored in a file whose pathname consists of the components of the hostname in reverse order. For example, the information for .b host.example.com is stored in .b com./example./host . For top-level domains like .b com this can create a large number of subdirectories which on some filesystems can exhaust some limits. Moreover, the performance of lookups in directory with thousands of entries can be fairly slow depending on the filesystem implementation. .pp Additionally enabling .b SingleThreadDelivery has the added effect of single-threading mail delivery to a destination. This can be quite helpful if the remote machine is running an SMTP server that is easily overloaded or cannot accept more than a single connection at a time, but can cause some messages to be punted to a future queue run. It also applies to .i all hosts, so setting this because you have one machine on site that runs some software that is easily overrun can cause mail to other hosts to be slowed down. If this option is set, you probably want to set the .b MinQueueAge option as well and run the queue fairly frequently; this way jobs that are skipped because another .i sendmail is talking to the same host will be tried again quickly rather than being delayed for a long time. .pp The disk based host information is stored in a subdirectory of the .b mqueue directory called .b \&.hoststat \**. .(f \**This is the usual value of the .b HostStatusDirectory option; it can, of course, go anywhere you like in your filesystem. .)f Removing this directory and its subdirectories has an effect similar to the .i purgestat command and is completely safe. However, .i purgestat only removes expired (Timeout.hoststatus) data. The information in these directories can be perused with the .i hoststat command, which will indicate the host name, the last access, and the status of that access. An asterisk in the left most column indicates that a .i sendmail process currently has the host locked for mail delivery. .pp The disk based connection information is treated the same way as memory based connection information for the purpose of timeouts. By default, information about host failures is valid for 30 minutes. This can be adjusted with the .b Timeout.hoststatus option. .pp The connection information stored on disk may be expired at any time with the .i purgestat command or by invoking sendmail with the .b \-bH switch. The connection information may be viewed with the .i hoststat command or by invoking sendmail with the .b \-bh switch. .sh 2 "The Service Switch" .pp The implementation of certain system services such as host and user name lookup is controlled by the service switch. If the host operating system supports such a switch, and sendmail knows about it, .i sendmail will use the native version. Ultrix, Solaris, and DEC OSF/1 are examples of such systems\**. .(f \**HP-UX 10 has service switch support, but since the APIs are apparently not available in the libraries .i sendmail does not use the native service switch in this release. .)f .pp If the underlying operating system does not support a service switch (e.g., SunOS 4.X, HP-UX, BSD) then .i sendmail will provide a stub implementation. The .b ServiceSwitchFile option points to the name of a file that has the service definitions. Each line has the name of a service and the possible implementations of that service. For example, the file: .(b hosts dns files nis aliases files nis .)b will ask .i sendmail to look for hosts in the Domain Name System first. If the requested host name is not found, it tries local files, and if that fails it tries NIS. Similarly, when looking for aliases it will try the local files first followed by NIS. .pp Notice: since .i sendmail must access MX records for correct operation, it will use DNS if it is configured in the .b ServiceSwitchFile file. Hence an entry like .(b hosts files dns .)b will not avoid DNS lookups even if a host can be found in /etc/hosts. .pp Service switches are not completely integrated. For example, despite the fact that the host entry listed in the above example specifies to look in NIS, on SunOS this won't happen because the system implementation of .i gethostbyname \|(3) doesn't understand this. .sh 2 "The Alias Database" .pp After recipient addresses are read from the SMTP connection or command line they are parsed by ruleset 0, which must resolve to a {\c .i mailer , .i host , .i address } triple. If the flags selected by the .i mailer include the .b A (aliasable) flag, the .i address part of the triple is looked up as the key (i.e., the left hand side) in the alias database. If there is a match, the address is deleted from the send queue and all addresses on the right hand side of the alias are added in place of the alias that was found. This is a recursive operation, so aliases found in the right hand side of the alias are similarly expanded. .pp The alias database exists in two forms. One is a text form, maintained in the file .i /etc/mail/aliases. The aliases are of the form .(b name: name1, name2, ... .)b Only local names may be aliased; e.g., .(b eric@prep.ai.MIT.EDU: eric@CS.Berkeley.EDU .)b will not have the desired effect (except on prep.ai.MIT.EDU, and they probably don't want me)\**. .(f \**Actually, any mailer that has the `A' mailer flag set will permit aliasing; this is normally limited to the local mailer. .)f Aliases may be continued by starting any continuation lines with a space or a tab or by putting a backslash directly before the newline. Blank lines and lines beginning with a sharp sign (\c .q # ) are comments. .pp The second form is processed by the .i ndbm \|(3)\** .(f \**The .i gdbm package does not work. .)f or the Berkeley DB library. This form is in the file .i /etc/mail/aliases.db (if using NEWDB) or .i /etc/mail/aliases.dir and .i /etc/mail/aliases.pag (if using NDBM). This is the form that .i sendmail actually uses to resolve aliases. This technique is used to improve performance. .pp The control of search order is actually set by the service switch. Essentially, the entry .(b O AliasFile=switch:aliases .)b is always added as the first alias entry; also, the first alias file name without a class (e.g., without .q nis: on the front) will be used as the name of the file for a ``files'' entry in the aliases switch. For example, if the configuration file contains .(b O AliasFile=/etc/mail/aliases .)b and the service switch contains .(b aliases nis files nisplus .)b then aliases will first be searched in the NIS database, then in /etc/mail/aliases, then in the NIS+ database. .pp You can also use .sm NIS -based alias files. For example, the specification: .(b O AliasFile=/etc/mail/aliases O AliasFile=nis:mail.aliases@my.nis.domain .)b will first search the /etc/mail/aliases file and then the map named .q mail.aliases in .q my.nis.domain . Warning: if you build your own .sm NIS -based alias files, be sure to provide the .b \-l flag to .i makedbm (8) to map upper case letters in the keys to lower case; otherwise, aliases with upper case letters in their names won't match incoming addresses. .pp Additional flags can be added after the colon exactly like a .b K line \(em for example: .(b O AliasFile=nis:\-N mail.aliases@my.nis.domain .)b will search the appropriate NIS map and always include null bytes in the key. Also: .(b O AliasFile=nis:\-f mail.aliases@my.nis.domain .)b will prevent sendmail from downcasing the key before the alias lookup. .sh 3 "Rebuilding the alias database" .pp The .i hash or .i dbm version of the database may be rebuilt explicitly by executing the command .(b newaliases .)b This is equivalent to giving .i sendmail the .b \-bi flag: .(b /usr/\*(SD/sendmail \-bi .)b .pp If you have multiple aliases databases specified, the .b \-bi flag rebuilds all the database types it understands (for example, it can rebuild NDBM databases but not NIS databases). .sh 3 "Potential problems" .pp There are a number of problems that can occur with the alias database. They all result from a .i sendmail process accessing the DBM version while it is only partially built. This can happen under two circumstances: One process accesses the database while another process is rebuilding it, or the process rebuilding the database dies (due to being killed or a system crash) before completing the rebuild. .pp Sendmail has three techniques to try to relieve these problems. First, it ignores interrupts while rebuilding the database; this avoids the problem of someone aborting the process leaving a partially rebuilt database. Second, it locks the database source file during the rebuild \(em but that may not work over NFS or if the file is unwritable. Third, at the end of the rebuild it adds an alias of the form .(b @: @ .)b (which is not normally legal). Before .i sendmail will access the database, it checks to insure that this entry exists\**. .(f \**The .b AliasWait option is required in the configuration for this action to occur. This should normally be specified. .)f .sh 3 "List owners" .pp If an error occurs on sending to a certain address, say .q \fIx\fP , .i sendmail will look for an alias of the form .q owner-\fIx\fP to receive the errors. This is typically useful for a mailing list where the submitter of the list has no control over the maintenance of the list itself; in this case the list maintainer would be the owner of the list. For example: .(b unix-wizards: eric@ucbarpa, wnj@monet, nosuchuser, sam@matisse owner-unix-wizards: unix-wizards-request unix-wizards-request: eric@ucbarpa .)b would cause .q eric@ucbarpa to get the error that will occur when someone sends to unix-wizards due to the inclusion of .q nosuchuser on the list. .pp List owners also cause the envelope sender address to be modified. The contents of the owner alias are used if they point to a single user, otherwise the name of the alias itself is used. For this reason, and to obey Internet conventions, the .q owner- address normally points at the .q -request address; this causes messages to go out with the typical Internet convention of using ``\c .i list -request'' as the return address. .sh 2 "User Information Database" .pp This option is deprecated, use virtusertable and genericstable instead as explained in .i cf/README . If you have a version of .i sendmail with the user information database compiled in, and you have specified one or more databases using the .b U option, the databases will be searched for a .i user :maildrop entry. If found, the mail will be sent to the specified address. .sh 2 "Per-User Forwarding (.forward Files)" .pp As an alternative to the alias database, any user may put a file with the name .q .forward in his or her home directory. If this file exists, .i sendmail redirects mail for that user to the list of addresses listed in the .forward file. Note that aliases are fully expanded before forward files are referenced. For example, if the home directory for user .q mckusick has a .forward file with contents: .(b mckusick@ernie kirk@calder .)b then any mail arriving for .q mckusick will be redirected to the specified accounts. .pp Actually, the configuration file defines a sequence of filenames to check. By default, this is the user's .forward file, but can be defined to be more generally using the .b ForwardPath option. If you change this, you will have to inform your user base of the change; \&.forward is pretty well incorporated into the collective subconscious. .sh 2 "Special Header Lines" .pp Several header lines have special interpretations defined by the configuration file. Others have interpretations built into .i sendmail that cannot be changed without changing the code. These built-ins are described here. .sh 3 "Errors-To:" .pp If errors occur anywhere during processing, this header will cause error messages to go to the listed addresses. This is intended for mailing lists. .pp The Errors-To: header was created in the bad old days when UUCP didn't understand the distinction between an envelope and a header; this was a hack to provide what should now be passed as the envelope sender address. It should go away. It is only used if the .b UseErrorsTo option is set. .pp The Errors-To: header is officially deprecated and will go away in a future release. .sh 3 "Apparently-To:" .pp RFC 822 requires at least one recipient field (To:, Cc:, or Bcc: line) in every message. If a message comes in with no recipients listed in the message then .i sendmail will adjust the header based on the .q NoRecipientAction option. One of the possible actions is to add an .q "Apparently-To:" header line for any recipients it is aware of. .pp The Apparently-To: header is non-standard and is both deprecated and strongly discouraged. .sh 3 "Precedence" .pp The Precedence: header can be used as a crude control of message priority. It tweaks the sort order in the queue and can be configured to change the message timeout values. The precedence of a message also controls how delivery status notifications (DSNs) are processed for that message. .sh 2 "IDENT Protocol Support" .pp .i Sendmail supports the IDENT protocol as defined in RFC 1413. Note that the RFC states a client should wait at least 30 seconds for a response. The default Timeout.ident is 5 seconds as many sites have adopted the practice of dropping IDENT queries. This has lead to delays processing mail. Although this enhances identification of the author of an email message by doing a ``call back'' to the originating system to include the owner of a particular TCP connection in the audit trail it is in no sense perfect; a determined forger can easily spoof the IDENT protocol. The following description is excerpted from RFC 1413: .ba +5 .lp 6. Security Considerations .lp The information returned by this protocol is at most as trustworthy as the host providing it OR the organization operating the host. For example, a PC in an open lab has few if any controls on it to prevent a user from having this protocol return any identifier the user wants. Likewise, if the host has been compromised the information returned may be completely erroneous and misleading. .lp The Identification Protocol is not intended as an authorization or access control protocol. At best, it provides some additional auditing information with respect to TCP connections. At worst, it can provide misleading, incorrect, or maliciously incorrect information. .lp The use of the information returned by this protocol for other than auditing is strongly discouraged. Specifically, using Identification Protocol information to make access control decisions - either as the primary method (i.e., no other checks) or as an adjunct to other methods may result in a weakening of normal host security. .lp An Identification server may reveal information about users, entities, objects or processes which might normally be considered private. An Identification server provides service which is a rough analog of the CallerID services provided by some phone companies and many of the same privacy considerations and arguments that apply to the CallerID service apply to Identification. If you wouldn't run a "finger" server due to privacy considerations you may not want to run this protocol. .ba .lp In some cases your system may not work properly with IDENT support due to a bug in the TCP/IP implementation. The symptoms will be that for some hosts the SMTP connection will be closed almost immediately. If this is true or if you do not want to use IDENT, you should set the IDENT timeout to zero; this will disable the IDENT protocol. .sh 1 "ARGUMENTS" .pp The complete list of arguments to .i sendmail is described in detail in Appendix A. Some important arguments are described here. .sh 2 "Queue Interval" .pp The amount of time between forking a process to run through the queue is defined by the .b \-q flag. If you run with delivery mode set to .b i or .b b this can be relatively large, since it will only be relevant when a host that was down comes back up. If you run in .b q mode it should be relatively short, since it defines the maximum amount of time that a message may sit in the queue. (See also the MinQueueAge option.) .pp RFC 1123 section 5.3.1.1 says that this value should be at least 30 minutes (although that probably doesn't make sense if you use ``queue-only'' mode). .pp Notice: the meaning of the interval time depends on whether normal queue runners or persistent queue runners are used. For the former, it is the time between subsequent starts of a queue run. For the latter, it is the time sendmail waits after a persistent queue runner has finished its work to start the next one. Hence for persistent queue runners this interval should be very low, typically no more than two minutes. .sh 2 "Daemon Mode" .pp If you allow incoming mail over an IPC connection, you should have a daemon running. This should be set by your .i /etc/rc file using the .b \-bd flag. The .b \-bd flag and the .b \-q flag may be combined in one call: .(b /usr/\*(SD/sendmail \-bd \-q30m .)b .pp An alternative approach is to invoke sendmail from .i inetd (8) (use the .b \-bs \ \-Am flags to ask sendmail to speak SMTP on its standard input and output and to run as MTA). This works and allows you to wrap .i sendmail in a TCP wrapper program, but may be a bit slower since the configuration file has to be re-read on every message that comes in. If you do this, you still need to have a .i sendmail running to flush the queue: .(b /usr/\*(SD/sendmail \-q30m .)b .sh 2 "Forcing the Queue" .pp In some cases you may find that the queue has gotten clogged for some reason. You can force a queue run using the .b \-q flag (with no value). It is entertaining to use the .b \-v flag (verbose) when this is done to watch what happens: .(b /usr/\*(SD/sendmail \-q \-v .)b .pp You can also limit the jobs to those with a particular queue identifier, recipient, sender, quarantine reason, or queue group using one of the queue modifiers. For example, .q \-qRberkeley restricts the queue run to jobs that have the string .q berkeley somewhere in one of the recipient addresses. Similarly, .q \-qSstring limits the run to particular senders, .q \-qIstring limits it to particular queue identifiers, and .q \-qQstring limits it to particular quarantined reasons and only operated on quarantined queue items, and .q \-qGstring limits it to a particular queue group. The named queue group will be run even if it is set to have 0 runners. You may also place an .b ! before the .b I or .b R or .b S or .b Q to indicate that jobs are limited to not including a particular queue identifier, recipient or sender. For example, .q \-q!Rseattle limits the queue run to jobs that do not have the string .q seattle somewhere in one of the recipient addresses. Should you need to terminate the queue jobs currently active then a SIGTERM to the parent of the process (or processes) will cleanly stop the jobs. .sh 2 "Debugging" .pp There are a fairly large number of debug flags built into .i sendmail . Each debug flag has a category and a level. Higher levels increase the level of debugging activity; in most cases, this means to print out more information. The convention is that levels greater than nine are .q absurd, i.e., they print out so much information that you wouldn't normally want to see them except for debugging that particular piece of code. .pp You should .b never run a production sendmail server in debug mode. Many of the debug flags will result in debug output being sent over the SMTP channel unless the option .b \-D is used. This will confuse many mail programs. However, for testing purposes, it can be useful when sending mail manually via telnet to the port you are using while debugging. .pp A debug category is either an integer, like 42, or a name, like ANSI. You can specify a range of numeric debug categories using the syntax 17-42. You can specify a set of named debug categories using a glob pattern like .q sm_trace_* . At present, only .q * and .q ? are supported in these glob patterns. .pp Debug flags are set using the .b \-d option; the syntax is: .(b .ta \w'debug-categories:M 'u debug-flag: \fB\-d\fP debug-list debug-list: debug-option [ , debug-option ]* debug-option: debug-categories [ . debug-level ] debug-categories: integer | integer \- integer | category-pattern category-pattern: [a-zA-Z_*?][a-zA-Z0-9_*?]* debug-level: integer .)b where spaces are for reading ease only. For example, .(b \-d12 Set category 12 to level 1 \-d12.3 Set category 12 to level 3 \-d3\-17 Set categories 3 through 17 to level 1 \-d3\-17.4 Set categories 3 through 17 to level 4 \-dANSI Set category ANSI to level 1 \-dsm_trace_*.3 Set all named categories matching sm_trace_* to level 3 .)b For a complete list of the available debug flags you will have to look at the code and the .i TRACEFLAGS file in the sendmail distribution (they are too dynamic to keep this document up to date). For a list of named debug categories in the sendmail binary, use .(b ident /usr/sbin/sendmail | grep Debug .)b .sh 2 "Changing the Values of Options" .pp Options can be overridden using the .b \-o or .b \-O command line flags. For example, .(b /usr/\*(SD/sendmail \-oT2m .)b sets the .b T (timeout) option to two minutes for this run only; the equivalent line using the long option name is .(b /usr/\*(SD/sendmail -OTimeout.queuereturn=2m .)b .pp Some options have security implications. Sendmail allows you to set these, but relinquishes its set-user-ID or set-group-ID permissions thereafter\**. .(f \**That is, it sets its effective uid to the real uid; thus, if you are executing as root, as from root's crontab file or during system startup the root permissions will still be honored. .)f .sh 2 "Trying a Different Configuration File" .pp An alternative configuration file can be specified using the .b \-C flag; for example, .(b /usr/\*(SD/sendmail \-Ctest.cf \-oQ/tmp/mqueue .)b uses the configuration file .i test.cf instead of the default .i /etc/mail/sendmail.cf. If the .b \-C flag has no value it defaults to .i sendmail.cf in the current directory. .pp .i Sendmail gives up set-user-ID root permissions (if it has been installed set-user-ID root) when you use this flag, so it is common to use a publicly writable directory (such as /tmp) as the queue directory (QueueDirectory or Q option) while testing. .sh 2 "Logging Traffic" .pp Many SMTP implementations do not fully implement the protocol. For example, some personal computer based SMTPs do not understand continuation lines in reply codes. These can be very hard to trace. If you suspect such a problem, you can set traffic logging using the .b \-X flag. For example, .(b /usr/\*(SD/sendmail \-X /tmp/traffic \-bd .)b will log all traffic in the file .i /tmp/traffic . .pp This logs a lot of data very quickly and should .b NEVER be used during normal operations. After starting up such a daemon, force the errant implementation to send a message to your host. All message traffic in and out of .i sendmail , including the incoming SMTP traffic, will be logged in this file. .sh 2 "Testing Configuration Files" .pp When you build a configuration table, you can do a certain amount of testing using the .q "test mode" of .i sendmail . For example, you could invoke .i sendmail as: .(b sendmail \-bt \-Ctest.cf .)b which would read the configuration file .q test.cf and enter test mode. In this mode, you enter lines of the form: .(b rwset address .)b where .i rwset is the rewriting set you want to use and .i address is an address to apply the set to. Test mode shows you the steps it takes as it proceeds, finally showing you the address it ends up with. You may use a comma separated list of rwsets for sequential application of rules to an input. For example: .(b 3,1,21,4 monet:bollard .)b first applies ruleset three to the input .q monet:bollard. Ruleset one is then applied to the output of ruleset three, followed similarly by rulesets twenty-one and four. .pp If you need more detail, you can also use the .q \-d21 flag to turn on more debugging. For example, .(b sendmail \-bt \-d21.99 .)b turns on an incredible amount of information; a single word address is probably going to print out several pages worth of information. .pp You should be warned that internally, .i sendmail applies ruleset 3 to all addresses. In test mode you will have to do that manually. For example, older versions allowed you to use .(b 0 bruce@broadcast.sony.com .)b This version requires that you use: .(b 3,0 bruce@broadcast.sony.com .)b .pp As of version 8.7, some other syntaxes are available in test mode: .nr ii 1i .ip \&.D\|x\|value defines macro .i x to have the indicated .i value . This is useful when debugging rules that use the .b $& \c .i x syntax. .ip \&.C\|c\|value adds the indicated .i value to class .i c . .ip \&=S\|ruleset dumps the contents of the indicated ruleset. .ip \-d\|debug-spec is equivalent to the command-line flag. .lp Version 8.9 introduced more features: .nr ii 1i .ip ? shows a help message. .ip =M display the known mailers. .ip $m print the value of macro m. .ip $=c print the contents of class c. .ip /mx\ host returns the MX records for `host'. .ip /parse\ address parse address, returning the value of .i crackaddr , and the parsed address. .ip /try\ mailer\ addr rewrite address into the form it will have when presented to the indicated mailer. .ip /tryflags\ flags set flags used by parsing. The flags can be `H' for Header or `E' for Envelope, and `S' for Sender or `R' for Recipient. These can be combined, `HR' sets flags for header recipients. .ip /canon\ hostname try to canonify hostname. .ip /map\ mapname\ key look up `key' in the indicated `mapname'. .ip /quit quit address test mode. .lp .sh 2 "Persistent Host Status Information" .pp When .b HostStatusDirectory is enabled, information about the status of hosts is maintained on disk and can thus be shared between different instantiations of .i sendmail . The status of the last connection with each remote host may be viewed with the command: .(b sendmail \-bh .)b This information may be flushed with the command: .(b sendmail \-bH .)b Flushing the information prevents new .i sendmail processes from loading it, but does not prevent existing processes from using the status information that they already have. .sh 1 "TUNING" .pp There are a number of configuration parameters you may want to change, depending on the requirements of your site. Most of these are set using an option in the configuration file. For example, the line .q "O Timeout.queuereturn=5d" sets option .q Timeout.queuereturn to the value .q 5d (five days). .pp Most of these options have appropriate defaults for most sites. However, sites having very high mail loads may find they need to tune them as appropriate for their mail load. In particular, sites experiencing a large number of small messages, many of which are delivered to many recipients, may find that they need to adjust the parameters dealing with queue priorities. .pp All versions of .i sendmail prior to 8.7 had single character option names. As of 8.7, options have long (multi-character names). Although old short names are still accepted, most new options do not have short equivalents. .pp This section only describes the options you are most likely to want to tweak; read section .\"XREF 5 for more details. .sh 2 "Timeouts" .pp All time intervals are set using a scaled syntax. For example, .q 10m represents ten minutes, whereas .q 2h30m represents two and a half hours. The full set of scales is: .(b .ta 4n s seconds m minutes h hours d days w weeks .)b .sh 3 "Queue interval" .pp The argument to the .b \-q flag specifies how often a sub-daemon will run the queue. This is typically set to between fifteen minutes and one hour. If not set, or set to zero, the queue will not be run automatically. RFC 1123 section 5.3.1.1 recommends that this be at least 30 minutes. Should you need to terminate the queue jobs currently active then a SIGTERM to the parent of the process (or processes) will cleanly stop the jobs. .sh 3 "Read timeouts" .pp Timeouts all have option names .q Timeout.\fIsuboption\fP . Most of these control SMTP operations. The recognized .i suboption s, their default values, and the minimum values allowed by RFC 2821 section 4.5.3.2 (or RFC 1123 section 5.3.2) are: .nr ii 1i .ip connect The time to wait for an SMTP connection to open (the .i connect (2) system call) [0, unspecified]. If zero, uses the kernel default. In no case can this option extend the timeout longer than the kernel provides, but it can shorten it. This is to get around kernels that provide an absurdly long connection timeout (90 minutes in one case). .ip iconnect The same as .i connect, except it applies only to the initial attempt to connect to a host for a given message [0, unspecified]. The concept is that this should be very short (a few seconds); hosts that are well connected and responsive will thus be serviced immediately. Hosts that are slow will not hold up other deliveries in the initial delivery attempt. .ip aconnect [0, unspecified] The overall timeout waiting for all connection for a single delivery attempt to succeed. If 0, no overall limit is applied. This can be used to restrict the total amount of time trying to connect to a long list of host that could accept an e-mail for the recipient. This timeout does not apply to .b FallbackMXhost , i.e., if the time is exhausted, the .b FallbackMXhost is tried next. .ip initial The wait for the initial 220 greeting message [5m, 5m]. .ip helo The wait for a reply from a HELO or EHLO command [5m, unspecified]. This may require a host name lookup, so five minutes is probably a reasonable minimum. .ip mail\(dg The wait for a reply from a MAIL command [10m, 5m]. .ip rcpt\(dg The wait for a reply from a RCPT command [1h, 5m]. This should be long because it could be pointing at a list that takes a long time to expand (see below). .ip datainit\(dg The wait for a reply from a DATA command [5m, 2m]. .ip datablock\(dg\(dd The wait for reading a data block (that is, the body of the message). [1h, 3m]. This should be long because it also applies to programs piping input to .i sendmail which have no guarantee of promptness. .ip datafinal\(dg The wait for a reply from the dot terminating a message. [1h, 10m]. If this is shorter than the time actually needed for the receiver to deliver the message, duplicates will be generated. This is discussed in RFC 1047. .ip rset The wait for a reply from a RSET command [5m, unspecified]. .ip quit The wait for a reply from a QUIT command [2m, unspecified]. .ip misc The wait for a reply from miscellaneous (but short) commands such as NOOP (no-operation) and VERB (go into verbose mode). [2m, unspecified]. .ip command\(dg\(dd In server SMTP, the time to wait for another command. [1h, 5m]. .ip ident\(dd The timeout waiting for a reply to an IDENT query [5s\**, unspecified]. .(f \**On some systems the default is zero to turn the protocol off entirely. .)f .ip lhlo The wait for a reply to an LMTP LHLO command [2m, unspecified]. .ip auth The timeout for a reply in an SMTP AUTH dialogue [10m, unspecified]. .ip starttls The timeout for a reply to an SMTP STARTTLS command and the TLS handshake [1h, unspecified]. .ip fileopen\(dd The timeout for opening .forward and :include: files [60s, none]. .ip control\(dd The timeout for a complete control socket transaction to complete [2m, none]. .ip hoststatus\(dd How long status information about a host (e.g., host down) will be cached before it is considered stale [30m, unspecified]. .ip resolver.retrans\(dd The resolver's retransmission time interval (in seconds) [varies]. Sets both .i Timeout.resolver.retrans.first and .i Timeout.resolver.retrans.normal . .ip resolver.retrans.first\(dd The resolver's retransmission time interval (in seconds) for the first attempt to deliver a message [varies]. .ip resolver.retrans.normal\(dd The resolver's retransmission time interval (in seconds) for all resolver lookups except the first delivery attempt [varies]. .ip resolver.retry\(dd The number of times to retransmit a resolver query. Sets both .i Timeout.resolver.retry.first and .i Timeout.resolver.retry.normal [varies]. .ip resolver.retry.first\(dd The number of times to retransmit a resolver query for the first attempt to deliver a message [varies]. .ip resolver.retry.normal\(dd The number of times to retransmit a resolver query for all resolver lookups except the first delivery attempt [varies]. .lp For compatibility with old configuration files, if no .i suboption is specified, all the timeouts marked with .DG (\(dg) are set to the indicated value. All but those marked with .DD (\(dd) apply to client SMTP. .pp For example, the lines: .(b O Timeout.command=25m O Timeout.datablock=3h .)b sets the server SMTP command timeout to 25 minutes and the input data block timeout to three hours. .sh 3 "Message timeouts" .pp After sitting in the queue for a few days, an undeliverable message will time out. This is to insure that at least the sender is aware of the inability to send a message. The timeout is typically set to five days. It is sometimes considered convenient to also send a warning message if the message is in the queue longer than a few hours (assuming you normally have good connectivity; if your messages normally took several hours to send you wouldn't want to do this because it wouldn't be an unusual event). These timeouts are set using the .b Timeout.queuereturn and .b Timeout.queuewarn options in the configuration file (previously both were set using the .b T option). .pp If the message is submitted using the .sm NOTIFY .sm SMTP extension, warning messages will only be sent if .sm NOTIFY=DELAY is specified. The queuereturn and queuewarn timeouts can be further qualified with a tag based on the Precedence: field in the message; they must be one of .q urgent (indicating a positive non-zero precedence), .q normal (indicating a zero precedence), or .q non-urgent (indicating negative precedences). For example, setting .q Timeout.queuewarn.urgent=1h sets the warning timeout for urgent messages only to one hour. The default if no precedence is indicated is to set the timeout for all precedences. If the message has a normal (default) precedence and it is a delivery status notification (DSN), .b Timeout.queuereturn.dsn and .b Timeout.queuewarn.dsn can be used to give an alternative warn and return time for DSNs. The value "now" can be used for -O Timeout.queuereturn to return entries immediately during a queue run, e.g., to bounce messages independent of their time in the queue. .pp Since these options are global, and since you cannot know .i "a priori" how long another host outside your domain will be down, a five day timeout is recommended. This allows a recipient to fix the problem even if it occurs at the beginning of a long weekend. RFC 1123 section 5.3.1.1 says that this parameter should be ``at least 4\-5 days''. .pp The .b Timeout.queuewarn value can be piggybacked on the .b T option by indicating a time after which a warning message should be sent; the two timeouts are separated by a slash. For example, the line .(b OT5d/4h .)b causes email to fail after five days, but a warning message will be sent after four hours. This should be large enough that the message will have been tried several times. .sh 2 "Forking During Queue Runs" .pp By setting the .b ForkEachJob (\c .b Y ) option, .i sendmail will fork before each individual message while running the queue. This option was used with earlier releases to prevent .i sendmail from consuming large amounts of memory. It should no longer be necessary with .i sendmail 8.12. If the .b ForkEachJob option is not set, .i sendmail will keep track of hosts that are down during a queue run, which can improve performance dramatically. .pp If the .b ForkEachJob option is set, .i sendmail cannot use connection caching. .sh 2 "Queue Priorities" .pp Every message is assigned a priority when it is first instantiated, consisting of the message size (in bytes) offset by the message class (which is determined from the Precedence: header) times the .q "work class factor" and the number of recipients times the .q "work recipient factor." The priority is used to order the queue. Higher numbers for the priority mean that the message will be processed later when running the queue. .pp The message size is included so that large messages are penalized relative to small messages. The message class allows users to send .q "high priority" messages by including a .q Precedence: field in their message; the value of this field is looked up in the .b P lines of the configuration file. Since the number of recipients affects the amount of load a message presents to the system, this is also included into the priority. .pp The recipient and class factors can be set in the configuration file using the .b RecipientFactor (\c .b y ) and .b ClassFactor (\c .b z ) options respectively. They default to 30000 (for the recipient factor) and 1800 (for the class factor). The initial priority is: .EQ pri = msgsize - (class times bold ClassFactor) + (nrcpt times bold RecipientFactor) .EN (Remember, higher values for this parameter actually mean that the job will be treated with lower priority.) .pp The priority of a job can also be adjusted each time it is processed (that is, each time an attempt is made to deliver it) using the .q "work time factor," set by the .b RetryFactor (\c .b Z ) option. This is added to the priority, so it normally decreases the precedence of the job, on the grounds that jobs that have failed many times will tend to fail again in the future. The .b RetryFactor option defaults to 90000. .sh 2 "Load Limiting" .pp .i Sendmail can be asked to queue (but not deliver) mail if the system load average gets too high using the .b QueueLA (\c .b x ) option. When the load average exceeds the value of the .b QueueLA option, the delivery mode is set to .b q (queue only) if the .b QueueFactor (\c .b q ) option divided by the difference in the current load average and the .b QueueLA option plus one is less than the priority of the message \(em that is, the message is queued iff: .EQ pri > { bold QueueFactor } over { LA - { bold QueueLA } + 1 } .EN The .b QueueFactor option defaults to 600000, so each point of load average is worth 600000 priority points (as described above). .pp For drastic cases, the .b RefuseLA (\c .b X ) option defines a load average at which .i sendmail will refuse to accept network connections. Locally generated mail, i.e., mail which is not submitted via SMTP (including incoming UUCP mail), is still accepted. Notice that the MSP submits mail to the MTA via SMTP, and hence mail will be queued in the client queue in such a case. Therefore it is necessary to run the client mail queue periodically. .sh 2 "Resource Limits" .pp .i Sendmail has several parameters to control resource usage. Besides those mentionted in the previous section, there are at least .b MaxDaemonChildren , .b ConnectionRateThrottle , .b MaxQueueChildren , and .b MaxRunnersPerQueue . The latter two limit the number of .i sendmail processes that operate on the queue. These are discussed in the section ``Queue Group Declaration''. The former two can be used to limit the number of incoming connections. Their appropriate values depend on the host operating system and the hardware, e.g., amount of memory. In many situations it might be useful to set limits to prevent to have too many .i sendmail processes, however, these limits can be abused to mount a denial of service attack. For example, if .b MaxDaemonChildren=10 then an attacker needs to open only 10 SMTP sessions to the server, leave them idle for most of the time, and no more connections will be accepted. If this option is set then the timeouts used in a SMTP session should be lowered from their default values to their minimum values as specified in RFC 2821 and listed in section .\"XREF 4.1.2. .sh 2 "Measures against Denial of Service Attacks" .pp .i Sendmail has some built-in measures against simple denial of service (DoS) attacks. The SMTP server by default slows down if too many bad commands are issued or if some commands are repeated too often within a session. Details can be found in the source file .b sendmail/srvrsmtp.c by looking for the macro definitions of .b MAXBADCOMMANDS , .b MAXNOOPCOMMANDS , .b MAXHELOCOMMANDS , .b MAXVRFYCOMMANDS , and .b MAXETRNCOMMANDS . If an SMTP command is issued more often than the corresponding .b MAXcmdCOMMANDS value, then the response is delayed exponentially, starting with a sleep time of one second, up to a maximum of four minutes (as defined by .b MAXTIMEOUT ). If the option .b MaxDaemonChildren is set to a value greater than zero, then this could make a DoS attack even worse since it keeps a connection open longer than necessary. Therefore a connection is terminated with a 421 SMTP reply code if the number of commands exceeds the limit by a factor of two and .b MAXBADCOMMANDS is set to a value greater than zero (the default is 25). .sh 2 "Delivery Mode" .pp There are a number of delivery modes that .i sendmail can operate in, set by the .b DeliveryMode (\c .b d ) configuration option. These modes specify how quickly mail will be delivered. Legal modes are: .(b .ta 4n i deliver interactively (synchronously) b deliver in background (asynchronously) q queue only (don't deliver) d defer delivery attempts (don't deliver) .)b There are tradeoffs. Mode .q i gives the sender the quickest feedback, but may slow down some mailers and is hardly ever necessary. Mode .q b delivers promptly but can cause large numbers of processes if you have a mailer that takes a long time to deliver a message. Mode .q q minimizes the load on your machine, but means that delivery may be delayed for up to the queue interval. Mode .q d is identical to mode .q q except that it also prevents lookups in maps including the .b -D flag from working during the initial queue phase; it is intended for ``dial on demand'' sites where DNS lookups might cost real money. Some simple error messages (e.g., host unknown during the SMTP protocol) will be delayed using this mode. Mode .q b is the usual default. .pp If you run in mode .q q (queue only), .q d (defer), or .q b (deliver in background) .i sendmail will not expand aliases and follow .forward files upon initial receipt of the mail. This speeds up the response to RCPT commands. Mode .q i should not be used by the SMTP server. .sh 2 "Log Level" .pp The level of logging can be set for .i sendmail . The default using a standard configuration table is level 9. The levels are as follows: .nr ii 0.5i .ip 0 Minimal logging. .ip 1 Serious system failures and potential security problems. .ip 2 Lost communications (network problems) and protocol failures. .ip 3 Other serious failures, malformed addresses, transient forward/include errors, connection timeouts. .ip 4 Minor failures, out of date alias databases, connection rejections via check_ rulesets. .ip 5 Message collection statistics. .ip 6 Creation of error messages, VRFY and EXPN commands. .ip 7 Delivery failures (host or user unknown, etc.). .ip 8 Successful deliveries and alias database rebuilds. .ip 9 Messages being deferred (due to a host being down, etc.). .ip 10 Database expansion (alias, forward, and userdb lookups) and authentication information. .ip 11 NIS errors and end of job processing. .ip 12 Logs all SMTP connections. .ip 13 Log bad user shells, files with improper permissions, and other questionable situations. .ip 14 Logs refused connections. .ip 15 Log all incoming and outgoing SMTP commands. .ip 20 Logs attempts to run locked queue files. These are not errors, but can be useful to note if your queue appears to be clogged. .ip 30 Lost locks (only if using lockf instead of flock). .lp Additionally, values above 64 are reserved for extremely verbose debugging output. No normal site would ever set these. .sh 2 "File Modes" .pp The modes used for files depend on what functionality you want and the level of security you require. In many cases .i sendmail does careful checking of the modes of files and directories to avoid accidental compromise; if you want to make it possible to have group-writable support files you may need to use the .b DontBlameSendmail option to turn off some of these checks. .sh 3 "To suid or not to suid?" .pp .i Sendmail is no longer installed set-user-ID to root. sendmail/SECURITY explains how to configure and install .i sendmail without set-user-ID to root but set-group-ID which is the default configuration starting with 8.12. .pp The daemon usually runs as root, unless other measures are taken. At the point where .i sendmail is about to .i exec \|(2) a mailer, it checks to see if the userid is zero (root); if so, it resets the userid and groupid to a default (set by the .b U= equate in the mailer line; if that is not set, the .b DefaultUser option is used). This can be overridden by setting the .b S flag to the mailer for mailers that are trusted and must be called as root. However, this will cause mail processing to be accounted (using .i sa \|(8)) to root rather than to the user sending the mail. .pp A middle ground is to set the .b RunAsUser option. This causes .i sendmail to become the indicated user as soon as it has done the startup that requires root privileges (primarily, opening the .sm SMTP socket). If you use .b RunAsUser , the queue directory (normally .i /var/spool/mqueue ) should be owned by that user, and all files and databases (including user .i \&.forward files, alias files, :include: files, and external databases) must be readable by that user. Also, since sendmail will not be able to change its uid, delivery to programs or files will be marked as unsafe, e.g., undeliverable, in .i \&.forward , aliases, and :include: files. Administrators can override this by setting the .b DontBlameSendmail option to the setting .b NonRootSafeAddr . .b RunAsUser is probably best suited for firewall configurations that don't have regular user logins. If the option is used on a system which performs local delivery, then the local delivery agent must have the proper permissions (i.e., usually set-user-ID root) since it will be invoked by the .b RunAsUser , not by root. .sh 3 "Turning off security checks" .pp .i Sendmail is very particular about the modes of files that it reads or writes. For example, by default it will refuse to read most files that are group writable on the grounds that they might have been tampered with by someone other than the owner; it will even refuse to read files in group writable directories. Also, sendmail will refuse to create a new aliases database in an unsafe directory. You can get around this by manually creating the database file as a trusted user ahead of time and then rebuilding the aliases database with .b newaliases . .pp If you are .i quite sure that your configuration is safe and you want .i sendmail to avoid these security checks, you can turn off certain checks using the .b DontBlameSendmail option. This option takes one or more names that disable checks. In the descriptions that follow, .q "unsafe directory" means a directory that is writable by anyone other than the owner. The values are: .nr ii 0.5i .ip Safe No special handling. .ip AssumeSafeChown Assume that the .i chown system call is restricted to root. Since some versions of UNIX permit regular users to give away their files to other users on some filesystems, .i sendmail often cannot assume that a given file was created by the owner, particularly when it is in a writable directory. You can set this flag if you know that file giveaway is restricted on your system. .ip ClassFileInUnsafeDirPath When reading class files (using the .b F line in the configuration file), allow files that are in unsafe directories. .ip DontWarnForwardFileInUnsafeDirPath Prevent logging of unsafe directory path warnings for non-existent forward files. .ip ErrorHeaderInUnsafeDirPath Allow the file named in the .b ErrorHeader option to be in an unsafe directory. .ip FileDeliveryToHardLink Allow delivery to files that are hard links. .ip FileDeliveryToSymLink Allow delivery to files that are symbolic links. .ip ForwardFileInGroupWritableDirPath Allow .i \&.forward files in group writable directories. .ip ForwardFileInUnsafeDirPath Allow .i \&.forward files in unsafe directories. .ip ForwardFileInUnsafeDirPathSafe Allow a .i \&.forward file that is in an unsafe directory to include references to program and files. .ip GroupReadableKeyFile Accept a group-readable key file for STARTTLS. .ip GroupReadableSASLDBFile Accept a group-readable Cyrus SASL password file. .ip GroupWritableAliasFile Allow group-writable alias files. .ip GroupWritableDirPathSafe Change the definition of .q "unsafe directory" to consider group-writable directories to be safe. World-writable directories are always unsafe. .ip GroupWritableForwardFile Allow group writable .i \&.forward files. .ip GroupWritableForwardFileSafe Accept group-writable .i \&.forward files as safe for program and file delivery. .ip GroupWritableIncludeFile Allow group wriable .i :include: files. .ip GroupWritableIncludeFileSafe Accept group-writable .i :include: files as safe for program and file delivery. .ip GroupWritableSASLDBFile Accept a group-writable Cyrus SASL password file. .ip HelpFileInUnsafeDirPath Allow the file named in the .b HelpFile option to be in an unsafe directory. .ip IncludeFileInGroupWritableDirPath Allow .i :include: files in group writable directories. .ip IncludeFileInUnsafeDirPath Allow .i :include: files in unsafe directories. .ip IncludeFileInUnsafeDirPathSafe Allow a .i :include: file that is in an unsafe directory to include references to program and files. .ip InsufficientEntropy Try to use STARTTLS even if the PRNG for OpenSSL is not properly seeded despite the security problems. .ip LinkedAliasFileInWritableDir Allow an alias file that is a link in a writable directory. .ip LinkedClassFileInWritableDir Allow class files that are links in writable directories. .ip LinkedForwardFileInWritableDir Allow .i \&.forward files that are links in writable directories. .ip LinkedIncludeFileInWritableDir Allow .i :include: files that are links in writable directories. .ip LinkedMapInWritableDir Allow map files that are links in writable directories. This includes alias database files. .ip LinkedServiceSwitchFileInWritableDir Allow the service switch file to be a link even if the directory is writable. .ip MapInUnsafeDirPath Allow maps (e.g., .i hash , .i btree , and .i dbm files) in unsafe directories. This includes alias database files. .ip NonRootSafeAddr Do not mark file and program deliveries as unsafe if sendmail is not running with root privileges. .ip RunProgramInUnsafeDirPath Run programs that are in writable directories without logging a warning. .ip RunWritableProgram Run programs that are group- or world-writable without logging a warning. .ip TrustStickyBit Allow group or world writable directories if the sticky bit is set on the directory. Do not set this on systems which do not honor the sticky bit on directories. .ip WorldWritableAliasFile Accept world-writable alias files. .ip WorldWritableForwardfile Allow world writable .i \&.forward files. .ip WorldWritableIncludefile Allow world wriable .i :include: files. .ip WriteMapToHardLink Allow writes to maps that are hard links. .ip WriteMapToSymLink Allow writes to maps that are symbolic links. .ip WriteStatsToHardLink Allow the status file to be a hard link. .ip WriteStatsToSymLink Allow the status file to be a symbolic link. .sh 2 "Connection Caching" .pp When processing the queue, .i sendmail will try to keep the last few open connections open to avoid startup and shutdown costs. This only applies to IPC and LPC connections. .pp When trying to open a connection the cache is first searched. If an open connection is found, it is probed to see if it is still active by sending a .sm RSET command. It is not an error if this fails; instead, the connection is closed and reopened. .pp Two parameters control the connection cache. The .b ConnectionCacheSize (\c .b k ) option defines the number of simultaneous open connections that will be permitted. If it is set to zero, connections will be closed as quickly as possible. The default is one. This should be set as appropriate for your system size; it will limit the amount of system resources that .i sendmail will use during queue runs. Never set this higher than 4. .pp The .b ConnectionCacheTimeout (\c .b K ) option specifies the maximum time that any cached connection will be permitted to idle. When the idle time exceeds this value the connection is closed. This number should be small (under ten minutes) to prevent you from grabbing too many resources from other hosts. The default is five minutes. .sh 2 "Name Server Access" .pp Control of host address lookups is set by the .b hosts service entry in your service switch file. If you are on a system that has built-in service switch support (e.g., Ultrix, Solaris, or DEC OSF/1) then your system is probably configured properly already. Otherwise, .i sendmail will consult the file .b /etc/mail/service.switch , which should be created. .i Sendmail only uses two entries: .b hosts and .b aliases , although system routines may use other services (notably the .b passwd service for user name lookups by .i getpwname ). .pp However, some systems (such as SunOS 4.X) will do DNS lookups regardless of the setting of the service switch entry. In particular, the system routine .i gethostbyname (3) is used to look up host names, and many vendor versions try some combination of DNS, NIS, and file lookup in /etc/hosts without consulting a service switch. .i Sendmail makes no attempt to work around this problem, and the DNS lookup will be done anyway. If you do not have a nameserver configured at all, such as at a UUCP-only site, .i sendmail will get a .q "connection refused" message when it tries to connect to the name server. If the .b hosts switch entry has the service .q dns listed somewhere in the list, .i sendmail will interpret this to mean a temporary failure and will queue the mail for later processing; otherwise, it ignores the name server data. .pp The same technique is used to decide whether to do MX lookups. If you want MX support, you .i must have .q dns listed as a service in the .b hosts switch entry. .pp The .b ResolverOptions (\c .b I ) option allows you to tweak name server options. The command line takes a series of flags as documented in .i resolver (3) (with the leading .q RES_ deleted). Each can be preceded by an optional `+' or `\(mi'. For example, the line .(b O ResolverOptions=+AAONLY \(miDNSRCH .)b turns on the AAONLY (accept authoritative answers only) and turns off the DNSRCH (search the domain path) options. Most resolver libraries default DNSRCH, DEFNAMES, and RECURSE flags on and all others off. If NETINET6 is enabled, most libraries default to USE_INET6 as well. You can also include .q HasWildcardMX to specify that there is a wildcard MX record matching your domain; this turns off MX matching when canonifying names, which can lead to inappropriate canonifications. Use .q WorkAroundBrokenAAAA when faced with a broken nameserver that returns SERVFAIL (a temporary failure) on T_AAAA (IPv6) lookups during hostname canonification. Notice: it might be necessary to apply the same (or similar) options to .i submit.cf too. .pp Version level 1 configurations (see the section about ``Configuration Version Level'') turn DNSRCH and DEFNAMES off when doing delivery lookups, but leave them on everywhere else. Version 8 of .i sendmail ignores them when doing canonification lookups (that is, when using $[ ... $]), and always does the search. If you don't want to do automatic name extension, don't call $[ ... $]. .pp The search rules for $[ ... $] are somewhat different than usual. If the name being looked up has at least one dot, it always tries the unmodified name first. If that fails, it tries the reduced search path, and lastly tries the unmodified name (but only for names without a dot, since names with a dot have already been tried). This allows names such as ``utc.CS'' to match the site in Czechoslovakia rather than the site in your local Computer Science department. It also prefers A and CNAME records over MX records \*- that is, if it finds an MX record it makes note of it, but keeps looking. This way, if you have a wildcard MX record matching your domain, it will not assume that all names match. .pp To completely turn off all name server access on systems without service switch support (such as SunOS 4.X) you will have to recompile with \-DNAMED_BIND=0 and remove \-lresolv from the list of libraries to be searched when linking. .sh 2 "Moving the Per-User Forward Files" .pp Some sites mount each user's home directory from a local disk on their workstation, so that local access is fast. However, the result is that .forward file lookups from a central mail server are slow. In some cases, mail can even be delivered on machines inappropriately because of a file server being down. The performance can be especially bad if you run the automounter. .pp The .b ForwardPath (\c .b J ) option allows you to set a path of forward files. For example, the config file line .(b O ForwardPath=/var/forward/$u:$z/.forward.$w .)b would first look for a file with the same name as the user's login in /var/forward; if that is not found (or is inaccessible) the file ``.forward.\c .i machinename '' in the user's home directory is searched. A truly perverse site could also search by sender by using $r, $s, or $f. .pp If you create a directory such as /var/forward, it should be mode 1777 (that is, the sticky bit should be set). Users should create the files mode 0644. Note that you must use the ForwardFileInUnsafeDirPath and ForwardFileInUnsafeDirPathSafe flags with the .b DontBlameSendmail option to allow forward files in a world writable directory. This might also be used as a denial of service attack (users could create forward files for other users); a better approach might be to create /var/forward mode 0755 and create empty files for each user, owned by that user, mode 0644. If you do this, you don't have to set the DontBlameSendmail options indicated above. .sh 2 "Free Space" .pp On systems that have one of the system calls in the .i statfs (2) family (including .i statvfs and .i ustat ), you can specify a minimum number of free blocks on the queue filesystem using the .b MinFreeBlocks (\c .b b ) option. If there are fewer than the indicated number of blocks free on the filesystem on which the queue is mounted the SMTP server will reject mail with the 452 error code. This invites the SMTP client to try again later. .pp Beware of setting this option too high; it can cause rejection of email when that mail would be processed without difficulty. .sh 2 "Maximum Message Size" .pp To avoid overflowing your system with a large message, the .b MaxMessageSize option can be set to set an absolute limit on the size of any one message. This will be advertised in the ESMTP dialogue and checked during message collection. .sh 2 "Privacy Flags" .pp The .b PrivacyOptions (\c .b p ) option allows you to set certain ``privacy'' flags. Actually, many of them don't give you any extra privacy, rather just insisting that client SMTP servers use the HELO command before using certain commands or adding extra headers to indicate possible spoof attempts. .pp The option takes a series of flag names; the final privacy is the inclusive or of those flags. For example: .(b O PrivacyOptions=needmailhelo, noexpn .)b insists that the HELO or EHLO command be used before a MAIL command is accepted and disables the EXPN command. .pp The flags are detailed in section .\"XREF 5.6. .sh 2 "Send to Me Too" .pp Beginning with version 8.10, .i sendmail includes by default the (envelope) sender in any list expansions. For example, if .q matt sends to a list that contains .q matt as one of the members he will get a copy of the message. If the .b MeToo option is set to .sm FALSE (in the configuration file or via the command line), this behavior is changed, i.e., the (envelope) sender is excluded in list expansions. .sh 1 "THE WHOLE SCOOP ON THE CONFIGURATION FILE" .pp This section describes the configuration file in detail. .pp There is one point that should be made clear immediately: the syntax of the configuration file is designed to be reasonably easy to parse, since this is done every time .i sendmail starts up, rather than easy for a human to read or write. The configuration file should be generated via the method described in .b cf/README , it should not be edited directly unless someone is familiar with the internals of the syntax described here and it is not possible to achieve the desired result via the default method. .pp The configuration file is organized as a series of lines, each of which begins with a single character defining the semantics for the rest of the line. Lines beginning with a space or a tab are continuation lines (although the semantics are not well defined in many places). Blank lines and lines beginning with a sharp symbol (`#') are comments. .sh 2 "R and S \*- Rewriting Rules" .pp The core of address parsing are the rewriting rules. These are an ordered production system. .i Sendmail scans through the set of rewriting rules looking for a match on the left hand side (LHS) of the rule. When a rule matches, the address is replaced by the right hand side (RHS) of the rule. .pp There are several sets of rewriting rules. Some of the rewriting sets are used internally and must have specific semantics. Other rewriting sets do not have specifically assigned semantics, and may be referenced by the mailer definitions or by other rewriting sets. .pp The syntax of these two commands are: .(b F .b S \c .i n .)b Sets the current ruleset being collected to .i n . If you begin a ruleset more than once it appends to the old definition. .(b F .b R \c .i lhs .i rhs .i comments .)b The fields must be separated by at least one tab character; there may be embedded spaces in the fields. The .i lhs is a pattern that is applied to the input. If it matches, the input is rewritten to the .i rhs . The .i comments are ignored. .pp Macro expansions of the form .b $ \c .i x are performed when the configuration file is read. A literal .b $ can be included using .b $$ . Expansions of the form .b $& \c .i x are performed at run time using a somewhat less general algorithm. This is intended only for referencing internally defined macros such as .b $h that are changed at runtime. .sh 3 "The left hand side" .pp The left hand side of rewriting rules contains a pattern. Normal words are simply matched directly. Metasyntax is introduced using a dollar sign. The metasymbols are: .(b .ta \w'\fB$=\fP\fIx\fP 'u \fB$*\fP Match zero or more tokens \fB$+\fP Match one or more tokens \fB$\-\fP Match exactly one token \fB$=\fP\fIx\fP Match any phrase in class \fIx\fP \fB$~\fP\fIx\fP Match any word not in class \fIx\fP .)b If any of these match, they are assigned to the symbol .b $ \c .i n for replacement on the right hand side, where .i n is the index in the LHS. For example, if the LHS: .(b $\-:$+ .)b is applied to the input: .(b UCBARPA:eric .)b the rule will match, and the values passed to the RHS will be: .(b .ta 4n $1 UCBARPA $2 eric .)b .pp Additionally, the LHS can include .b $@ to match zero tokens. This is .i not bound to a .b $ \c .i n on the RHS, and is normally only used when it stands alone in order to match the null input. .sh 3 "The right hand side" .pp When the left hand side of a rewriting rule matches, the input is deleted and replaced by the right hand side. Tokens are copied directly from the RHS unless they begin with a dollar sign. Metasymbols are: .(b .ta \w'$#mailer\0\0\0'u \fB$\fP\fIn\fP Substitute indefinite token \fIn\fP from LHS \fB$[\fP\fIname\fP\fB$]\fP Canonicalize \fIname\fP \fB$(\fP\fImap key\fP \fB$@\fP\fIarguments\fP \fB$:\fP\fIdefault\fP \fB$)\fP Generalized keyed mapping function \fB$>\fP\fIn\fP \*(lqCall\*(rq ruleset \fIn\fP \fB$#\fP\fImailer\fP Resolve to \fImailer\fP \fB$@\fP\fIhost\fP Specify \fIhost\fP \fB$:\fP\fIuser\fP Specify \fIuser\fP .)b .pp The .b $ \c .i n syntax substitutes the corresponding value from a .b $+ , .b $\- , .b $* , .b $= , or .b $~ match on the LHS. It may be used anywhere. .pp A host name enclosed between .b $[ and .b $] is looked up in the host database(s) and replaced by the canonical name\**. .(f \**This is actually completely equivalent to $(host \fIhostname\fP$). In particular, a .b $: default can be used. .)f For example, .q $[ftp$] might become .q ftp.CS.Berkeley.EDU and .q $[[128.32.130.2]$] would become .q vangogh.CS.Berkeley.EDU. .i Sendmail recognizes its numeric IP address without calling the name server and replaces it with its canonical name. .pp The .b $( \&... .b $) syntax is a more general form of lookup; it uses a named map instead of an implicit map. If no lookup is found, the indicated .i default is inserted; if no default is specified and no lookup matches, the value is left unchanged. The .i arguments are passed to the map for possible use. .pp The .b $> \c .i n syntax causes the remainder of the line to be substituted as usual and then passed as the argument to ruleset .i n . The final value of ruleset .i n then becomes the substitution for this rule. The .b $> syntax expands everything after the ruleset name to the end of the replacement string and then passes that as the initial input to the ruleset. Recursive calls are allowed. For example, .(b $>0 $>3 $1 .)b expands $1, passes that to ruleset 3, and then passes the result of ruleset 3 to ruleset 0. .pp The .b $# syntax should .i only be used in ruleset zero, a subroutine of ruleset zero, or rulesets that return decisions (e.g., check_rcpt). It causes evaluation of the ruleset to terminate immediately, and signals to .i sendmail that the address has completely resolved. The complete syntax for ruleset 0 is: .(b \fB$#\fP\fImailer\fP \fB$@\fP\fIhost\fP \fB$:\fP\fIuser\fP .)b This specifies the {mailer, host, user} 3-tuple necessary to direct the mailer. Note: the third element ( .i user ) is often also called .i address part. If the mailer is local the host part may be omitted\**. .(f \**You may want to use it for special .q "per user" extensions. For example, in the address .q jgm+foo@CMU.EDU ; the .q +foo part is not part of the user name, and is passed to the local mailer for local use. .)f The .i mailer must be a single word, but the .i host and .i user may be multi-part. If the .i mailer is the built-in IPC mailer, the .i host may be a colon-separated list of hosts that are searched in order for the first working address (exactly like MX records). The .i user is later rewritten by the mailer-specific envelope rewriting set and assigned to the .b $u macro. As a special case, if the mailer specified has the .b F=@ flag specified and the first character of the .b $: value is .q @ , the .q @ is stripped off, and a flag is set in the address descriptor that causes sendmail to not do ruleset 5 processing. .pp Normally, a rule that matches is retried, that is, the rule loops until it fails. A RHS may also be preceded by a .b $@ or a .b $: to change this behavior. A .b $@ prefix causes the ruleset to return with the remainder of the RHS as the value. A .b $: prefix causes the rule to terminate immediately, but the ruleset to continue; this can be used to avoid continued application of a rule. The prefix is stripped before continuing. .pp The .b $@ and .b $: prefixes may precede a .b $> spec; for example: .(b .ta 8n R$+ $: $>7 $1 .)b matches anything, passes that to ruleset seven, and continues; the .b $: is necessary to avoid an infinite loop. .pp Substitution occurs in the order described, that is, parameters from the LHS are substituted, hostnames are canonicalized, .q subroutines are called, and finally .b $# , .b $@ , and .b $: are processed. .sh 3 "Semantics of rewriting rule sets" .pp There are six rewriting sets that have specific semantics. Five of these are related as depicted by figure 1. .(z .hl .ie n \{\ .(c +---+ -->| 0 |-->resolved address / +---+ / +---+ +---+ / ---->| 1 |-->| S |-- +---+ / +---+ / +---+ +---+ \e +---+ addr-->| 3 |-->| D |-- --->| 4 |-->msg +---+ +---+ \e +---+ +---+ / +---+ --->| 2 |-->| R |-- +---+ +---+ .)c .\} .el \{\ .ie !"\*(.T"" \{\ .PS boxwid = 0.3i boxht = 0.3i movewid = 0.3i moveht = 0.3i linewid = 0.3i lineht = 0.3i box invis "addr"; arrow Box3: box "3" A1: arrow BoxD: box "D"; line; L1: Here C: [ C1: arrow; box "1"; arrow; box "S"; line; E1: Here move to C1 down 0.5; right C2: arrow; box "2"; arrow; box "R"; line; E2: Here ] with .w at L1 + (0.5, 0) move to C.e right 0.5 L4: arrow; box "4"; arrow; box invis "msg" line from L1 to C.C1 line from L1 to C.C2 line from C.E1 to L4 line from C.E2 to L4 move to BoxD.n up 0.6; right Box0: arrow; box "0" arrow; box invis "resolved address" width 1.3 line from 1/3 of the way between A1 and BoxD.w to Box0 .PE .\} .el .sp 2i .\} .ce Figure 1 \*- Rewriting set semantics .(c D \*- sender domain addition S \*- mailer-specific sender rewriting R \*- mailer-specific recipient rewriting .)c .hl .)z .pp Ruleset three should turn the address into .q "canonical form." This form should have the basic syntax: .(b local-part@host-domain-spec .)b Ruleset three is applied by .i sendmail before doing anything with any address. .pp If no .q @ sign is specified, then the host-domain-spec .i may be appended (box .q D in Figure 1) from the sender address (if the .b C flag is set in the mailer definition corresponding to the .i sending mailer). .pp Ruleset zero is applied after ruleset three to addresses that are going to actually specify recipients. It must resolve to a .i "{mailer, host, address}" triple. The .i mailer must be defined in the mailer definitions from the configuration file. The .i host is defined into the .b $h macro for use in the argv expansion of the specified mailer. Notice: since the envelope sender address will be used if a delivery status notification must be send, i.e., is may specify a recipient, it is also run through ruleset zero. If ruleset zero returns a temporary error .b 4xy then delivery is deferred. This can be used to temporarily disable delivery, e.g., based on the time of the day or other varying parameters. It should not be used to quarantine e-mails. .pp Rulesets one and two are applied to all sender and recipient addresses respectively. They are applied before any specification in the mailer definition. They must never resolve. .pp Ruleset four is applied to all addresses in the message. It is typically used to translate internal to external form. .pp In addition, ruleset 5 is applied to all local addresses (specifically, those that resolve to a mailer with the `F=5' flag set) that do not have aliases. This allows a last minute hook for local names. .sh 3 "Ruleset hooks" .pp A few extra rulesets are defined as .q hooks that can be defined to get special features. They are all named rulesets. The .q check_* forms all give accept/reject status; falling off the end or returning normally is an accept, and resolving to .b $#error is a reject or quarantine. Quarantining is chosen by specifying .b quarantine in the second part of the mailer triplet: .(b $#error $@ quarantine $: Reason for quarantine .)b Many of these can also resolve to the special mailer name .b $#discard ; this accepts the message as though it were successful but then discards it without delivery. Note, this mailer cannot be chosen as a mailer in ruleset 0. Note also that all .q check_* rulesets have to deal with temporary failures, especially for map lookups, themselves, i.e., they should return a temporary error code or at least they should make a proper decision in those cases. .sh 4 "check_relay" .pp The .i check_relay ruleset is called after a connection is accepted by the daemon. It is not called when sendmail is started using the .b \-bs option. It is passed .(b client.host.name $| client.host.address .)b where .b $| is a metacharacter separating the two parts. This ruleset can reject connections from various locations. Note that it only checks the connecting SMTP client IP address and hostname. It does not check for third party message relaying. The .i check_rcpt ruleset discussed below usually does third party message relay checking. .sh 4 "check_mail" .pp The .i check_mail ruleset is passed the user name parameter of the .sm "SMTP MAIL" command. It can accept or reject the address. .sh 4 "check_rcpt" .pp The .i check_rcpt ruleset is passed the user name parameter of the .sm "SMTP RCPT" command. It can accept or reject the address. .sh 4 "check_data" .pp The .i check_data ruleset is called after the .sm "SMTP DATA" command, its parameter is the number of recipients. It can accept or reject the command. .sh 4 "check_compat" .pp The .i check_compat ruleset is passed .(b sender-address $| recipient-address .)b where .b $| is a metacharacter separating the addresses. It can accept or reject mail transfer between these two addresses much like the .i checkcompat() function. Note: while other .i check_* rulesets are invoked during the SMTP mail receiption stage (i.e., in the SMTP server), .i check_compat is invoked during the mail delivery stage. .sh 4 "check_eoh" .pp The .i check_eoh ruleset is passed .(b number-of-headers $| size-of-headers .)b where .b $| is a metacharacter separating the numbers. These numbers can be used for size comparisons with the .b arith map. The ruleset is triggered after all of the headers have been read. It can be used to correlate information gathered from those headers using the .b macro storage map. One possible use is to check for a missing header. For example: .(b .ta 1.5i Kstorage macro HMessage-Id: $>CheckMessageId SCheckMessageId # Record the presence of the header R$* $: $(storage {MessageIdCheck} $@ OK $) $1 R< $+ @ $+ > $@ OK R$* $#error $: 553 Header Error Scheck_eoh # Check the macro R$* $: < $&{MessageIdCheck} > # Clear the macro for the next message R$* $: $(storage {MessageIdCheck} $) $1 # Has a Message-Id: header R< $+ > $@ OK # Allow missing Message-Id: from local mail R$* $: < $&{client_name} > R< > $@ OK R< $=w > $@ OK # Otherwise, reject the mail R$* $#error $: 553 Header Error .)b Keep in mind the Message-Id: header is not a required header and is not a guaranteed spam indicator. This ruleset is an example and should probably not be used in production. .sh 4 "check_eom" .pp The .i check_eom ruleset is called after the end of a message, its parameter is the message size. It can accept or reject the message. .sh 4 "check_etrn" .pp The .i check_etrn ruleset is passed the parameter of the .sm "SMTP ETRN" command. It can accept or reject the command. .sh 4 "check_expn" .pp The .i check_expn ruleset is passed the user name parameter of the .sm "SMTP EXPN" command. It can accept or reject the address. .sh 4 "check_vrfy" .pp The .i check_vrfy ruleset is passed the user name parameter of the .sm "SMTP VRFY" command. It can accept or reject the command. .sh 4 "trust_auth" .pp The .i trust_auth ruleset is passed the AUTH= parameter of the .sm "SMTP MAIL" command. It is used to determine whether this value should be trusted. In order to make this decision, the ruleset may make use of the various .b ${auth_*} macros. If the ruleset does resolve to the .q error mailer the AUTH= parameter is not trusted and hence not passed on to the next relay. .sh 4 "tls_client" .pp The .i tls_client ruleset is called when sendmail acts as server, after a STARTTLS command has been issued, and from .i check_mail. The parameter is the value of .b ${verify} and STARTTLS or MAIL, respectively. If the ruleset does resolve to the .q error mailer, the appropriate error code is returned to the client. .sh 4 "tls_server" .pp The .i tls_server ruleset is called when sendmail acts as client after a STARTTLS command (should) have been issued. The parameter is the value of .b ${verify} . If the ruleset does resolve to the .q error mailer, the connection is aborted (treated as non-deliverable with a permanent or temporary error). .sh 4 "tls_rcpt" .pp The .i tls_rcpt ruleset is called each time before a RCPT TO command is sent. The parameter is the current recipient. If the ruleset does resolve to the .q error mailer, the RCPT TO command is suppressed (treated as non-deliverable with a permanent or temporary error). This ruleset allows to require encryption or verification of the recipient's MTA even if the mail is somehow redirected to another host. For example, sending mail to .i luke@endmail.org may get redirected to a host named .i death.star and hence the tls_server ruleset won't apply. By introducing per recipient restrictions such attacks (e.g., via DNS spoofing) can be made impossible. See .i cf/README how this ruleset can be used. .sh 4 "srv_features" .pp The .i srv_features ruleset is called with the connecting client's host name when a client connects to sendmail. This ruleset should return .b $# followed by a list of options (single characters delimited by white space). If the return value starts with anything else it is silently ignored. Generally upper case characters turn off a feature while lower case characters turn it on. Option `S' causes the server not to offer STARTTLS, which is useful to interact with MTAs/MUAs that have broken STARTTLS implementations by simply not offering it. `V' turns off the request for a client certificate during the TLS handshake. Options `A' and `P' suppress SMTP AUTH and PIPELINING, respectively. `c' is the equivalent to AuthOptions=p, i.e., it doesn't permit mechanisms susceptible to simple passive attack (e.g., PLAIN, LOGIN), unless a security layer is active. Option `l' requires SMTP AUTH for a connection. Options 'B', 'D', 'E', and 'X' suppress SMTP VERB, DSN, ETRN, and EXPN, respectively. .(b .ta 9n A Do not offer AUTH a Offer AUTH (default) B Do not offer VERB b Offer VERB (default) C Do not require security layer for plaintext AUTH (default) c Require security layer for plaintext AUTH D Do not offer DSN d Offer DSN (default) E Do not offer ETRN e Offer ETRN (default) L Do not require AUTH (default) l Require AUTH P Do not offer PIPELINING p Offer PIPELINING (default) S Do not offer STARTTLS s Offer STARTTLS (default) V Do not request a client certificate v Request a client certificate (default) X Do not offer EXPN x Offer EXPN (default) .)b Note: the entries marked as ``(default)'' may require that some configuration has been made, e.g., SMTP AUTH is only available if properly configured. Moreover, many options can be changed on a global basis via other settings as explained in this document, e.g., via DaemonPortOptions. .pp The ruleset may return `$#temp' to indicate that there is a temporary problem determining the correct features, e.g., if a map is unavailable. In that case, the SMTP server issues a temporary failure and does not accept email. .sh 4 "try_tls" .pp The .i try_tls ruleset is called when sendmail connects to another MTA. If the ruleset does resolve to the .q error mailer, sendmail does not try STARTTLS even if it is offered. This is useful to interact with MTAs that have broken STARTTLS implementations by simply not using it. .sh 4 "authinfo" .pp The .i authinfo ruleset is called when sendmail tries to authenticate to another MTA. It should return .b $# followed by a list of tokens that are used for SMTP AUTH. If the return value starts with anything else it is silently ignored. Each token is a tagged string of the form: "TDstring" (including the quotes), where .(b .ta 9n T Tag which describes the item D Delimiter: ':' simple text follows '=' string is base64 encoded string Value of the item .)b Valid values for the tag are: .(b .ta 9n U user (authorization) id I authentication id P password R realm M list of mechanisms delimited by spaces .)b If this ruleset is defined, the option .b DefaultAuthInfo is ignored (even if the ruleset does not return a ``useful'' result). .sh 4 "queuegroup" .pp The .i queuegroup ruleset is used to map a recipient address to a queue group name. The input for the ruleset is a recipient address as specified by the .sm "SMTP RCPT" command. The ruleset should return .b $# followed by the name of a queue group. If the return value starts with anything else it is silently ignored. See the section about ``Queue Groups and Queue Directories'' for further information. .sh 4 "greet_pause" .pp The .i greet_pause ruleset is used to specify the amount of time to pause before sending the initial SMTP 220 greeting. If any traffic is received during that pause, an SMTP 554 rejection response is given instead of the 220 greeting and all SMTP commands are rejected during that connection. This helps protect sites from open proxies and SMTP slammers. The ruleset should return .b $# followed by the number of milliseconds (thousandths of a second) to pause. If the return value starts with anything else or is not a number, it is silently ignored. Note: this ruleset is not invoked (and hence the feature is disabled) when the smtps (SMTP over SSL) is used, i.e., the .i s modifier is set for the daemon via .b DaemonPortOptions , because in this case the SSL handshake is performed before the greeting is sent. .sh 3 "IPC mailers" .pp Some special processing occurs if the ruleset zero resolves to an IPC mailer (that is, a mailer that has .q [IPC] listed as the Path in the .b M configuration line. The host name passed after .q $@ has MX expansion performed if not delivering via a named socket; this looks the name up in DNS to find alternate delivery sites. .pp The host name can also be provided as a dotted quad or an IPv6 address in square brackets; for example: .(b [128.32.149.78] .)b or .(b [IPv6:2002:c0a8:51d2::23f4] .)b This causes direct conversion of the numeric value to an IP host address. .pp The host name passed in after the .q $@ may also be a colon-separated list of hosts. Each is separately MX expanded and the results are concatenated to make (essentially) one long MX list. The intent here is to create .q fake MX records that are not published in DNS for private internal networks. .pp As a final special case, the host name can be passed in as a text string in square brackets: .(b [ucbvax.berkeley.edu] .)b This form avoids the MX mapping. .b N.B.: .i This is intended only for situations where you have a network firewall or other host that will do special processing for all your mail, so that your MX record points to a gateway machine; this machine could then do direct delivery to machines within your local domain. Use of this feature directly violates RFC 1123 section 5.3.5: it should not be used lightly. .r .sh 2 "D \*- Define Macro" .pp Macros are named with a single character or with a word in {braces}. The names ``x'' and ``{x}'' denote the same macro for every single character ``x''. Single character names may be selected from the entire ASCII set, but user-defined macros should be selected from the set of upper case letters only. Lower case letters and special symbols are used internally. Long names beginning with a lower case letter or a punctuation character are reserved for use by sendmail, so user-defined long macro names should begin with an upper case letter. .pp The syntax for macro definitions is: .(b F .b D \c .i x\|val .)b where .i x is the name of the macro (which may be a single character or a word in braces) and .i val is the value it should have. There should be no spaces given that do not actually belong in the macro value. .pp Macros are interpolated using the construct .b $ \c .i x , where .i x is the name of the macro to be interpolated. This interpolation is done when the configuration file is read, except in .b M lines. The special construct .b $& \c .i x can be used in .b R lines to get deferred interpolation. .pp Conditionals can be specified using the syntax: .(b $?x text1 $| text2 $. .)b This interpolates .i text1 if the macro .b $x is set and non-null, and .i text2 otherwise. The .q else (\c .b $| ) clause may be omitted. .pp The following macros are defined and/or used internally by .i sendmail for interpolation into argv's for mailers or for other contexts. The ones marked \(dg are information passed into sendmail\**, .(f \**As of version 8.6, all of these macros have reasonable defaults. Previous versions required that they be defined. .)f the ones marked \(dd are information passed both in and out of sendmail, and the unmarked macros are passed out of sendmail but are not otherwise used internally. These macros are: .nr ii 5n .ip $a The origination date in RFC 822 format. This is extracted from the Date: line. .ip $b The current date in RFC 822 format. .ip $c The hop count. This is a count of the number of Received: lines plus the value of the .b \-h command line flag. .ip $d The current date in UNIX (ctime) format. .ip $e\(dg (Obsolete; use SmtpGreetingMessage option instead.) The SMTP entry message. This is printed out when SMTP starts up. The first word must be the .b $j macro as specified by RFC 821. Defaults to .q "$j Sendmail $v ready at $b" . Commonly redefined to include the configuration version number, e.g., .q "$j Sendmail $v/$Z ready at $b" .ip $f The envelope sender (from) address. .ip $g The sender address relative to the recipient. For example, if .b $f is .q foo , .b $g will be .q host!foo , .q foo@host.domain , or whatever is appropriate for the receiving mailer. .ip $h The recipient host. This is set in ruleset 0 from the $@ field of a parsed address. .ip $i The queue id, e.g., .q f344MXxp018717 . .ip $j\(dd The \*(lqofficial\*(rq domain name for this site. This is fully qualified if the full qualification can be found. It .i must be redefined to be the fully qualified domain name if your system is not configured so that information can find it automatically. .ip $k The UUCP node name (from the uname system call). .ip $l\(dg (Obsolete; use UnixFromLine option instead.) The format of the UNIX from line. Unless you have changed the UNIX mailbox format, you should not change the default, which is .q "From $g $d" . .ip $m The domain part of the \fIgethostname\fP return value. Under normal circumstances, .b $j is equivalent to .b $w.$m . .ip $n\(dg The name of the daemon (for error messages). Defaults to .q MAILER-DAEMON . .ip $o\(dg (Obsolete: use OperatorChars option instead.) The set of \*(lqoperators\*(rq in addresses. A list of characters which will be considered tokens and which will separate tokens when doing parsing. For example, if .q @ were in the .b $o macro, then the input .q a@b would be scanned as three tokens: .q a, .q @, and .q b. Defaults to .q ".:@[]" , which is the minimum set necessary to do RFC 822 parsing; a richer set of operators is .q ".:%@!/[]" , which adds support for UUCP, the %-hack, and X.400 addresses. .ip $p Sendmail's process id. .ip $q\(dg Default format of sender address. The .b $q macro specifies how an address should appear in a message when it is defaulted. Defaults to .q "<$g>" . It is commonly redefined to be .q "$?x$x <$g>$|$g$." or .q "$g$?x ($x)$." , corresponding to the following two formats: .(b Eric Allman eric@CS.Berkeley.EDU (Eric Allman) .)b .i Sendmail properly quotes names that have special characters if the first form is used. .ip $r Protocol used to receive the message. Set from the .b \-p command line flag or by the SMTP server code. .ip $s Sender's host name. Set from the .b \-p command line flag or by the SMTP server code (in which case it is set to the EHLO/HELO parameter). .ip $t A numeric representation of the current time in the format YYYYMMDDHHmm (4 digit year 1900-9999, 2 digit month 01-12, 2 digit day 01-31, 2 digit hours 00-23, 2 digit minutes 00-59). .ip $u The recipient user. .ip $v The version number of the .i sendmail binary. .ip $w\(dd The hostname of this site. This is the root name of this host (but see below for caveats). .ip $x The full name of the sender. .ip $z The home directory of the recipient. .ip $_ The validated sender address. See also .b ${client_resolve} . .ip ${addr_type} The type of the address which is currently being rewritten. This macro contains up to three characters, the first is either `e' or `h' for envelope/header address, the second is a space, and the third is either `s' or `r' for sender/recipient address. .ip ${alg_bits} The maximum keylength (in bits) of the symmetric encryption algorithm used for a TLS connection. This may be less than the effective keylength, which is stored in .b ${cipher_bits} , for ``export controlled'' algorithms. .ip ${auth_authen} The client's authentication credentials as determined by authentication (only set if successful). The format depends on the mechanism used, it might be just `user', or `user@realm', or something similar (SMTP AUTH only). .ip ${auth_author} The authorization identity, i.e. the AUTH= parameter of the .sm "SMTP MAIL" command if supplied. .ip ${auth_type} The mechanism used for SMTP authentication (only set if successful). .ip ${auth_ssf} The keylength (in bits) of the symmetric encryption algorithm used for the security layer of a SASL mechanism. .ip ${bodytype} The message body type (7BIT or 8BITMIME), as determined from the envelope. .ip ${cert_issuer} The DN (distinguished name) of the CA (certificate authority) that signed the presented certificate (the cert issuer) (STARTTLS only). .ip ${cert_md5} The MD5 hash of the presented certificate (STARTTLS only). .ip ${cert_subject} The DN of the presented certificate (called the cert subject) (STARTTLS only). .ip ${cipher} The cipher suite used for the connection, e.g., EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CBC-SHA, DES-CBC-MD5, DES-CBC3-SHA (STARTTLS only). .ip ${cipher_bits} The effective keylength (in bits) of the symmetric encryption algorithm used for a TLS connection. .ip ${client_addr} The IP address of the SMTP client. IPv6 addresses are tagged with "IPv6:" before the address. Defined in the SMTP server only. .ip ${client_connections} The number of open connections in the SMTP server for the client IP address. .ip ${client_flags} The flags specified by the Modifier= part of .b ClientPortOptions where flags are separated from each other by spaces and upper case flags are doubled. That is, Modifier=hA will be represented as "h AA" in .b ${client_flags} , which is required for testing the flags in rulesets. .ip ${client_name} The host name of the SMTP client. This may be the client's bracketed IP address in the form [ nnn.nnn.nnn.nnn ] for IPv4 and [ IPv6:nnnn:...:nnnn ] for IPv6 if the client's IP address is not resolvable, or if it is resolvable but the IP address of the resolved hostname doesn't match the original IP address. Defined in the SMTP server only. See also .b ${client_resolve} . .ip ${client_port} The port number of the SMTP client. Defined in the SMTP server only. .ip ${client_ptr} The result of the PTR lookup for the client IP address. Note: this is the same as .b ${client_name} if and only if .b ${client_resolve} is OK. Defined in the SMTP server only. .ip ${client_rate} The number of incoming connections for the client IP address over the time interval specified by ConnectionRateWindowSize. .ip ${client_resolve} Holds the result of the resolve call for .b ${client_name} . Possible values are: .(b .ta 10n OK resolved successfully FAIL permanent lookup failure FORGED forward lookup doesn't match reverse lookup TEMP temporary lookup failure .)b Defined in the SMTP server only. .i sendmail performs a hostname lookup on the IP address of the connecting client. Next the IP addresses of that hostname are looked up. If the client IP address does not appear in that list, then the hostname is maybe forged. This is reflected as the value FORGED for .b ${client_resolve} and it also shows up in .b $_ as "(may be forged)". .ip ${cn_issuer} The CN (common name) of the CA that signed the presented certificate (STARTTLS only). Note: if the CN cannot be extracted properly it will be replaced by one of these strings based on the encountered error: .(b .ta 25n BadCertificateContainsNUL CN contains a NUL character BadCertificateTooLong CN is too long BadCertificateUnknown CN could not be extracted .)b In the last case, some other (unspecific) error occurred. .ip ${cn_subject} The CN (common name) of the presented certificate (STARTTLS only). See .b ${cn_issuer} for possible replacements. .ip ${currHeader} Header value as quoted string (possibly truncated to .b MAXNAME ). This macro is only available in header check rulesets. .ip ${daemon_addr} The IP address the daemon is listening on for connections. .ip ${daemon_family} The network family if the daemon is accepting network connections. Possible values include .q inet , .q inet6 , .q iso , .q ns , .q x.25 .ip ${daemon_flags} The flags for the daemon as specified by the Modifier= part of .b DaemonPortOptions whereby the flags are separated from each other by spaces, and upper case flags are doubled. That is, Modifier=Ea will be represented as "EE a" in .b ${daemon_flags} , which is required for testing the flags in rulesets. .ip ${daemon_info} Some information about a daemon as a text string. For example, .q SMTP+queueing@00:30:00 . .ip ${daemon_name} The name of the daemon from .b DaemonPortOptions Name= suboption. If this suboption is not set, "Daemon#", where # is the daemon number, is used. .ip ${daemon_port} The port the daemon is accepting connection on. Unless .b DaemonPortOptions is set, this will most likely be .q 25 . .ip ${deliveryMode} The current delivery mode sendmail is using. It is initially set to the value of the .b DeliveryMode option. .ip ${envid} The envelope id parameter (ENVID=) passed to sendmail as part of the envelope. .ip ${hdrlen} The length of the header value which is stored in ${currHeader} (before possible truncation). If this value is greater than or equal to .b MAXNAME the header has been truncated. .ip ${hdr_name} The name of the header field for which the current header check ruleset has been called. This is useful for a default header check ruleset to get the name of the header; the macro is only available in header check rulesets. .ip ${if_addr} The IP address of the interface of an incoming connection unless it is in the loopback net. IPv6 addresses are tagged with "IPv6:" before the address. .ip ${if_addr_out} The IP address of the interface of an outgoing connection unless it is in the loopback net. IPv6 addresses are tagged with "IPv6:" before the address. .ip ${if_family} The IP family of the interface of an incoming connection unless it is in the loopback net. .ip ${if_family_out} The IP family of the interface of an outgoing connection unless it is in the loopback net. .ip ${if_name} The hostname associated with the interface of an incoming connection. This macro can be used for SmtpGreetingMessage and HReceived for virtual hosting. For example: .(b O SmtpGreetingMessage=$?{if_name}${if_name}$|$j$. MTA .)b .ip ${if_name_out} The name of the interface of an outgoing connection. .ip ${load_avg} The current load average. .ip ${mail_addr} The address part of the resolved triple of the address given for the .sm "SMTP MAIL" command. Defined in the SMTP server only. .ip ${mail_host} The host from the resolved triple of the address given for the .sm "SMTP MAIL" command. Defined in the SMTP server only. .ip ${mail_mailer} The mailer from the resolved triple of the address given for the .sm "SMTP MAIL" command. Defined in the SMTP server only. .ip ${msg_id} The value of the Message-Id: header. .ip ${msg_size} The value of the SIZE= parameter, i.e., usually the size of the message (in an ESMTP dialogue), before the message has been collected, thereafter the message size as computed by .i sendmail (and can be used in check_compat). .ip ${nbadrcpts} The number of bad recipients for a single message. .ip ${nrcpts} The number of validated recipients for a single message. Note: since recipient validation happens after .i check_rcpt has been called, the value in this ruleset is one less than what might be expected. .ip ${ntries} The number of delivery attempts. .ip ${opMode} The current operation mode (from the .b \-b flag). .ip ${quarantine} The quarantine reason for the envelope, if it is quarantined. .ip ${queue_interval} The queue run interval given by the .b \-q flag. For example, .b \-q30m would set .b ${queue_interval} to .q 00:30:00 . .ip ${rcpt_addr} The address part of the resolved triple of the address given for the .sm "SMTP RCPT" command. Defined in the SMTP server only after a RCPT command. .ip ${rcpt_host} The host from the resolved triple of the address given for the .sm "SMTP RCPT" command. Defined in the SMTP server only after a RCPT command. .ip ${rcpt_mailer} The mailer from the resolved triple of the address given for the .sm "SMTP RCPT" command. Defined in the SMTP server only after a RCPT command. .ip ${server_addr} The address of the server of the current outgoing SMTP connection. For LMTP delivery the macro is set to the name of the mailer. .ip ${server_name} The name of the server of the current outgoing SMTP or LMTP connection. .ip ${time} The output of the .i time (3) function, i.e., the number of seconds since 0 hours, 0 minutes, 0 seconds, January 1, 1970, Coordinated Universal Time (UTC). .ip ${tls_version} The TLS/SSL version used for the connection, e.g., TLSv1, SSLv3, SSLv2; defined after STARTTLS has been used. .ip ${total_rate} The total number of incoming connections over the time interval specified by ConnectionRateWindowSize. .ip ${verify} The result of the verification of the presented cert; only defined after STARTTLS has been used (or attempted). Possible values are: .(b .ta 13n OK verification succeeded. NO no cert presented. NOT no cert requested. FAIL cert presented but could not be verified, e.g., the signing CA is missing. NONE STARTTLS has not been performed. TEMP temporary error occurred. PROTOCOL some protocol error occurred at the ESMTP level (not TLS). SOFTWARE STARTTLS handshake failed, which is a fatal error for this session, the e-mail will be queued. .)b .pp There are three types of dates that can be used. The .b $a and .b $b macros are in RFC 822 format; .b $a is the time as extracted from the .q Date: line of the message (if there was one), and .b $b is the current date and time (used for postmarks). If no .q Date: line is found in the incoming message, .b $a is set to the current time also. The .b $d macro is equivalent to the .b $b macro in UNIX (ctime) format. .pp The macros .b $w , .b $j , and .b $m are set to the identity of this host. .i Sendmail tries to find the fully qualified name of the host if at all possible; it does this by calling .i gethostname (2) to get the current hostname and then passing that to .i gethostbyname (3) which is supposed to return the canonical version of that host name.\** .(f \**For example, on some systems .i gethostname might return .q foo which would be mapped to .q foo.bar.com by .i gethostbyname . .)f Assuming this is successful, .b $j is set to the fully qualified name and .b $m is set to the domain part of the name (everything after the first dot). The .b $w macro is set to the first word (everything before the first dot) if you have a level 5 or higher configuration file; otherwise, it is set to the same value as .b $j . If the canonification is not successful, it is imperative that the config file set .b $j to the fully qualified domain name\**. .(f \**Older versions of sendmail didn't pre-define .b $j at all, so up until 8.6, config files .i always had to define .b $j . .)f .pp The .b $f macro is the id of the sender as originally determined; when mailing to a specific host the .b $g macro is set to the address of the sender .ul relative to the recipient. For example, if I send to .q bollard@matisse.CS.Berkeley.EDU from the machine .q vangogh.CS.Berkeley.EDU the .b $f macro will be .q eric and the .b $g macro will be .q eric@vangogh.CS.Berkeley.EDU. .pp The .b $x macro is set to the full name of the sender. This can be determined in several ways. It can be passed as flag to .i sendmail . It can be defined in the .sm NAME environment variable. The third choice is the value of the .q Full-Name: line in the header if it exists, and the fourth choice is the comment field of a .q From: line. If all of these fail, and if the message is being originated locally, the full name is looked up in the .i /etc/passwd file. .pp When sending, the .b $h , .b $u , and .b $z macros get set to the host, user, and home directory (if local) of the recipient. The first two are set from the .b $@ and .b $: part of the rewriting rules, respectively. .pp The .b $p and .b $t macros are used to create unique strings (e.g., for the .q Message-Id: field). The .b $i macro is set to the queue id on this host; if put into the timestamp line it can be extremely useful for tracking messages. The .b $v macro is set to be the version number of .i sendmail ; this is normally put in timestamps and has been proven extremely useful for debugging. .pp The .b $c field is set to the .q "hop count," i.e., the number of times this message has been processed. This can be determined by the .b \-h flag on the command line or by counting the timestamps in the message. .pp The .b $r and .b $s fields are set to the protocol used to communicate with .i sendmail and the sending hostname. They can be set together using the .b \-p command line flag or separately using the .b \-M or .b \-oM flags. .pp The .b $_ is set to a validated sender host name. If the sender is running an RFC 1413 compliant IDENT server and the receiver has the IDENT protocol turned on, it will include the user name on that host. .pp The .b ${client_name} , .b ${client_addr} , and .b ${client_port} macros are set to the name, address, and port number of the SMTP client who is invoking .i sendmail as a server. These can be used in the .i check_* rulesets (using the .b $& deferred evaluation form, of course!). .sh 2 "C and F \*- Define Classes" .pp Classes of phrases may be defined to match on the left hand side of rewriting rules, where a .q phrase is a sequence of characters that does not contain space characters. For example a class of all local names for this site might be created so that attempts to send to oneself can be eliminated. These can either be defined directly in the configuration file or read in from another file. Classes are named as a single letter or a word in {braces}. Class names beginning with lower case letters and special characters are reserved for system use. Classes defined in config files may be given names from the set of upper case letters for short names or beginning with an upper case letter for long names. .pp The syntax is: .(b F .b C \c .i c\|phrase1 .i phrase2... .br .b F \c .i c\|file .br .b F \c .i c\||program .br .b F \c .i c\|[mapkey]@mapclass:mapspec .)b The first form defines the class .i c to match any of the named words. If .i phrase1 or .i phrase2 is another class, e.g., .i $=S , the contents of class .i S are added to class .i c . It is permissible to split them among multiple lines; for example, the two forms: .(b CHmonet ucbmonet .)b and .(b CHmonet CHucbmonet .)b are equivalent. The ``F'' forms read the elements of the class .i c from the named .i file , .i program , or .i "map specification" . Each element should be listed on a separate line. To specify an optional file, use ``\-o'' between the class name and the file name, e.g., .(b Fc \-o /path/to/file .)b If the file can't be used, .i sendmail will not complain but silently ignore it. The map form should be an optional map key, an at sign, and a map class followed by the specification for that map. Examples include: .(b F{VirtHosts}@ldap:\-k (&(objectClass=virtHosts)(host=*)) \-v host F{MyClass}foo@hash:/etc/mail/classes .)b will fill the class .b $={VirtHosts} from an LDAP map lookup and .b $={MyClass} from a hash database map lookup of the .b foo . There is also a built-in schema that can be accessed by only specifying: .(b F{\c .i ClassName }@LDAP .)b This will tell sendmail to use the default schema: .(b \-k (&(objectClass=sendmailMTAClass) (sendmailMTAClassName=\c .i ClassName ) (|(sendmailMTACluster=${sendmailMTACluster}) (sendmailMTAHost=$j))) \-v sendmailMTAClassValue .)b Note that the lookup is only done when sendmail is initially started. .pp Elements of classes can be accessed in rules using .b $= or .b $~ . The .b $~ (match entries not in class) only matches a single word; multi-word entries in the class are ignored in this context. .pp Some classes have internal meaning to .i sendmail : .nr ii 0.5i .\".ip $=b .\"A set of Content-Types that will not have the newline character .\"translated to CR-LF before encoding into base64 MIME. .\"The class can have major times .\"(e.g., .\".q image ) .\"or full types .\"(such as .\".q application/octet-stream ). .\"The class is initialized with .\".q application/octet-stream , .\".q image , .\".q audio , .\"and .\".q video . .ip $=e contains the Content-Transfer-Encodings that can be 8\(->7 bit encoded. It is predefined to contain .q 7bit , .q 8bit , and .q binary . .ip $=k set to be the same as .b $k , that is, the UUCP node name. .ip $=m set to the set of domains by which this host is known, initially just .b $m . .ip $=n can be set to the set of MIME body types that can never be eight to seven bit encoded. It defaults to .q multipart/signed . Message types .q message/* and .q multipart/* are never encoded directly. Multipart messages are always handled recursively. The handling of message/* messages are controlled by class .b $=s . .ip $=q A set of Content-Types that will never be encoded as base64 (if they have to be encoded, they will be encoded as quoted-printable). It can have primary types (e.g., .q text ) or full types (such as .q text/plain ). -The class is initialized to have -.q text/plain -only. .ip $=s contains the set of subtypes of message that can be treated recursively. By default it contains only .q rfc822 . Other .q message/* types cannot be 8\(->7 bit encoded. If a message containing eight bit data is sent to a seven bit host, and that message cannot be encoded into seven bits, it will be stripped to 7 bits. .ip $=t set to the set of trusted users by the .b T configuration line. If you want to read trusted users from a file, use .b Ft \c .i /file/name . .ip $=w set to be the set of all names this host is known by. This can be used to match local hostnames. .ip $={persistentMacros} set to the macros that should be saved across queue runs. Care should be taken when adding macro names to this class. .pp .i Sendmail can be compiled to allow a .i scanf (3) string on the .b F line. This lets you do simplistic parsing of text files. For example, to read all the user names in your system .i /etc/passwd file into a class, use .(b FL/etc/passwd %[^:] .)b which reads every line up to the first colon. .sh 2 "M \*- Define Mailer" .pp Programs and interfaces to mailers are defined in this line. The format is: .(b F .b M \c .i name , {\c .i field =\c .i value \|}* .)b where .i name is the name of the mailer (used internally only) and the .q field=name pairs define attributes of the mailer. Fields are: .(b .ta 1i Path The pathname of the mailer Flags Special flags for this mailer Sender Rewriting set(s) for sender addresses Recipient Rewriting set(s) for recipient addresses recipients Maximum number of recipients per connection Argv An argument vector to pass to this mailer Eol The end-of-line string for this mailer Maxsize The maximum message length to this mailer maxmessages The maximum message deliveries per connection Linelimit The maximum line length in the message body Directory The working directory for the mailer Userid The default user and group id to run as Nice The nice(2) increment for the mailer Charset The default character set for 8-bit characters Type Type information for DSN diagnostics Wait The maximum time to wait for the mailer Queuegroup The default queue group for the mailer / The root directory for the mailer .)b Only the first character of the field name is checked (it's case-sensitive). .pp The following flags may be set in the mailer description. Any other flags may be used freely to conditionally assign headers to messages destined for particular mailers. Flags marked with \(dg are not interpreted by the .i sendmail binary; these are the conventionally used to correlate to the flags portion of the .b H line. Flags marked with \(dd apply to the mailers for the sender address rather than the usual recipient mailers. .nr ii 4n .ip a Run Extended SMTP (ESMTP) protocol (defined in RFCs 1869, 1652, and 1870). This flag defaults on if the SMTP greeting message includes the word .q ESMTP . .ip A Look up the user (address) part of the resolved mailer triple, in the alias database. Normally this is only set for local mailers. .ip b Force a blank line on the end of a message. This is intended to work around some stupid versions of /bin/mail that require a blank line, but do not provide it themselves. It would not normally be used on network mail. .ip B Strip leading backslashes (\e) off of the address; this is a subset of the functionality of the .b s flag. .ip c Do not include comments in addresses. This should only be used if you have to work around a remote mailer that gets confused by comments. This strips addresses of the form .q "Phrase
" or .q "address (Comment)" down to just .q address . .ip C\(dd If mail is .i received from a mailer with this flag set, any addresses in the header that do not have an at sign (\c .q @ ) after being rewritten by ruleset three will have the .q @domain clause from the sender envelope address tacked on. This allows mail with headers of the form: .(b From: usera@hosta To: userb@hostb, userc .)b to be rewritten as: .(b From: usera@hosta To: userb@hostb, userc@hosta .)b automatically. However, it doesn't really work reliably. .ip d Do not include angle brackets around route-address syntax addresses. This is useful on mailers that are going to pass addresses to a shell that might interpret angle brackets as I/O redirection. However, it does not protect against other shell metacharacters. Therefore, passing addresses to a shell should not be considered secure. .ip D\(dg This mailer wants a .q Date: header line. .ip e This mailer is expensive to connect to, so try to avoid connecting normally; any necessary connection will occur during a queue run. See also option .b HoldExpensive . .ip E Escape lines beginning with .q From\0 in the message with a `>' sign. .ip f The mailer wants a .b \-f .i from flag, but only if this is a network forward operation (i.e., the mailer will give an error if the executing user does not have special permissions). .ip F\(dg This mailer wants a .q From: header line. .ip g Normally, .i sendmail sends internally generated email (e.g., error messages) using the null return address as required by RFC 1123. However, some mailers don't accept a null return address. If necessary, you can set the .b g flag to prevent .i sendmail from obeying the standards; error messages will be sent as from the MAILER-DAEMON (actually, the value of the .b $n macro). .ip h Upper case should be preserved in host names (the $@ portion of the mailer triplet resolved from ruleset 0) for this mailer. .ip i Do User Database rewriting on envelope sender address. .ip I This mailer will be speaking SMTP to another .i sendmail \*- as such it can use special protocol features. This flag should not be used except for debugging purposes because it uses .b VERB as SMTP command. .ip j Do User Database rewriting on recipients as well as senders. .ip k Normally when .i sendmail connects to a host via SMTP, it checks to make sure that this isn't accidently the same host name as might happen if .i sendmail is misconfigured or if a long-haul network interface is set in loopback mode. This flag disables the loopback check. It should only be used under very unusual circumstances. .ip K Currently unimplemented. Reserved for chunking. .ip l This mailer is local (i.e., final delivery will be performed). .ip L Limit the line lengths as specified in RFC 821. This deprecated option should be replaced by the .b L= mail declaration. For historic reasons, the .b L flag also sets the .b 7 flag. .ip m This mailer can send to multiple users on the same host in one transaction. When a .b $u macro occurs in the .i argv part of the mailer definition, that field will be repeated as necessary for all qualifying users. Removing this flag can defeat duplicate supression on a remote site as each recipient is sent in a separate transaction. .ip M\(dg This mailer wants a .q Message-Id: header line. .ip n Do not insert a UNIX-style .q From line on the front of the message. .ip o Always run as the owner of the recipient mailbox. Normally .i sendmail runs as the sender for locally generated mail or as .q daemon (actually, the user specified in the .b u option) when delivering network mail. The normal behavior is required by most local mailers, which will not allow the envelope sender address to be set unless the mailer is running as daemon. This flag is ignored if the .b S flag is set. .ip p Use the route-addr style reverse-path in the SMTP .q "MAIL FROM:" command rather than just the return address; although this is required in RFC 821 section 3.1, many hosts do not process reverse-paths properly. Reverse-paths are officially discouraged by RFC 1123. .ip P\(dg This mailer wants a .q Return-Path: line. .ip q When an address that resolves to this mailer is verified (SMTP VRFY command), generate 250 responses instead of 252 responses. This will imply that the address is local. .ip r Same as .b f , but sends a .b \-r flag. .ip R Open SMTP connections from a .q secure port. Secure ports aren't (secure, that is) except on UNIX machines, so it is unclear that this adds anything. .i sendmail must be running as root to be able to use this flag. .ip s Strip quote characters (" and \e) off of the address before calling the mailer. .ip S Don't reset the userid before calling the mailer. This would be used in a secure environment where .i sendmail ran as root. This could be used to avoid forged addresses. If the .b U= field is also specified, this flag causes the effective user id to be set to that user. .ip u Upper case should be preserved in user names for this mailer. Standards require preservation of case in the local part of addresses, except for those address for which your system accepts responsibility. RFC 2142 provides a long list of addresses which should be case insensitive. If you use this flag, you may be violating RFC 2142. Note that postmaster is always treated as a case insensitive address regardless of this flag. .ip U This mailer wants UUCP-style .q From lines with the ugly .q "remote from " on the end. .ip w The user must have a valid account on this machine, i.e., .i getpwnam must succeed. If not, the mail is bounced. See also the .b MailBoxDatabase option. This is required to get .q \&.forward capability. .ip W Ignore long term host status information (see Section "Persistent Host Status Information"). .ip x\(dg This mailer wants a .q Full-Name: header line. .ip X This mailer wants to use the hidden dot algorithm as specified in RFC 821; basically, any line beginning with a dot will have an extra dot prepended (to be stripped at the other end). This insures that lines in the message containing a dot will not terminate the message prematurely. .ip z Run Local Mail Transfer Protocol (LMTP) between .i sendmail and the local mailer. This is a variant on SMTP defined in RFC 2033 that is specifically designed for delivery to a local mailbox. .ip Z Apply DialDelay (if set) to this mailer. .ip 0 Don't look up MX records for hosts sent via SMTP/LMTP. Do not apply .b FallbackMXhost either. .ip 1 Don't send null characters ('\\0') to this mailer. .ip 2 Don't use ESMTP even if offered; this is useful for broken systems that offer ESMTP but fail on EHLO (without recovering when HELO is tried next). .ip 3 Extend the list of characters converted to =XX notation when converting to Quoted-Printable to include those that don't map cleanly between ASCII and EBCDIC. Useful if you have IBM mainframes on site. .ip 5 If no aliases are found for this address, pass the address through ruleset 5 for possible alternate resolution. This is intended to forward the mail to an alternate delivery spot. .ip 6 Strip headers to seven bits. .ip 7 Strip all output to seven bits. This is the default if the .b L flag is set. Note that clearing this option is not sufficient to get full eight bit data passed through .i sendmail . If the .b 7 option is set, this is essentially always set, since the eighth bit was stripped on input. Note that this option will only impact messages that didn't have 8\(->7 bit MIME conversions performed. .ip 8 If set, it is acceptable to send eight bit data to this mailer; the usual attempt to do 8\(->7 bit MIME conversions will be bypassed. .ip 9 If set, do .i limited 7\(->8 bit MIME conversions. These conversions are limited to text/plain data. .ip : Check addresses to see if they begin .q :include: ; if they do, convert them to the .q *include* mailer. .ip | Check addresses to see if they begin with a `|'; if they do, convert them to the .q prog mailer. .ip / Check addresses to see if they begin with a `/'; if they do, convert them to the .q *file* mailer. .ip @ Look up addresses in the user database. .ip % Do not attempt delivery on initial receipt of a message or on queue runs unless the queued message is selected using one of the -qI/-qR/-qS queue run modifiers or an ETRN request. .pp Configuration files prior to level 6 assume the `A', `w', `5', `:', `|', `/', and `@' options on the mailer named .q local . .pp The mailer with the special name .q error can be used to generate a user error. The (optional) host field is an exit status to be returned, and the user field is a message to be printed. The exit status may be numeric or one of the values USAGE, NOUSER, NOHOST, UNAVAILABLE, SOFTWARE, TEMPFAIL, PROTOCOL, or CONFIG to return the corresponding EX_ exit code, or an enhanced error code as described in RFC 1893, .ul Enhanced Mail System Status Codes. For example, the entry: .(b $#error $@ NOHOST $: Host unknown in this domain .)b on the RHS of a rule will cause the specified error to be generated and the .q "Host unknown" exit status to be returned if the LHS matches. This mailer is only functional in rulesets 0, 5, or one of the check_* rulesets. The host field can also contain the special token .b quarantine which instructs sendmail to quarantine the current message. .pp The mailer with the special name .q discard causes any mail sent to it to be discarded but otherwise treated as though it were successfully delivered. This mailer cannot be used in ruleset 0, only in the various address checking rulesets. .pp The mailer named .q local .i must be defined in every configuration file. This is used to deliver local mail, and is treated specially in several ways. Additionally, three other mailers named .q prog , .q *file* , and .q *include* may be defined to tune the delivery of messages to programs, files, and :include: lists respectively. They default to: .(b Mprog, P=/bin/sh, F=lsoDq9, T=DNS/RFC822/X-Unix, A=sh \-c $u M*file*, P=[FILE], F=lsDFMPEouq9, T=DNS/RFC822/X-Unix, A=FILE $u M*include*, P=/dev/null, F=su, A=INCLUDE $u .)b .pp Builtin pathnames are [FILE] and [IPC], the former is used for delivery to files, the latter for delivery via interprocess communication. For mailers that use [IPC] as pathname the argument vector (A=) must start with TCP or FILE for delivery via a TCP or a Unix domain socket. If TCP is used, the second argument must be the name of the host to contact. Optionally a third argument can be used to specify a port, the default is smtp (port 25). If FILE is used, the second argument must be the name of the Unix domain socket. .pp If the argument vector does not contain $u then .i sendmail will speak SMTP (or LMTP if the mailer flag z is specified) to the mailer. .pp If no Eol field is defined, then the default is "\\r\\n" for SMTP mailers and "\\n" of others. .pp The Sender and Recipient rewriting sets may either be a simple ruleset id or may be two ids separated by a slash; if so, the first rewriting set is applied to envelope addresses and the second is applied to headers. Setting any value to zero disables corresponding mailer-specific rewriting. .pp The Directory is actually a colon-separated path of directories to try. For example, the definition .q D=$z:/ first tries to execute in the recipient's home directory; if that is not available, it tries to execute in the root of the filesystem. This is intended to be used only on the .q prog mailer, since some shells (such as .i csh ) refuse to execute if they cannot read the current directory. Since the queue directory is not normally readable by unprivileged users .i csh scripts as recipients can fail. .pp The Userid specifies the default user and group id to run as, overriding the .b DefaultUser option (q.v.). If the .b S mailer flag is also specified, this user and group will be set as the effective uid and gid for the process. This may be given as .i user:group to set both the user and group id; either may be an integer or a symbolic name to be looked up in the .i passwd and .i group files respectively. If only a symbolic user name is specified, the group id in the .i passwd file for that user is used as the group id. .pp The Charset field is used when converting a message to MIME; this is the character set used in the Content-Type: header. If this is not set, the .b DefaultCharset option is used, and if that is not set, the value .q unknown-8bit is used. .b WARNING: this field applies to the sender's mailer, not the recipient's mailer. For example, if the envelope sender address lists an address on the local network and the recipient is on an external network, the character set will be set from the Charset= field for the local network mailer, not that of the external network mailer. .pp The Type= field sets the type information used in MIME error messages as defined by RFC 1894. It is actually three values separated by slashes: the MTA-type (that is, the description of how hosts are named), the address type (the description of e-mail addresses), and the diagnostic type (the description of error diagnostic codes). Each of these must be a registered value or begin with .q X\- . The default is .q dns/rfc822/smtp . .pp The m= field specifies the maximum number of messages to attempt to deliver on a single SMTP or LMTP connection. The default is infinite. .pp The r= field specifies the maximum number of recipients to attempt to deliver in a single envelope. It defaults to 100. .pp The /= field specifies a new root directory for the mailer. The path is macro expanded and then passed to the .q chroot system call. The root directory is changed before the Directory field is consulted or the uid is changed. .pp The Wait= field specifies the maximum time to wait for the mailer to return after sending all data to it. This applies to mailers that have been forked by .i sendmail . .pp The Queuegroup= field specifies the default queue group in which received mail should be queued. This can be overridden by other means as explained in section ``Queue Groups and Queue Directories''. .sh 2 "H \*- Define Header" .pp The format of the header lines that .i sendmail inserts into the message are defined by the .b H line. The syntax of this line is one of the following: .(b F .b H \c .i hname \c .b : .i htemplate .)b .(b F .b H [\c .b ? \c .i mflags \c .b ? \c .b ]\c .i hname \c .b : .i htemplate .)b .(b F .b H [\c .b ?$ \c .i {macro} \c .b ? \c .b ]\c .i hname \c .b : .i htemplate .)b Continuation lines in this spec are reflected directly into the outgoing message. The .i htemplate is macro-expanded before insertion into the message. If the .i mflags (surrounded by question marks) are specified, at least one of the specified flags must be stated in the mailer definition for this header to be automatically output. If a .i ${macro} (surrounded by question marks) is specified, the header will be automatically output if the macro is set. The macro may be set using any of the normal methods, including using the .b macro storage map in a ruleset. If one of these headers is in the input it is reflected to the output regardless of these flags or macros. Notice: If a .i ${macro} is used to set a header, then it is useful to add that macro to class .i $={persistentMacros} which consists of the macros that should be saved across queue runs. .pp Some headers have special semantics that will be described later. .pp A secondary syntax allows validation of headers as they are being read. To enable validation, use: .(b .b H \c .i Header \c .b ": $>" \c .i Ruleset .b H \c .i Header \c .b ": $>+" \c .i Ruleset .)b The indicated .i Ruleset is called for the specified .i Header , and can return .b $#error to reject or quarantine the message or .b $#discard to discard the message (as with the other .b check_ * rulesets). The ruleset receives the header field-body as argument, i.e., not the header field-name; see also ${hdr_name} and ${currHeader}. The header is treated as a structured field, that is, text in parentheses is deleted before processing, unless the second form .b $>+ is used. Note: only one ruleset can be associated with a header; .i sendmail will silently ignore multiple entries. .pp For example, the configuration lines: .(b HMessage-Id: $>CheckMessageId SCheckMessageId R< $+ @ $+ > $@ OK R$* $#error $: Illegal Message-Id header .)b would refuse any message that had a Message-Id: header of any of the following forms: .(b Message-Id: <> Message-Id: some text Message-Id: extra crud .)b A default ruleset that is called for headers which don't have a specific ruleset defined for them can be specified by: .(b .b H \c .i * \c .b ": $>" \c .i Ruleset .)b or .(b .b H \c .i * \c .b ": $>+" \c .i Ruleset .)b .sh 2 "O \*- Set Option" .pp There are a number of global options that can be set from a configuration file. Options are represented by full words; some are also representable as single characters for back compatibility. The syntax of this line is: .(b F .b O \0 .i option \c .b = \c .i value .)b This sets option .i option to be .i value . Note that there .i must be a space between the letter `O' and the name of the option. An older version is: .(b F .b O \c .i o\|value .)b where the option .i o is a single character. Depending on the option, .i value may be a string, an integer, a boolean (with legal values .q t , .q T , .q f , or .q F ; the default is TRUE), or a time interval. .pp All filenames used in options should be absolute paths, i.e., starting with '/'. Relative filenames most likely cause surprises during operation (unless otherwise noted). .pp The options supported (with the old, one character names in brackets) are: .nr ii 1i .ip "AliasFile=\fIspec, spec, ...\fP" [A] Specify possible alias file(s). Each .i spec should be in the format ``\c .i class \c .b : .i info '' where .i class \c .b : is optional and defaults to ``implicit''. Note that .i info is required for all .i class es except .q ldap . For the .q ldap class, if .i info is not specified, a default .i info value is used as follows: .(b \-k (&(objectClass=sendmailMTAAliasObject) (sendmailMTAAliasName=aliases) (|(sendmailMTACluster=${sendmailMTACluster}) (sendmailMTAHost=$j)) (sendmailMTAKey=%0)) \-v sendmailMTAAliasValue .)b Depending on how .i sendmail is compiled, valid classes are .q implicit (search through a compiled-in list of alias file types, for back compatibility), .q hash (if .sm NEWDB is specified), .q btree (if .sm NEWDB is specified), .q dbm (if .sm NDBM is specified), .q stab (internal symbol table \*- not normally used unless you have no other database lookup), .q sequence (use a sequence of maps previously declared), .q ldap (if .sm LDAPMAP is specified), or .q nis (if .sm NIS is specified). If a list of .i spec s are provided, .i sendmail searches them in order. .ip AliasWait=\fItimeout\fP [a] If set, wait up to .i timeout (units default to minutes) for an .q @:@ entry to exist in the alias database before starting up. If it does not appear in the .i timeout interval issue a warning. .ip AllowBogusHELO [no short name] If set, allow HELO SMTP commands that don't include a host name. Setting this violates RFC 1123 section 5.2.5, but is necessary to interoperate with several SMTP clients. If there is a value, it is still checked for legitimacy. .ip AuthMaxBits=\fIN\fP [no short name] Limit the maximum encryption strength for the security layer in SMTP AUTH (SASL). Default is essentially unlimited. This allows to turn off additional encryption in SASL if STARTTLS is already encrypting the communication, because the existing encryption strength is taken into account when choosing an algorithm for the security layer. For example, if STARTTLS is used and the symmetric cipher is 3DES, then the the keylength (in bits) is 168. Hence setting .b AuthMaxBits to 168 will disable any encryption in SASL. .ip AuthMechanisms [no short name] List of authentication mechanisms for AUTH (separated by spaces). The advertised list of authentication mechanisms will be the intersection of this list and the list of available mechanisms as determined by the Cyrus SASL library. If STARTTLS is active, EXTERNAL will be added to this list. In that case, the value of {cert_subject} is used as authentication id. .ip AuthOptions [no short name] List of options for SMTP AUTH consisting of single characters with intervening white space or commas. .(b .ta 4n A Use the AUTH= parameter for the MAIL FROM command only when authentication succeeded. This can be used as a workaround for broken MTAs that do not implement RFC 2554 correctly. a protection from active (non-dictionary) attacks during authentication exchange. c require mechanisms which pass client credentials, and allow mechanisms which can pass credentials to do so. d don't permit mechanisms susceptible to passive dictionary attack. f require forward secrecy between sessions (breaking one won't help break next). m require mechanisms which provide mutual authentication (only available if using Cyrus SASL v2 or later). p don't permit mechanisms susceptible to simple passive attack (e.g., PLAIN, LOGIN), unless a security layer is active. y don't permit mechanisms that allow anonymous login. .)b The first option applies to sendmail as a client, the others to a server. Example: .(b O AuthOptions=p,y .)b would disallow ANONYMOUS as AUTH mechanism and would allow PLAIN and LOGIN only if a security layer (e.g., provided by STARTTLS) is already active. The options 'a', 'c', 'd', 'f', 'p', and 'y' refer to properties of the selected SASL mechanisms. Explanations of these properties can be found in the Cyrus SASL documentation. .ip AuthRealm [no short name] The authentication realm that is passed to the Cyrus SASL library. If no realm is specified, .b $j is used. .ip BadRcptThrottle=\fIN\fP [no short name] If set and the specified number of recipients in a single SMTP transaction have been rejected, sleep for one second after each subsequent RCPT command in that transaction. .ip BlankSub=\fIc\fP [B] Set the blank substitution character to .i c . Unquoted spaces in addresses are replaced by this character. Defaults to space (i.e., no change is made). .ip CACertPath [no short name] Path to directory with certificates of CAs. This directory directory must contain the hashes of each CA certificate as filenames (or as links to them). .ip CACertFile [no short name] File containing one or more CA certificates; see section about STARTTLS for more information. .ip CheckAliases [n] Validate the RHS of aliases when rebuilding the alias database. .ip CheckpointInterval=\fIN\fP [C] Checkpoints the queue every .i N (default 10) addresses sent. If your system crashes during delivery to a large list, this prevents retransmission to any but the last .i N recipients. .ip ClassFactor=\fIfact\fP [z] The indicated .i fact or is multiplied by the message class (determined by the Precedence: field in the user header and the .b P lines in the configuration file) and subtracted from the priority. Thus, messages with a higher Priority: will be favored. Defaults to 1800. .ip ClientCertFile [no short name] File containing the certificate of the client, i.e., this certificate is used when .i sendmail acts as client (for STARTTLS). .ip ClientKeyFile [no short name] File containing the private key belonging to the client certificate (for STARTTLS if .i sendmail runs as client). .ip ClientPortOptions=\fIoptions\fP [O] Set client SMTP options. The options are .i key=value pairs separated by commas. Known keys are: .(b .ta 1i Port Name/number of source port for connection (defaults to any free port) Addr Address mask (defaults INADDR_ANY) Family Address family (defaults to INET) SndBufSize Size of TCP send buffer RcvBufSize Size of TCP receive buffer Modifier Options (flags) for the client .)b The .i Addr ess -mask may be a numeric address in dot notation +mask may be a numeric address in IPv4 dot notation or IPv6 colon notation or a network name. +Note that if a network name is specified, +only the first IP address returned for it will be used. +This may cause indeterminate behavior for network names +that resolve to multiple addresses. +Therefore, use of an address is recommended. .i Modifier can be the following character: .(b .ta 1i h use name of interface for HELO command A don't use AUTH when sending e-mail S don't use STARTTLS when sending e-mail .)b If ``h'' is set, the name corresponding to the outgoing interface address (whether chosen via the Connection parameter or the default) is used for the HELO/EHLO command. However, the name must not start with a square bracket and it must contain at least one dot. This is a simple test whether the name is not an IP address (in square brackets) but a qualified hostname. Note that multiple ClientPortOptions settings are allowed in order to give settings for each protocol family (e.g., one for Family=inet and one for Family=inet6). A restriction placed on one family only affects outgoing connections on that particular family. .ip ColonOkInAddr [no short name] If set, colons are acceptable in e-mail addresses (e.g., .q host:user ). If not set, colons indicate the beginning of a RFC 822 group construct (\c .q "groupname: member1, member2, ... memberN;" ). Doubled colons are always acceptable (\c .q nodename::user ) and proper route-addr nesting is understood (\c .q <@relay:user@host> ). Furthermore, this option defaults on if the configuration version level is less than 6 (for back compatibility). However, it must be off for full compatibility with RFC 822. .ip ConnectionCacheSize=\fIN\fP [k] The maximum number of open connections that will be cached at a time. The default is one. This delays closing the current connection until either this invocation of .i sendmail needs to connect to another host or it terminates. Setting it to zero defaults to the old behavior, that is, connections are closed immediately. Since this consumes file descriptors, the connection cache should be kept small: 4 is probably a practical maximum. .ip ConnectionCacheTimeout=\fItimeout\fP [K] The maximum amount of time a cached connection will be permitted to idle without activity. If this time is exceeded, the connection is immediately closed. This value should be small (on the order of ten minutes). Before .i sendmail uses a cached connection, it always sends a RSET command to check the connection; if this fails, it reopens the connection. This keeps your end from failing if the other end times out. The point of this option is to be a good network neighbor and avoid using up excessive resources on the other end. The default is five minutes. .ip ConnectOnlyTo=\fIaddress\fP [no short name] This can be used to override the connection address (for testing purposes). .ip ConnectionRateThrottle=\fIN\fP [no short name] If set to a positive value, allow no more than .i N incoming connections in a one second period per daemon. This is intended to flatten out peaks and allow the load average checking to cut in. Defaults to zero (no limits). .ip ConnectionRateWindowSize=\fIN\fP [no short name] Define the length of the interval for which the number of incoming connections is maintained. The default is 60 seconds. .ip ControlSocketName=\fIname\fP [no short name] Name of the control socket for daemon management. A running .i sendmail daemon can be controlled through this named socket. Available commands are: .i help, .i mstat, .i restart, .i shutdown, and .i status. The .i status command returns the current number of daemon children, the maximum number of daemon children, the free disk space (in blocks) of the queue directory, and the load average of the machine expressed as an integer. If not set, no control socket will be available. Solaris and pre-4.4BSD kernel users should see the note in sendmail/README . .ip CRLFile=\fIname\fP [no short name] Name of file that contains certificate revocation status, useful for X.509v3 authentication. CRL checking requires at least OpenSSL version 0.9.7. Note: if a CRLFile is specified but the file is unusable, STARTTLS is disabled. .ip DHParameters Possible values are: .(b .ta 1i 5 use 512 bit prime 1 use 1024 bit prime none do not use Diffie-Hellman NAME load prime from file .)b This is only required if a ciphersuite containing DSA/DH is used. If ``5'' is selected, then precomputed, fixed primes are used. This is the default for the client side. If ``1'' is selected, then prime values are computed during startup. This is the default for the server side. Note: this operation can take a significant amount of time on a slow machine (several seconds), but it is only done once at startup. If ``none'' is selected, then TLS ciphersuites containing DSA/DH cannot be used. If a file name is specified (which must be an absolute path), then the primes are read from it. .ip DaemonPortOptions=\fIoptions\fP [O] Set server SMTP options. Each instance of .b DaemonPortOptions leads to an additional incoming socket. The options are .i key=value pairs. Known keys are: .(b .ta 1i Name User-definable name for the daemon (defaults to "Daemon#") Port Name/number of listening port (defaults to "smtp") Addr Address mask (defaults INADDR_ANY) Family Address family (defaults to INET) InputMailFilters List of input mail filters for the daemon Listen Size of listen queue (defaults to 10) Modifier Options (flags) for the daemon SndBufSize Size of TCP send buffer RcvBufSize Size of TCP receive buffer children maximum number of children per daemon, see \fBMaxDaemonChildren\fP. DeliveryMode Delivery mode per daemon, see \fBDeliveryMode\fP. refuseLA RefuseLA per daemon delayLA DelayLA per daemon queueLA QueueLA per daemon .)b The .i Name key is used for error messages and logging. The .i Addr ess -mask may be a numeric address in dot notation +mask may be a numeric address in IPv4 dot notation or IPv6 colon notation or a network name. +Note that if a network name is specified, +only the first IP address returned for it will be used. +This may cause indeterminate behavior for network names +that resolve to multiple addresses. +Therefore, use of an address is recommended. The .i Family key defaults to INET (IPv4). IPv6 users who wish to also accept IPv6 connections should add additional Family=inet6 .b DaemonPortOptions lines. The .i InputMailFilters key overrides the default list of input mail filters listed in the .b InputMailFilters option. If multiple input mail filters are required, they must be separated by semicolons (not commas). .i Modifier can be a sequence (without any delimiters) of the following characters: .(b .ta 1i a always require authentication b bind to interface through which mail has been received c perform hostname canonification (.cf) f require fully qualified hostname (.cf) s Run smtps (SMTP over SSL) instead of smtp u allow unqualified addresses (.cf) A disable AUTH (overrides 'a' modifier) C don't perform hostname canonification E disallow ETRN (see RFC 2476) O optional; if opening the socket fails ignore it S don't offer STARTTLS .)b That is, one way to specify a message submission agent (MSA) that always requires authentication is: .(b O DaemonPortOptions=Name=MSA, Port=587, M=Ea .)b The modifiers that are marked with "(.cf)" have only effect in the standard configuration file, in which they are available via .b ${daemon_flags} . Notice: Do .b not use the ``a'' modifier on a public accessible MTA! It should only be used for a MSA that is accessed by authorized users for initial mail submission. Users must authenticate to use a MSA which has this option turned on. The flags ``c'' and ``C'' can change the default for hostname canonification in the .i sendmail.cf file. See the relevant documentation for .sm FEATURE(nocanonify) . The modifier ``f'' disallows addresses of the form .b user@host unless they are submitted directly. The flag ``u'' allows unqualified sender addresses, i.e., those without @host. ``b'' forces sendmail to bind to the interface through which the e-mail has been received for the outgoing connection. .b WARNING: Use ``b'' only if outgoing mail can be routed through the incoming connection's interface to its destination. No attempt is made to catch problems due to a misconfiguration of this parameter, use it only for virtual hosting where each virtual interface can connect to every possible location. This will also override possible settings via .b ClientPortOptions. Note, .i sendmail will listen on a new socket for each occurence of the .b DaemonPortOptions option in a configuration file. The modifier ``O'' causes sendmail to ignore a socket if it can't be opened. This applies to failures from the socket(2) and bind(2) calls. .ip DefaultAuthInfo [no short name] Filename that contains default authentication information for outgoing connections. This file must contain the user id, the authorization id, the password (plain text), the realm and the list of mechanisms to use on separate lines and must be readable by root (or the trusted user) only. If no realm is specified, .b $j is used. If no mechanisms are specified, the list given by .b AuthMechanisms is used. Notice: this option is deprecated and will be removed in future versions. Moreover, it doesn't work for the MSP since it can't read the file (the file must not be group/world-readable otherwise .i sendmail will complain). Use the authinfo ruleset instead which provides more control over the usage of the data anyway. .ip DefaultCharSet=\fIcharset\fP [no short name] When a message that has 8-bit characters but is not in MIME format is converted to MIME (see the EightBitMode option) a character set must be included in the Content-Type: header. This character set is normally set from the Charset= field of the mailer descriptor. If that is not set, the value of this option is used. If this option is not set, the value .q unknown-8bit is used. .ip DataFileBufferSize=\fIthreshold\fP [no short name] Set the .i threshold , in bytes, before a memory-based queue data file becomes disk-based. The default is 4096 bytes. .ip DeadLetterDrop=\fIfile\fP [no short name] Defines the location of the system-wide dead.letter file, formerly hardcoded to /usr/tmp/dead.letter. If this option is not set (the default), sendmail will not attempt to save to a system-wide dead.letter file in the event it cannot bounce the mail to the user or postmaster. Instead, it will rename the qf file as it has in the past when the dead.letter file could not be opened. .ip DefaultUser=\fIuser:group\fP [u] Set the default userid for mailers to .i user:group . If .i group is omitted and .i user is a user name (as opposed to a numeric user id) the default group listed in the /etc/passwd file for that user is used as the default group. Both .i user and .i group may be numeric. Mailers without the .i S flag in the mailer definition will run as this user. Defaults to 1:1. The value can also be given as a symbolic user name.\** .(f \**The old .b g option has been combined into the .b DefaultUser option. .)f .ip DelayLA=\fILA\fP [no short name] When the system load average exceeds .i LA , .i sendmail will sleep for one second on most SMTP commands and before accepting connections. .ip DeliverByMin=\fItime\fP [0] Set minimum time for Deliver By SMTP Service Extension (RFC 2852). If 0, no time is listed, if less than 0, the extension is not offered, if greater than 0, it is listed as minimum time for the EHLO keyword DELIVERBY. .ip DeliveryMode=\fIx\fP [d] Deliver in mode .i x . Legal modes are: .(b .ta 4n i Deliver interactively (synchronously) b Deliver in background (asynchronously) q Just queue the message (deliver during queue run) d Defer delivery and all map lookups (deliver during queue run) .)b Defaults to ``b'' if no option is specified, ``i'' if it is specified but given no argument (i.e., ``Od'' is equivalent to ``Odi''). The .b \-v command line flag sets this to .b i . Note: for internal reasons, ``i'' does not work if a milter is enabled which can reject or delete recipients. In that case the mode will be changed to ``b''. .ip DialDelay=\fIsleeptime\fP [no short name] Dial-on-demand network connections can see timeouts if a connection is opened before the call is set up. If this is set to an interval and a connection times out on the first connection being attempted .i sendmail will sleep for this amount of time and try again. This should give your system time to establish the connection to your service provider. Units default to seconds, so .q DialDelay=5 uses a five second delay. Defaults to zero (no retry). This delay only applies to mailers which have the Z flag set. .ip DirectSubmissionModifiers=\fImodifiers\fP Defines .b ${daemon_flags} for direct (command line) submissions. If not set, .b ${daemon_flags} is either "CC f" if the option .b \-G is used or "c u" otherwise. Note that only the the "CC", "c", "f", and "u" flags are checked. .ip DontBlameSendmail=\fIoption,option,...\fP [no short name] In order to avoid possible cracking attempts caused by world- and group-writable files and directories, .i sendmail does paranoid checking when opening most of its support files. If for some reason you absolutely must run with, for example, a group-writable .i /etc directory, then you will have to turn off this checking (at the cost of making your system more vulnerable to attack). The possible arguments have been described earlier. The details of these flags are described above. .\"XXX should have more here!!! XXX .b "Use of this option is not recommended." .ip DontExpandCnames [no short name] The standards say that all host addresses used in a mail message must be fully canonical. For example, if your host is named .q Cruft.Foo.ORG and also has an alias of .q FTP.Foo.ORG , the former name must be used at all times. This is enforced during host name canonification ($[ ... $] lookups). If this option is set, the protocols are ignored and the .q wrong thing is done. However, the IETF is moving toward changing this standard, so the behavior may become acceptable. Please note that hosts downstream may still rewrite the address to be the true canonical name however. .ip DontInitGroups [no short name] If set, .i sendmail will avoid using the initgroups(3) call. If you are running NIS, this causes a sequential scan of the groups.byname map, which can cause your NIS server to be badly overloaded in a large domain. The cost of this is that the only group found for users will be their primary group (the one in the password file), which will make file access permissions somewhat more restrictive. Has no effect on systems that don't have group lists. .ip DontProbeInterfaces [no short name] .i Sendmail normally finds the names of all interfaces active on your machine when it starts up and adds their name to the .b $=w class of known host aliases. If you have a large number of virtual interfaces or if your DNS inverse lookups are slow this can be time consuming. This option turns off that probing. However, you will need to be certain to include all variant names in the .b $=w class by some other mechanism. If set to .b loopback , loopback interfaces (e.g., lo0) will not be probed. .ip DontPruneRoutes [R] Normally, .i sendmail tries to eliminate any unnecessary explicit routes when sending an error message (as discussed in RFC 1123 \(sc 5.2.6). For example, when sending an error message to .(b <@known1,@known2,@known3:user@unknown> .)b .i sendmail will strip off the .q @known1,@known2 in order to make the route as direct as possible. However, if the .b R option is set, this will be disabled, and the mail will be sent to the first address in the route, even if later addresses are known. This may be useful if you are caught behind a firewall. .ip DoubleBounceAddress=\fIerror-address\fP [no short name] If an error occurs when sending an error message, send the error report (termed a .q "double bounce" because it is an error .q bounce that occurs when trying to send another error .q bounce ) to the indicated address. The address is macro expanded at the time of delivery. If not set, defaults to .q postmaster . If set to an empty string, double bounces are dropped. .ip EightBitMode=\fIaction\fP [8] Set handling of eight-bit data. There are two kinds of eight-bit data: that declared as such using the .b BODY=8BITMIME ESMTP declaration or the .b \-B8BITMIME command line flag, and undeclared 8-bit data, that is, input that just happens to be eight bits. There are three basic operations that can happen: undeclared 8-bit data can be automatically converted to 8BITMIME, undeclared 8-bit data can be passed as-is without conversion to MIME (``just send 8''), and declared 8-bit data can be converted to 7-bits for transmission to a non-8BITMIME mailer. The possible .i action s are: .(b .\" r Reject undeclared 8-bit data; .\" don't convert 8BITMIME\(->7BIT (``reject'') s Reject undeclared 8-bit data (``strict'') .\" do convert 8BITMIME\(->7BIT (``strict'') .\" c Convert undeclared 8-bit data to MIME; .\" don't convert 8BITMIME\(->7BIT (``convert'') m Convert undeclared 8-bit data to MIME (``mime'') .\" do convert 8BITMIME\(->7BIT (``mime'') .\" j Pass undeclared 8-bit data; .\" don't convert 8BITMIME\(->7BIT (``just send 8'') p Pass undeclared 8-bit data (``pass'') .\" do convert 8BITMIME\(->7BIT (``pass'') .\" a Adaptive algorithm: see below .)b .\"The adaptive algorithm is to accept 8-bit data, .\"converting it to 8BITMIME only if the receiver understands that, .\"otherwise just passing it as undeclared 8-bit data; .\"8BITMIME\(->7BIT conversions are done. In all cases properly declared 8BITMIME data will be converted to 7BIT as needed. .ip ErrorHeader=\fIfile-or-message\fP [E] Prepend error messages with the indicated message. If it begins with a slash, it is assumed to be the pathname of a file containing a message (this is the recommended setting). Otherwise, it is a literal message. The error file might contain the name, email address, and/or phone number of a local postmaster who could provide assistance to end users. If the option is missing or null, or if it names a file which does not exist or which is not readable, no message is printed. .ip ErrorMode=\fIx\fP [e] Dispose of errors using mode .i x . The values for .i x are: .(b p Print error messages (default) q No messages, just give exit status m Mail back errors w Write back errors (mail if user not logged in) e Mail back errors (when applicable) and give zero exit stat always .)b Note that the last mode, .q e , is for Berknet error processing and should not be used in normal circumstances. Note, too, that mode .q q , only applies to errors recognized before sendmail forks for background delivery. .ip FallbackMXhost=\fIfallbackhost\fP [V] If specified, the .i fallbackhost acts like a very low priority MX on every host. MX records will be looked up for this host, unless the name is surrounded by square brackets. This is intended to be used by sites with poor network connectivity. Messages which are undeliverable due to temporary address failures (e.g., DNS failure) also go to the FallbackMXhost. .ip FallBackSmartHost=\fIhostname\fP If specified, the .i FallBackSmartHost will be used in a last-ditch effort for each host. This is intended to be used by sites with "fake internal DNS", e.g., a company whose DNS accurately reflects the world inside that company's domain but not outside. .ip FastSplit [no short name] If set to a value greater than zero (the default is one), it suppresses the MX lookups on addresses when they are initially sorted, i.e., for the first delivery attempt. This usually results in faster envelope splitting unless the MX records are readily available in a local DNS cache. To enforce initial sorting based on MX records set .b FastSplit to zero. If the mail is submitted directly from the command line, then the value also limits the number of processes to deliver the envelopes; if more envelopes are created they are only queued up and must be taken care of by a queue run. Since the default submission method is via SMTP (either from a MUA or via the MSP), the value of .b FastSplit is seldom used to limit the number of processes to deliver the envelopes. .ip ForkEachJob [Y] If set, deliver each job that is run from the queue in a separate process. .ip ForwardPath=\fIpath\fP [J] Set the path for searching for users' .forward files. The default is .q $z/.forward . Some sites that use the automounter may prefer to change this to .q /var/forward/$u to search a file with the same name as the user in a system directory. It can also be set to a sequence of paths separated by colons; .i sendmail stops at the first file it can successfully and safely open. For example, .q /var/forward/$u:$z/.forward will search first in /var/forward/\c .i username and then in .i ~username /.forward (but only if the first file does not exist). .ip HeloName=\fIname\fP [no short name] Set the name to be used for HELO/EHLO (instead of $j). .ip HoldExpensive [c] If an outgoing mailer is marked as being expensive, don't connect immediately. .ip HostsFile=\fIpath\fP [no short name] The path to the hosts database, normally .q /etc/hosts . This option is only consulted when sendmail is canonifying addresses, and then only when .q files is in the .q hosts service switch entry. In particular, this file is .i never used when looking up host addresses; that is under the control of the system .i gethostbyname (3) routine. .ip HostStatusDirectory=\fIpath\fP [no short name] The location of the long term host status information. When set, information about the status of hosts (e.g., host down or not accepting connections) will be shared between all .i sendmail processes; normally, this information is only held within a single queue run. This option requires a connection cache of at least 1 to function. If the option begins with a leading `/', it is an absolute pathname; otherwise, it is relative to the mail queue directory. A suggested value for sites desiring persistent host status is .q \&.hoststat (i.e., a subdirectory of the queue directory). .ip IgnoreDots [i] Ignore dots in incoming messages. This is always disabled (that is, dots are always accepted) when reading SMTP mail. .ip InputMailFilters=\fIname,name,...\fP A comma separated list of filters which determines which filters (see the "X \*- Mail Filter (Milter) Definitions" section) and the invocation sequence are contacted for incoming SMTP messages. If none are set, no filters will be contacted. .ip LDAPDefaultSpec=\fIspec\fP [no short name] Sets a default map specification for LDAP maps. The value should only contain LDAP specific settings such as .q "-h host -p port -d bindDN" . The settings will be used for all LDAP maps unless the individual map specification overrides a setting. This option should be set before any LDAP maps are defined. .ip LogLevel=\fIn\fP [L] Set the log level to .i n . Defaults to 9. .ip M\fIx\|value\fP [no long version] Set the macro .i x to .i value . This is intended only for use from the command line. The .b \-M flag is preferred. .ip MailboxDatabase [no short name] Type of lookup to find information about local mailboxes, defaults to ``pw'' which uses .i getpwnam . Other types can be introduced by adding them to the source code, see libsm/mbdb.c for details. .ip UseMSP [no short name] Use as mail submission program, i.e., allow group writable queue files if the group is the same as that of a set-group-ID sendmail binary. See the file .b sendmail/SECURITY in the distribution tarball. .ip MatchGECOS [G] Allow fuzzy matching on the GECOS field. If this flag is set, and the usual user name lookups fail (that is, there is no alias with this name and a .i getpwnam fails), sequentially search the password file for a matching entry in the GECOS field. This also requires that MATCHGECOS be turned on during compilation. This option is not recommended. .ip MaxAliasRecursion=\fIN\fP [no short name] The maximum depth of alias recursion (default: 10). .ip MaxDaemonChildren=\fIN\fP [no short name] If set, .i sendmail will refuse connections when it has more than .i N children processing incoming mail or automatic queue runs. This does not limit the number of outgoing connections. If the default .b DeliveryMode (background) is used, then .i sendmail may create an almost unlimited number of children (depending on the number of transactions and the relative execution times of mail receiption and mail delivery). If the limit should be enforced, then a .b DeliveryMode other than background must be used. If not set, there is no limit to the number of children -- that is, the system load average controls this. .ip MaxHeadersLength=\fIN\fP [no short name] The maximum length of the sum of all headers. This can be used to prevent a denial of service attack. The default is no limit. .ip MaxHopCount=\fIN\fP [h] The maximum hop count. Messages that have been processed more than .i N times are assumed to be in a loop and are rejected. Defaults to 25. .ip MaxMessageSize=\fIN\fP [no short name] Specify the maximum message size to be advertised in the ESMTP EHLO response. Messages larger than this will be rejected. If set to a value greater than zero, that value will be listed in the SIZE response, otherwise SIZE is advertised in the ESMTP EHLO response without a parameter. .ip MaxMimeHeaderLength=\fIN[/M]\fP [no short name] Sets the maximum length of certain MIME header field values to .i N characters. These MIME header fields are determined by being a member of class {checkMIMETextHeaders}, which currently contains only the header Content-Description. For some of these headers which take parameters, the maximum length of each parameter is set to .i M if specified. If .i /M is not specified, one half of .i N will be used. By default, these values are 2048 and 1024, respectively. To allow any length, a value of 0 can be specified. .ip MaxNOOPCommands=\fIN\fP Override the default of .b MAXNOOPCOMMANDS for the number of .i useless commands, see Section "Measures against Denial of Service Attacks". .ip MaxQueueChildren=\fIN\fP [no short name] When set, this limits the number of concurrent queue runner processes to .i N. This helps to control the amount of system resources used when processing the queue. When there are multiple queue groups defined and the total number of queue runners for these queue groups would exceed .i MaxQueueChildren then the queue groups will not all run concurrently. That is, some portion of the queue groups will run concurrently such that .i MaxQueueChildren will not be exceeded, while the remaining queue groups will be run later (in round robin order). See also .i MaxRunnersPerQueue and the section \fBQueue Group Declaration\fP. Notice: .i sendmail does not count individual queue runners, but only sets of processes that act on a workgroup. Hence the actual number of queue runners may be lower than the limit imposed by .i MaxQueueChildren . This discrepancy can be large if some queue runners have to wait for a slow server and if short intervals are used. .ip MaxQueueRunSize=\fIN\fP [no short name] The maximum number of jobs that will be processed in a single queue run. If not set, there is no limit on the size. If you have very large queues or a very short queue run interval this could be unstable. However, since the first .i N jobs in queue directory order are run (rather than the .i N highest priority jobs) this should be set as high as possible to avoid .q losing jobs that happen to fall late in the queue directory. Note: this option also restricts the number of entries printed by .i mailq . That is, if .i MaxQueueRunSize is set to a value .b N larger than zero, then only .b N entries are printed per queue group. .ip MaxRecipientsPerMessage=\fIN\fP [no short name] The maximum number of recipients that will be accepted per message in an SMTP transaction. Note: setting this too low can interfere with sending mail from MUAs that use SMTP for initial submission. If not set, there is no limit on the number of recipients per envelope. .ip MaxRunnersPerQueue=\fIN\fP [no short name] This sets the default maximum number of queue runners for queue groups. Up to .i N queue runners will work in parallel on a queue group's messages. This is useful where the processing of a message in the queue might delay the processing of subsequent messages. Such a delay may be the result of non-erroneous situations such as a low bandwidth connection. May be overridden on a per queue group basis by setting the .i Runners option; see the section \fBQueue Group Declaration\fP. The default is 1 when not set. .ip MeToo [m] Send to me too, even if I am in an alias expansion. This option is deprecated and will be removed from a future version. .ip Milter [no short name] This option has several sub(sub)options. The names of the suboptions are separated by dots. At the first level the following options are available: .(b .ta \w'LogLevel'u+3n LogLevel Log level for input mail filter actions, defaults to LogLevel. macros Specifies list of macro to transmit to filters. See list below. .)b The ``macros'' option has the following suboptions which specify the list of macro to transmit to milters after a certain event occurred. .(b .ta \w'envfrom'u+3n connect After session connection start helo After EHLO/HELO command envfrom After MAIL From command envrcpt After RCPT To command data After DATA command. eoh After DATA command and header eom After DATA command and terminating ``.'' .)b By default the lists of macros are empty. Example: .(b O Milter.LogLevel=12 O Milter.macros.connect=j, _, {daemon_name} .)b .ip MinFreeBlocks=\fIN\fP [b] Insist on at least .i N blocks free on the filesystem that holds the queue files before accepting email via SMTP. If there is insufficient space .i sendmail gives a 452 response to the MAIL command. This invites the sender to try again later. .ip MinQueueAge=\fIage\fP [no short name] Don't process any queued jobs that have been in the queue less than the indicated time interval. This is intended to allow you to get responsiveness by processing the queue fairly frequently without thrashing your system by trying jobs too often. The default units are minutes. Note: This option is ignored for queue runs that select a subset of the queue, i.e., .q \-q[!][I|R|S|Q][string] .ip MustQuoteChars=\fIs\fP [no short name] Sets the list of characters that must be quoted if used in a full name that is in the phrase part of a ``phrase
'' syntax. The default is ``\'.''. The characters ``@,;:\e()[]'' are always added to this list. .ip NiceQueueRun [no short name] The priority of queue runners (nice(3)). This value must be greater or equal zero. .ip NoRecipientAction [no short name] The action to take when you receive a message that has no valid recipient headers (To:, Cc:, Bcc:, or Apparently-To: \(em the last included for back compatibility with old .i sendmail s). It can be .b None to pass the message on unmodified, which violates the protocol, .b Add-To to add a To: header with any recipients it can find in the envelope (which might expose Bcc: recipients), .b Add-Apparently-To to add an Apparently-To: header (this is only for back-compatibility and is officially deprecated), .b Add-To-Undisclosed to add a header .q "To: undisclosed-recipients:;" to make the header legal without disclosing anything, or .b Add-Bcc to add an empty Bcc: header. .ip OldStyleHeaders [o] Assume that the headers may be in old format, i.e., spaces delimit names. This actually turns on an adaptive algorithm: if any recipient address contains a comma, parenthesis, or angle bracket, it will be assumed that commas already exist. If this flag is not on, only commas delimit names. Headers are always output with commas between the names. Defaults to off. .ip OperatorChars=\fIcharlist\fP [$o macro] The list of characters that are considered to be .q operators , that is, characters that delimit tokens. All operator characters are tokens by themselves; sequences of non-operator characters are also tokens. White space characters separate tokens but are not tokens themselves \(em for example, .q AAA.BBB has three tokens, but .q "AAA BBB" has two. If not set, OperatorChars defaults to .q \&.\|:\|@\|[\|] ; additionally, the characters .q (\|)\|<\|>\|,\|; are always operators. Note that OperatorChars must be set in the configuration file before any rulesets. .ip PidFile=\fIfilename\fP [no short name] Filename of the pid file. (default is _PATH_SENDMAILPID). The .i filename is macro-expanded before it is opened, and unlinked when .i sendmail exits. .ip PostmasterCopy=\fIpostmaster\fP [P] If set, copies of error messages will be sent to the named .i postmaster . Only the header of the failed message is sent. Errors resulting from messages with a negative precedence will not be sent. Since most errors are user problems, this is probably not a good idea on large sites, and arguably contains all sorts of privacy violations, but it seems to be popular with certain operating systems vendors. The address is macro expanded at the time of delivery. Defaults to no postmaster copies. .ip PrivacyOptions=\fI\|opt,opt,...\fP [p] Set the privacy .i opt ions. ``Privacy'' is really a misnomer; many of these are just a way of insisting on stricter adherence to the SMTP protocol. The .i opt ions can be selected from: .(b .ta \w'noactualrecipient'u+3n public Allow open access needmailhelo Insist on HELO or EHLO command before MAIL needexpnhelo Insist on HELO or EHLO command before EXPN noexpn Disallow EXPN entirely, implies noverb. needvrfyhelo Insist on HELO or EHLO command before VRFY novrfy Disallow VRFY entirely noetrn Disallow ETRN entirely noverb Disallow VERB entirely restrictmailq Restrict mailq command restrictqrun Restrict \-q command line flag restrictexpand Restrict \-bv and \-v command line flags noreceipts Don't return success DSNs\** nobodyreturn Don't return the body of a message with DSNs goaway Disallow essentially all SMTP status queries authwarnings Put X-Authentication-Warning: headers in messages and log warnings noactualrecipient Don't put X-Actual-Recipient lines in DSNs which reveal the actual account that addresses map to. .)b .(f \**N.B.: the .b noreceipts flag turns off support for RFC 1891 (Delivery Status Notification). .)f The .q goaway pseudo-flag sets all flags except .q noreceipts , .q restrictmailq , .q restrictqrun , .q restrictexpand , .q noetrn , and .q nobodyreturn . If mailq is restricted, only people in the same group as the queue directory can print the queue. If queue runs are restricted, only root and the owner of the queue directory can run the queue. The .q restrictexpand pseudo-flag instructs .i sendmail to drop privileges when the .b \-bv option is given by users who are neither root nor the TrustedUser so users cannot read private aliases, forwards, or :include: files. It will add the .q NonRootSafeAddr to the .q DontBlameSendmail option to prevent misleading unsafe address warnings. It also overrides the .b \-v (verbose) command line option to prevent information leakage. Authentication Warnings add warnings about various conditions that may indicate attempts to spoof the mail system, such as using a non-standard queue directory. .ip ProcessTitlePrefix=\fIstring\fP [no short name] Prefix the process title shown on 'ps' listings with .i string . The .i string will be macro processed. .ip QueueDirectory=\fIdir\fP [Q] The QueueDirectory option serves two purposes. First, it specifies the directory or set of directories that comprise the default queue group. Second, it specifies the directory D which is the ancestor of all queue directories, and which sendmail uses as its current working directory. When sendmail dumps core, it leaves its core files in D. There are two cases. If \fIdir\fR ends with an asterisk (eg, \fI/var/spool/mqueue/qd*\fR), then all of the directories or symbolic links to directories beginning with `qd' in .i /var/spool/mqueue will be used as queue directories of the default queue group, and .i /var/spool/mqueue will be used as the working directory D. Otherwise, \fIdir\fR must name a directory (usually \fI/var/spool/mqueue\fR): the default queue group consists of the single queue directory \fIdir\fR, and the working directory D is set to \fIdir\fR. To define additional groups of queue directories, use the configuration file `Q' command. Do not change the queue directory structure while sendmail is running. .ip QueueFactor=\fIfactor\fP [q] Use .i factor as the multiplier in the map function to decide when to just queue up jobs rather than run them. This value is divided by the difference between the current load average and the load average limit (\c .b QueueLA option) to determine the maximum message priority that will be sent. Defaults to 600000. .ip QueueLA=\fILA\fP [x] When the system load average exceeds .i LA and the .b QueueFactor (\c .b q ) option divided by the difference in the current load average and the .b QueueLA option plus one is less than the priority of the message, just queue messages (i.e., don't try to send them). Defaults to 8 multiplied by the number of processors online on the system (if that can be determined). .ip QueueFileMode=\fImode\fP [no short name] Default permissions for queue files (octal). If not set, sendmail uses 0600 unless its real and effective uid are different in which case it uses 0644. .ip QueueSortOrder=\fIalgorithm\fP [no short name] Sets the .i algorithm used for sorting the queue. Only the first character of the value is used. Legal values are .q host (to order by the name of the first host name of the first recipient), .q filename (to order by the name of the queue file name), .q time (to order by the submission/creation time), .q random (to order randomly), .q modification (to order by the modification time of the qf file (older entries first)), .q none (to not order), and .q priority (to order by message priority). Host ordering makes better use of the connection cache, but may tend to process low priority messages that go to a single host over high priority messages that go to several hosts; it probably shouldn't be used on slow network links. Filename and modification time ordering saves the overhead of reading all of the queued items before starting the queue run. Creation (submission) time ordering is almost always a bad idea, since it allows large, bulk mail to go out before smaller, personal mail, but may have applicability on some hosts with very fast connections. Random is useful if several queue runners are started by hand which try to drain the same queue since odds are they will be working on different parts of the queue at the same time. Priority ordering is the default. .ip QueueTimeout=\fItimeout\fP [T] A synonym for .q Timeout.queuereturn . Use that form instead of the .q QueueTimeout form. .ip RandFile [no short name] Name of file containing random data or the name of the UNIX socket if EGD is used. A (required) prefix "egd:" or "file:" specifies the type. STARTTLS requires this filename if the compile flag HASURANDOMDEV is not set (see sendmail/README). .ip ResolverOptions=\fIoptions\fP [I] Set resolver options. Values can be set using .b + \c .i flag and cleared using .b \- \c .i flag ; the .i flag s can be .q debug , .q aaonly , .q usevc , .q primary , .q igntc , .q recurse , .q defnames , .q stayopen , .q use_inet6 , or .q dnsrch . The string .q HasWildcardMX (without a .b + or .b \- ) can be specified to turn off matching against MX records when doing name canonifications. The string .q WorkAroundBrokenAAAA (without a .b + or .b \- ) can be specified to work around some broken nameservers which return SERVFAIL (a temporary failure) on T_AAAA (IPv6) lookups. Notice: it might be necessary to apply the same (or similar) options to .i submit.cf too. .ip RequiresDirfsync [no short name] This option can be used to override the compile time flag .b REQUIRES_DIR_FSYNC at runtime by setting it to .sm false . If the compile time flag is not set, the option is ignored. The flag turns on support for file systems that require to call .i fsync() for a directory if the meta-data in it has been changed. This should be turned on at least for older versions of ReiserFS; it is enabled by default for Linux. According to some information this flag is not needed anymore for kernel 2.4.16 and newer. .ip RrtImpliesDsn [R] If this option is set, a .q Return-Receipt-To: header causes the request of a DSN, which is sent to the envelope sender as required by RFC 1891, not to the address given in the header. .ip RunAsUser=\fIuser\fP [no short name] The .i user parameter may be a user name (looked up in .i /etc/passwd ) or a numeric user id; either form can have .q ":group" attached (where group can be numeric or symbolic). If set to a non-zero (non-root) value, .i sendmail will change to this user id shortly after startup\**. .(f \**When running as a daemon, it changes to this user after accepting a connection but before reading any .sm SMTP commands. .)f This avoids a certain class of security problems. However, this means that all .q \&.forward and .q :include: files must be readable by the indicated .i user and all files to be written must be writable by .i user Also, all file and program deliveries will be marked unsafe unless the option .b DontBlameSendmail=NonRootSafeAddr is set, in which case the delivery will be done as .i user . It is also incompatible with the .b SafeFileEnvironment option. In other words, it may not actually add much to security on an average system, and may in fact detract from security (because other file permissions must be loosened). However, it should be useful on firewalls and other places where users don't have accounts and the aliases file is well constrained. .ip RecipientFactor=\fIfact\fP [y] The indicated .i fact or is added to the priority (thus .i lowering the priority of the job) for each recipient, i.e., this value penalizes jobs with large numbers of recipients. Defaults to 30000. .ip RefuseLA=\fILA\fP [X] When the system load average exceeds .i LA , refuse incoming SMTP connections. Defaults to 12 multiplied by the number of processors online on the system (if that can be determined). .ip RejectLogInterval=\fItimeout\fP [no short name] Log interval when refusing connections for this long (default: 3h). .ip RetryFactor=\fIfact\fP [Z] The .i fact or is added to the priority every time a job is processed. Thus, each time a job is processed, its priority will be decreased by the indicated value. In most environments this should be positive, since hosts that are down are all too often down for a long time. Defaults to 90000. .ip SafeFileEnvironment=\fIdir\fP [no short name] If this option is set, .i sendmail will do a .i chroot (2) call into the indicated .i dir ectory before doing any file writes. If the file name specified by the user begins with .i dir , that partial path name will be stripped off before writing, so (for example) if the SafeFileEnvironment variable is set to .q /safe then aliases of .q /safe/logs/file and .q /logs/file actually indicate the same file. Additionally, if this option is set, .i sendmail refuses to deliver to symbolic links. .ip SaveFromLine [f] Save UNIX-style .q From lines at the front of headers. Normally they are assumed redundant and discarded. .ip SendMimeErrors [j] If set, send error messages in MIME format (see RFC 2045 and RFC 1344 for details). If disabled, .i sendmail will not return the DSN keyword in response to an EHLO and will not do Delivery Status Notification processing as described in RFC 1891. .ip ServerCertFile [no short name] File containing the certificate of the server, i.e., this certificate is used when sendmail acts as server (used for STARTTLS). .ip ServerKeyFile [no short name] File containing the private key belonging to the server certificate (used for STARTTLS). .ip ServiceSwitchFile=\fIfilename\fP [no short name] If your host operating system has a service switch abstraction (e.g., /etc/nsswitch.conf on Solaris or /etc/svc.conf on Ultrix and DEC OSF/1) that service will be consulted and this option is ignored. Otherwise, this is the name of a file that provides the list of methods used to implement particular services. The syntax is a series of lines, each of which is a sequence of words. The first word is the service name, and following words are service types. The services that .i sendmail consults directly are .q aliases and .q hosts. Service types can be .q dns , .q nis , .q nisplus , or .q files (with the caveat that the appropriate support must be compiled in before the service can be referenced). If ServiceSwitchFile is not specified, it defaults to /etc/mail/service.switch. If that file does not exist, the default switch is: .(b aliases files hosts dns nis files .)b The default file is .q /etc/mail/service.switch . .ip SevenBitInput [7] Strip input to seven bits for compatibility with old systems. This shouldn't be necessary. .ip SharedMemoryKey [no short name] Key to use for shared memory segment; if not set (or 0), shared memory will not be used. If set to -1 .i sendmail can select a key itself provided that also .b SharedMemoryKeyFile is set. Requires support for shared memory to be compiled into .i sendmail . If this option is set, .i sendmail can share some data between different instances. For example, the number of entries in a queue directory or the available space in a file system. This allows for more efficient program execution, since only one process needs to update the data instead of each individual process gathering the data each time it is required. .ip SharedMemoryKeyFile [no short name] If .b SharedMemoryKey is set to -1 then the automatically selected shared memory key will be stored in the specified file. .ip SingleLineFromHeader [no short name] If set, From: lines that have embedded newlines are unwrapped onto one line. This is to get around a botch in Lotus Notes that apparently cannot understand legally wrapped RFC 822 headers. .ip SingleThreadDelivery [no short name] If set, a client machine will never try to open two SMTP connections to a single server machine at the same time, even in different processes. That is, if another .i sendmail is already talking to some host a new .i sendmail will not open another connection. This property is of mixed value; although this reduces the load on the other machine, it can cause mail to be delayed (for example, if one .i sendmail is delivering a huge message, other .i sendmail s won't be able to send even small messages). Also, it requires another file descriptor (for the lock file) per connection, so you may have to reduce the .b ConnectionCacheSize option to avoid running out of per-process file descriptors. Requires the .b HostStatusDirectory option. .ip SmtpGreetingMessage=\fImessage\fP [$e macro] The message printed when the SMTP server starts up. Defaults to .q "$j Sendmail $v ready at $b". .ip SoftBounce If set, issue temporary errors (4xy) instead of permanent errors (5xy). This can be useful during testing of a new configuration to avoid erroneous bouncing of mails. .ip StatusFile=\fIfile\fP [S] Log summary statistics in the named .i file . If no file name is specified, "statistics" is used. If not set, no summary statistics are saved. This file does not grow in size. It can be printed using the .i mailstats (8) program. .ip SuperSafe [s] This option can be set to True, False, Interactive, or PostMilter. If set to True, .i sendmail will be super-safe when running things, i.e., always instantiate the queue file, even if you are going to attempt immediate delivery. .i Sendmail always instantiates the queue file before returning control to the client under any circumstances. This should really .i always be set to True. The Interactive value has been introduced in 8.12 and can be used together with .b DeliveryMode=i . It skips some synchronization calls which are effectively doubled in the code execution path for this mode. If set to PostMilter, .i sendmail defers synchronizing the queue file until any milters have signaled acceptance of the message. PostMilter is useful only when .i sendmail is running as an SMTP server; in all other situations it acts the same as True. .ip TLSSrvOptions [no short name] List of options for SMTP STARTTLS for the server consisting of single characters with intervening white space or commas. The flag ``V'' disables client verification, and hence it is not possible to use a client certificate for relaying. Currently there are no other flags available. .ip TempFileMode=\fImode\fP [F] The file mode for transcript files, files to which .i sendmail delivers directly, files in the .b HostStatusDirectory , and .b StatusFile . It is interpreted in octal by default. Defaults to 0600. .ip Timeout.\fItype\fP=\|\fItimeout\fP [r; subsumes old T option as well] Set timeout values. For more information, see section .\" XREF 4.1. .ip TimeZoneSpec=\fItzinfo\fP [t] Set the local time zone info to .i tzinfo \*- for example, .q PST8PDT . Actually, if this is not set, the TZ environment variable is cleared (so the system default is used); if set but null, the user's TZ variable is used, and if set and non-null the TZ variable is set to this value. .ip TrustedUser=\fIuser\fP [no short name] The .i user parameter may be a user name (looked up in .i /etc/passwd ) or a numeric user id. Trusted user for file ownership and starting the daemon. If set, generated alias databases and the control socket (if configured) will automatically be owned by this user. .ip TryNullMXList [w] If this system is the .q best (that is, lowest preference) MX for a given host, its configuration rules should normally detect this situation and treat that condition specially by forwarding the mail to a UUCP feed, treating it as local, or whatever. However, in some cases (such as Internet firewalls) you may want to try to connect directly to that host as though it had no MX records at all. Setting this option causes .i sendmail to try this. The downside is that errors in your configuration are likely to be diagnosed as .q "host unknown" or .q "message timed out" instead of something more meaningful. This option is disrecommended. .ip UnixFromLine=\fIfromline\fP [$l macro] Defines the format used when .i sendmail must add a UNIX-style From_ line (that is, a line beginning .q Fromuser ). Defaults to .q "From $g $d" . Don't change this unless your system uses a different UNIX mailbox format (very unlikely). .ip UnsafeGroupWrites [no short name] If set (default), :include: and .forward files that are group writable are considered .q unsafe , that is, they cannot reference programs or write directly to files. World writable :include: and .forward files are always unsafe. Note: use .b DontBlameSendmail instead; this option is deprecated. .ip UseErrorsTo [l] If there is an .q Errors-To: header, send error messages to the addresses listed there. They normally go to the envelope sender. Use of this option causes .i sendmail to violate RFC 1123. This option is disrecommended and deprecated. .ip UserDatabaseSpec=\fIudbspec\fP [U] The user database specification. .ip Verbose [v] Run in verbose mode. If this is set, .i sendmail adjusts options .b HoldExpensive (old .b c ) and .b DeliveryMode (old .b d ) so that all mail is delivered completely in a single job so that you can see the entire delivery process. Option .b Verbose should .i never be set in the configuration file; it is intended for command line use only. Note that the use of option .b Verbose can cause authentication information to leak, if you use a sendmail client to authenticate to a server. If the authentication mechanism uses plain text passwords (as with LOGIN or PLAIN), then the password could be compromised. To avoid this, do not install sendmail set-user-ID root, and disable the .b VERB SMTP command with a suitable .b PrivacyOptions setting. .ip XscriptFileBufferSize=\fIthreshold\fP [no short name] Set the .i threshold , in bytes, before a memory-based queue transcript file becomes disk-based. The default is 4096 bytes. .lp All options can be specified on the command line using the \-O or \-o flag, but most will cause .i sendmail to relinquish its set-user-ID permissions. The options that will not cause this are SevenBitInput [7], EightBitMode [8], MinFreeBlocks [b], CheckpointInterval [C], DeliveryMode [d], ErrorMode [e], IgnoreDots [i], SendMimeErrors [j], LogLevel [L], MeToo [m], OldStyleHeaders [o], PrivacyOptions [p], SuperSafe [s], Verbose [v], QueueSortOrder, MinQueueAge, DefaultCharSet, Dial Delay, NoRecipientAction, ColonOkInAddr, MaxQueueRunSize, SingleLineFromHeader, and AllowBogusHELO. Actually, PrivacyOptions [p] given on the command line are added to those already specified in the .i sendmail.cf file, i.e., they can't be reset. Also, M (define macro) when defining the r or s macros is also considered .q safe . .sh 2 "P \*- Precedence Definitions" .pp Values for the .q "Precedence:" field may be defined using the .b P control line. The syntax of this field is: .(b \fBP\fP\fIname\fP\fB=\fP\fInum\fP .)b When the .i name is found in a .q Precedence: field, the message class is set to .i num . Higher numbers mean higher precedence. Numbers less than zero have the special property that if an error occurs during processing the body of the message will not be returned; this is expected to be used for .q "bulk" mail such as through mailing lists. The default precedence is zero. For example, our list of precedences is: .(b Pfirst-class=0 Pspecial-delivery=100 Plist=\-30 Pbulk=\-60 Pjunk=\-100 .)b People writing mailing list exploders are encouraged to use .q "Precedence: list" . Older versions of .i sendmail (which discarded all error returns for negative precedences) didn't recognize this name, giving it a default precedence of zero. This allows list maintainers to see error returns on both old and new versions of .i sendmail . .sh 2 "V \*- Configuration Version Level" .pp To provide compatibility with old configuration files, the .b V line has been added to define some very basic semantics of the configuration file. These are not intended to be long term supports; rather, they describe compatibility features which will probably be removed in future releases. .pp .b N.B.: these version .i levels have nothing to do with the version .i number on the files. For example, as of this writing version 10 config files (specifically, 8.10) used version level 9 configurations. .pp .q Old configuration files are defined as version level one. Version level two files make the following changes: .np Host name canonification ($[ ... $]) appends a dot if the name is recognized; this gives the config file a way of finding out if anything matched. (Actually, this just initializes the .q host map with the .q \-a. flag \*- you can reset it to anything you prefer by declaring the map explicitly.) .np Default host name extension is consistent throughout processing; version level one configurations turned off domain extension (that is, adding the local domain name) during certain points in processing. Version level two configurations are expected to include a trailing dot to indicate that the name is already canonical. .np Local names that are not aliases are passed through a new distinguished ruleset five; this can be used to append a local relay. This behavior can be prevented by resolving the local name with an initial `@'. That is, something that resolves to a local mailer and a user name of .q vikki will be passed through ruleset five, but a user name of .q @vikki will have the `@' stripped, will not be passed through ruleset five, but will otherwise be treated the same as the prior example. The expectation is that this might be used to implement a policy where mail sent to .q vikki was handled by a central hub, but mail sent to .q vikki@localhost was delivered directly. .pp Version level three files allow # initiated comments on all lines. Exceptions are backslash escaped # marks and the $# syntax. .pp Version level four configurations are completely equivalent to level three for historical reasons. .pp Version level five configuration files change the default definition of .b $w to be just the first component of the hostname. .pp Version level six configuration files change many of the local processing options (such as aliasing and matching the beginning of the address for `|' characters) to be mailer flags; this allows fine-grained control over the special local processing. Level six configuration files may also use long option names. The .b ColonOkInAddr option (to allow colons in the local-part of addresses) defaults .b on for lower numbered configuration files; the configuration file requires some additional intelligence to properly handle the RFC 822 group construct. .pp Version level seven configuration files used new option names to replace old macros (\c .b $e became .b SmtpGreetingMessage , .b $l became .b UnixFromLine , and .b $o became .b OperatorChars . Also, prior to version seven, the .b F=q flag (use 250 instead of 252 return value for .sm "SMTP VRFY" commands) was assumed. .pp Version level eight configuration files allow .b $# on the left hand side of ruleset lines. .pp Version level nine configuration files allow parentheses in rulesets, i.e. they are not treated as comments and hence removed. .pp Version level ten configuration files allow queue group definitions. .pp The .b V line may have an optional .b / \c .i vendor to indicate that this configuration file uses modifications specific to a particular vendor\**. .(f \**And of course, vendors are encouraged to add themselves to the list of recognized vendors by editing the routine .i setvendor in .i conf.c . Please send e-mail to sendmail@Sendmail.ORG to register your vendor dialect. .)f You may use .q /Berkeley to emphasize that this configuration file uses the Berkeley dialect of .i sendmail . .sh 2 "K \*- Key File Declaration" .pp Special maps can be defined using the line: .(b Kmapname mapclass arguments .)b The .i mapname is the handle by which this map is referenced in the rewriting rules. The .i mapclass is the name of a type of map; these are compiled in to .i sendmail . The .i arguments are interpreted depending on the class; typically, there would be a single argument naming the file containing the map. .pp Maps are referenced using the syntax: .(b $( \fImap\fP \fIkey\fP $@ \fIarguments\fP $: \fIdefault\fP $) .)b where either or both of the .i arguments or .i default portion may be omitted. The .i "$@ arguments" may appear more than once. The indicated .i key and .i arguments are passed to the appropriate mapping function. If it returns a value, it replaces the input. If it does not return a value and the .i default is specified, the .i default replaces the input. Otherwise, the input is unchanged. .pp The .i arguments are passed to the map for arbitrary use. Most map classes can interpolate these arguments into their values using the syntax .q %\fIn\fP (where .i n is a digit) to indicate the corresponding .i argument . Argument .q %0 indicates the database key. For example, the rule .(b .ta 1.5i R$\- ! $+ $: $(uucp $1 $@ $2 $: $2 @ $1 . UUCP $) .)b Looks up the UUCP name in a (user defined) UUCP map; if not found it turns it into .q \&.UUCP form. The database might contain records like: .(b decvax %1@%0.DEC.COM research %1@%0.ATT.COM .)b Note that .i default clauses never do this mapping. .pp The built-in map with both name and class .q host is the host name canonicalization lookup. Thus, the syntax: .(b $(host \fIhostname\fP$) .)b is equivalent to: .(b $[\fIhostname\fP$] .)b .pp There are many defined classes. .ip dbm Database lookups using the ndbm(3) library. .i Sendmail must be compiled with .b NDBM defined. .ip btree Database lookups using the btree interface to the Berkeley DB library. .i Sendmail must be compiled with .b NEWDB defined. .ip hash Database lookups using the hash interface to the Berkeley DB library. .i Sendmail must be compiled with .b NEWDB defined. .ip nis NIS lookups. .i Sendmail must be compiled with .b NIS defined. .ip nisplus NIS+ lookups. .i Sendmail must be compiled with .b NISPLUS defined. The argument is the name of the table to use for lookups, and the .b \-k and .b \-v flags may be used to set the key and value columns respectively. .ip hesiod Hesiod lookups. .i Sendmail must be compiled with .b HESIOD defined. .ip ldap LDAP X500 directory lookups. .i Sendmail must be compiled with .b LDAPMAP defined. The map supports most of the standard arguments and most of the command line arguments of the .i ldapsearch program. Note that, by default, if a single query matches multiple values, only the first value will be returned unless the .b \-z (value separator) map flag is set. Also, the .b \-1 map flag will treat a multiple value return as if there were no matches. .ip netinfo NeXT NetInfo lookups. .i Sendmail must be compiled with .b NETINFO defined. .ip text Text file lookups. The format of the text file is defined by the .b \-k (key field number), .b \-v (value field number), and .b \-z (field delimiter) flags. .ip ph PH query map. Contributed and supported by Mark Roth, roth@uiuc.edu. For more information, consult the web site .q http://www-dev.cites.uiuc.edu/sendmail/ . .ip nsd nsd map for IRIX 6.5 and later. Contributed and supported by Bob Mende of SGI, mende@sgi.com. .ip stab Internal symbol table lookups. Used internally for aliasing. .ip implicit Really should be called .q alias \(em this is used to get the default lookups for alias files, and is the default if no class is specified for alias files. .ip user Looks up users using .i getpwnam (3). The .b \-v flag can be used to specify the name of the field to return (although this is normally used only to check the existence of a user). .ip host Canonifies host domain names. Given a host name it calls the name server to find the canonical name for that host. .ip bestmx Returns the best MX record for a host name given as the key. The current machine is always preferred \*- that is, if the current machine is one of the hosts listed as a lowest-preference MX record, then it will be guaranteed to be returned. This can be used to find out if this machine is the target for an MX record, and mail can be accepted on that basis. If the .b \-z flag is given, then all MX names are returned, separated by the given delimiter. .ip dns This map requires the option -R to specify the DNS resource record type to lookup. The following types are supported: A, AAAA, AFSDB, CNAME, MX, NS, PTR, SRV, and TXT. A map lookup will return only one record. Hence for some types, e.g., MX records, the return value might be a random element of the list due to randomizing in the DNS resolver. .ip sequence The arguments on the `K' line are a list of maps; the resulting map searches the argument maps in order until it finds a match for the indicated key. For example, if the key definition is: .(b Kmap1 ... Kmap2 ... Kseqmap sequence map1 map2 .)b then a lookup against .q seqmap first does a lookup in map1. If that is found, it returns immediately. Otherwise, the same key is used for map2. .ip syslog the key is logged via .i syslogd \|(8). The lookup returns the empty string. .ip switch Much like the .q sequence map except that the order of maps is determined by the service switch. The argument is the name of the service to be looked up; the values from the service switch are appended to the map name to create new map names. For example, consider the key definition: .(b Kali switch aliases .)b together with the service switch entry: .(b aliases nis files .)b This causes a query against the map .q ali to search maps named .q ali.nis and .q ali.files in that order. .ip dequote Strip double quotes (") from a name. It does not strip backslashes, and will not strip quotes if the resulting string would contain unscannable syntax (that is, basic errors like unbalanced angle brackets; more sophisticated errors such as unknown hosts are not checked). The intent is for use when trying to accept mail from systems such as DECnet that routinely quote odd syntax such as .(b "49ers::ubell" .)b A typical usage is probably something like: .(b Kdequote dequote \&... R$\- $: $(dequote $1 $) R$\- $+ $: $>3 $1 $2 .)b Care must be taken to prevent unexpected results; for example, .(b "|someprogram < input > output" .)b will have quotes stripped, but the result is probably not what you had in mind. Fortunately these cases are rare. .ip regex The map definition on the .b K line contains a regular expression. Any key input is compared to that expression using the POSIX regular expressions routines regcomp(), regerr(), and regexec(). Refer to the documentation for those routines for more information about the regular expression matching. No rewriting of the key is done if the .b \-m flag is used. Without it, the key is discarded or if .b \-s if used, it is substituted by the substring matches, delimited by .b $| or the string specified with the the .b \-d flag. The flags available for the map are .(b .ta 4n -n not -f case sensitive -b basic regular expressions (default is extended) -s substring match -d set the delimiter used for -s -a append string to key -m match only, do not replace/discard value -D perform no lookup in deferred delivery mode. .)b The .b \-s flag can include an optional parameter which can be used to select the substrings in the result of the lookup. For example, .(b -s1,3,4 .)b Notes: to match a .b $ in a string, \\$$ must be used. If the pattern contains spaces, they must be replaced with the blank substitution character, unless it is space itself. .ip program The arguments on the .b K line are the pathname to a program and any initial parameters to be passed. When the map is called, the key is added to the initial parameters and the program is invoked as the default user/group id. The first line of standard output is returned as the value of the lookup. This has many potential security problems, and has terrible performance; it should be used only when absolutely necessary. .ip macro Set or clear a macro value. To set a macro, pass the value as the first argument in the map lookup. To clear a macro, do not pass an argument in the map lookup. The map always returns the empty string. Example of typical usage include: .(b Kstorage macro \&... # set macro ${MyMacro} to the ruleset match R$+ $: $(storage {MyMacro} $@ $1 $) $1 # set macro ${MyMacro} to an empty string R$* $: $(storage {MyMacro} $@ $) $1 # clear macro ${MyMacro} R$\- $: $(storage {MyMacro} $) $1 .)b .ip arith Perform simple arithmetic operations. The operation is given as key, currently +, -, *, /, %, |, & (bitwise OR, AND), l (for less than), =, and r (for random) are supported. The two operands are given as arguments. The lookup returns the result of the computation, i.e., .sm TRUE or .sm FALSE for comparisons, integer values otherwise. The r operator returns a pseudo-random number whose value lies between the first and second operand (which requires that the first operand is smaller than the second). All options which are possible for maps are ignored. A simple example is: .(b Kcomp arith \&... Scheck_etrn R$* $: $(comp l $@ $&{load_avg} $@ 7 $) $1 RFALSE $# error \&... .)b .ip socket The socket map uses a simple request/reply protocol over TCP or UNIX domain sockets to query an external server. Both requests and replies are text based and encoded as netstrings, i.e., a string "hello there" becomes: .(b 11:hello there, .)b Note: neither requests nor replies end with CRLF. The request consists of the database map name and the lookup key separated by a space character: .(b ' ' .)b The server responds with a status indicator and the result (if any): .(b ' ' .)b The status indicator specifies the result of the lookup operation itself and is one of the following upper case words: .(b .ta 9n OK the key was found, result contains the looked up value NOTFOUND the key was not found, the result is empty TEMP a temporary failure occured TIMEOUT a timeout occured on the server side PERM a permanent failure occured .)b In case of errors (status TEMP, TIMEOUT or PERM) the result field may contain an explanatory message. However, the explanatory message is not used any further by .i sendmail . Example replies: .(b 31:OK resolved.address@example.com, .)b .(b 56:OK error:550 5.7.1 User does not accept mail from sender, .)b in case of successful lookups, or: .(b 8:NOTFOUND, .)b in case the key was not found, or: .(b 55:TEMP this text explains that we had a temporary failure, .)b in case of a temporary map lookup failure. The socket map uses the same syntax as milters (see Section "X \*- Mail Filter (Milter) Definitions") to specify the remote endpoint, e.g., .(b Ksocket mySocketMap inet:12345@127.0.0.1 .)b If multiple socket maps define the same remote endpoint, they will share a single connection to this endpoint. .pp Most of these accept as arguments the same optional flags and a filename (or a mapname for NIS; the filename is the root of the database path, so that .q .db or some other extension appropriate for the database type will be added to get the actual database name). Known flags are: .ip "\-o" Indicates that this map is optional \*- that is, if it cannot be opened, no error is produced, and .i sendmail will behave as if the map existed but was empty. .ip "\-N, \-O" If neither .b \-N or .b \-O are specified, .i sendmail uses an adaptive algorithm to decide whether or not to look for null bytes on the end of keys. It starts by trying both; if it finds any key with a null byte it never tries again without a null byte and vice versa. If .b \-N is specified it never tries without a null byte and if .b \-O is specified it never tries with a null byte. Setting one of these can speed matches but are never necessary. If both .b \-N and .b \-O are specified, .i sendmail will never try any matches at all \(em that is, everything will appear to fail. .ip "\-a\fIx\fP" Append the string .i x on successful matches. For example, the default .i host map appends a dot on successful matches. .ip "\-T\fIx\fP" Append the string .i x on temporary failures. For example, .i x would be appended if a DNS lookup returned .q "server failed" or an NIS lookup could not locate a server. See also the .b \-t flag. .ip "\-f" Do not fold upper to lower case before looking up the key. .ip "\-m" Match only (without replacing the value). If you only care about the existence of a key and not the value (as you might when searching the NIS map .q hosts.byname for example), this flag prevents the map from substituting the value. However, The \-a argument is still appended on a match, and the default is still taken if the match fails. .ip "\-k\fIkeycol\fP" The key column name (for NIS+) or number (for text lookups). For LDAP maps this is an LDAP filter string in which %s is replaced with the literal contents of the lookup key and %0 is replaced with the LDAP escaped contents of the lookup key according to RFC 2254. If the flag .b \-K is used, then %1 through %9 are replaced with the LDAP escaped contents of the arguments specified in the map lookup. .ip "\-v\fIvalcol\fP" The value column name (for NIS+) or number (for text lookups). For LDAP maps this is the name of one or more attributes to be returned; multiple attributes can be separated by commas. If not specified, all attributes found in the match will be returned. The attributes listed can also include a type and one or more objectClass values for matching as described in the LDAP section. .ip "\-z\fIdelim\fP" The column delimiter (for text lookups). It can be a single character or one of the special strings .q \|\en or .q \|\et to indicate newline or tab respectively. If omitted entirely, the column separator is any sequence of white space. For LDAP maps this is the separator character to combine multiple values into a single return string. If not set, the LDAP lookup will only return the first match found. For DNS maps this is the separator character at which the result of a query is cut off if is too long. .ip "\-t" Normally, when a map attempts to do a lookup and the server fails (e.g., .i sendmail couldn't contact any name server; this is .i not the same as an entry not being found in the map), the message being processed is queued for future processing. The .b \-t flag turns off this behavior, letting the temporary failure (server down) act as though it were a permanent failure (entry not found). It is particularly useful for DNS lookups, where someone else's misconfigured name server can cause problems on your machine. However, care must be taken to ensure that you don't bounce mail that would be resolved correctly if you tried again. A common strategy is to forward such mail to another, possibly better connected, mail server. .ip "\-D" Perform no lookup in deferred delivery mode. This flag is set by default for the .i host map. .ip "\-S\fIspacesub\fP The character to use to replace space characters after a successful map lookup (esp. useful for regex and syslog maps). .ip "\-s\fIspacesub\fP For the dequote map only, the character to use to replace space characters after a successful dequote. .ip "\-q" Don't dequote the key before lookup. .ip "\-L\fIlevel\fP For the syslog map only, it specifies the level to use for the syslog call. .ip "\-A" When rebuilding an alias file, the .b \-A flag causes duplicate entries in the text version to be merged. For example, two entries: .(b list: user1, user2 list: user3 .)b would be treated as though it were the single entry .(b list: user1, user2, user3 .)b in the presence of the .b \-A flag. .pp Some additional flags are available for the host and dns maps: .ip "\-d" delay: specify the resolver's retransmission time interval (in seconds). .ip "\-r" retry: specify the number of times to retransmit a resolver query. .pp The dns map has another flag: .ip "\-B" basedomain: specify a domain that is always appended to queries. .pp The following additional flags are present in the ldap map only: .ip "\-R" Do not auto chase referrals. sendmail must be compiled with .b \-DLDAP_REFERRALS to use this flag. .ip "\-n" Retrieve attribute names only. .ip "\-V\fIsep\fP" Retrieve both attributes name and value(s), separated by .i sep . .ip "\-r\fIderef\fP" Set the alias dereference option to one of never, always, search, or find. .ip "\-s\fIscope\fP" Set search scope to one of base, one (one level), or sub (subtree). .ip "\-h\fIhost\fP" LDAP server hostname. Some LDAP libraries allow you to specify multiple, space-separated hosts for redundancy. In addition, each of the hosts listed can be followed by a colon and a port number to override the default LDAP port. .ip "\-p\fIport\fP" LDAP service port. .ip "\-H \fILDAPURI\fP" Use the specified LDAP URI instead of specifying the hostname and port separately with the the .b \-h and .b \-p options shown above. For example, .(b -h server.example.com -p 389 -b dc=example,dc=com .)b is equivalent to .(b -H ldap://server.example.com:389 -b dc=example,dc=com .)b If the LDAP library supports it, the LDAP URI format however can also request LDAP over SSL by using .b ldaps:// instead of .b ldap:// . For example: .(b O LDAPDefaultSpec=-H ldaps://ldap.example.com -b dc=example,dc=com .)b Similarly, if the LDAP library supports it, It can also be used to specify a UNIX domain socket using .b ldapi:// : .(b O LDAPDefaultSpec=-H ldapi://socketfile -b dc=example,dc=com .)b .ip "\-b\fIbase\fP" LDAP search base. .ip "\-l\fItimelimit\fP" Time limit for LDAP queries. .ip "\-Z\fIsizelimit\fP" Size (number of matches) limit for LDAP or DNS queries. .ip "\-d\fIdistinguished_name\fP" The distinguished name to use to login to the LDAP server. .ip "\-M\fImethod\fP" The method to authenticate to the LDAP server. Should be one of .b LDAP_AUTH_NONE , .b LDAP_AUTH_SIMPLE , or .b LDAP_AUTH_KRBV4 . .ip "\-P\fIpasswordfile\fP" The file containing the secret key for the .b LDAP_AUTH_SIMPLE authentication method or the name of the Kerberos ticket file for .b LDAP_AUTH_KRBV4 . .ip "\-1" Force LDAP searches to only succeed if a single match is found. If multiple values are found, the search is treated as if no match was found. .ip "\-w\fIversion\fP" Set the LDAP API/protocol version to use. The default depends on the LDAP client libraries in use. For example, .b "\-w 3" will cause .i sendmail to use LDAPv3 when communicating with the LDAP server. .ip "\-K" Treat the LDAP search key as multi-argument and replace %1 through %9 in the key with the LDAP escaped contents of the lookup arguments specified in the map lookup. .pp The .i dbm map appends the strings .q \&.pag and .q \&.dir to the given filename; the .i hash and .i btree maps append .q \&.db . For example, the map specification .(b Kuucp dbm \-o \-N /etc/mail/uucpmap .)b specifies an optional map named .q uucp of class .q dbm ; it always has null bytes at the end of every string, and the data is located in /etc/mail/uucpmap.{dir,pag}. .pp The program .i makemap (8) can be used to build any of the three database-oriented maps. It takes the following flags: .ip \-f Do not fold upper to lower case in the map. .ip \-N Include null bytes in keys. .ip \-o Append to an existing (old) file. .ip \-r Allow replacement of existing keys; normally, re-inserting an existing key is an error. .ip \-v Print what is happening. .lp The .i sendmail daemon does not have to be restarted to read the new maps as long as you change them in place; file locking is used so that the maps won't be read while they are being updated. .pp New classes can be added in the routine .b setupmaps in file .b conf.c . .sh 2 "Q \*- Queue Group Declaration" .pp In addition to the option .i QueueDirectory, queue groups can be declared that define a (group of) queue directories under a common name. The syntax is as follows: .(b F .b Q \c .i name {, \c .i field =\c .i value \|}+ .)b where .i name is the symbolic name of the queue group under which it can be referenced in various places and the .q field=value pairs define attributes of the queue group. The name must only consist of alphanumeric characters. Fields are: .ip Flags Flags for this queue group. .ip Nice The nice(2) increment for the queue group. This value must be greater or equal zero. .ip Interval The time between two queue runs. .ip Path The queue directory of the group (required). .ip Runners The number of parallel runners processing the queue. Note that .b F=f must be set if this value is greater than one. .ip Jobs The maximum number of jobs (messages delivered) per queue run. .ip recipients The maximum number of recipients per envelope. Envelopes with more than this number of recipients will be split into multiple envelopes in the same queue directory. The default value 0 means no limit. .lp Only the first character of the field name is checked. .pp By default, a queue group named .i mqueue is defined that uses the value of the .i QueueDirectory option as path. Notice: all paths that are used for queue groups must be subdirectories of .i QueueDirectory . Since they can be symbolic links, this isn't a real restriction, If .i QueueDirectory uses a wildcard, then the directory one level up is considered the ``base'' directory which all other queue directories must share. Please make sure that the queue directories do not overlap, e.g., do not specify .(b O QueueDirectory=/var/spool/mqueue/* Qone, P=/var/spool/mqueue/dir1 Qtwo, P=/var/spool/mqueue/dir2 .)b because this also includes .q dir1 and .q dir2 in the default queue group. However, .(b O QueueDirectory=/var/spool/mqueue/main* Qone, P=/var/spool/mqueue/dir Qtwo, P=/var/spool/mqueue/other* .)b is a valid queue group specification. .pp Options listed in the ``Flags'' field can be used to modify the behavior of a queue group. The ``f'' flag must be set if multiple queue runners are supposed to work on the entries in a queue group. Otherwise .i sendmail will work on the entries strictly sequentially. .pp The ``Interval'' field sets the time between queue runs. If no queue group specific interval is set, then the parameter of the .b -q option from the command line is used. .pp To control the overall number of concurrently active queue runners the option .b MaxQueueChildren can be set. This limits the number of processes used for running the queues to .b MaxQueueChildren , though at any one time fewer processes may be active as a result of queue options, completed queue runs, system load, etc. .pp The maximum number of queue runners for an individual queue group can be controlled via the .b Runners option. If set to 0, entries in the queue will not be processed, which is useful to ``quarantine'' queue files. The number of runners per queue group may also be set with the option .b MaxRunnersPerQueue , which applies to queue groups that have no individual limit. That is, the default value for .b Runners is .b MaxRunnersPerQueue if set, otherwise 1. .pp The field Jobs describes the maximum number of jobs (messages delivered) per queue run, which is the queue group specific value of .b MaxQueueRunSize . .pp Notice: queue groups should be declared after all queue related options have been set because queue groups take their defaults from those options. If an option is set after a queue group declaration, the values of options in the queue group are set to the defaults of .i sendmail unless explicitly set in the declaration. .pp Each envelope is assigned to a queue group based on the algorithm described in section ``Queue Groups and Queue Directories''. .sh 2 "X \*- Mail Filter (Milter) Definitions" .pp The .i sendmail Mail Filter API (Milter) is designed to allow third-party programs access to mail messages as they are being processed in order to filter meta-information and content. They are declared in the configuration file as: .(b F .b X \c .i name {, \c .i field =\c .i value \|}* .)b where .i name is the name of the filter (used internally only) and the .q field=name pairs define attributes of the filter. Also see the documentation for the .b InputMailFilters option for more information. .pp Fields are: .(b .ta 1i Socket The socket specification Flags Special flags for this filter Timeouts Timeouts for this filter .)b Only the first character of the field name is checked (it's case-sensitive). .pp The socket specification is one of the following forms: .(b F .b S= \c .b inet \c .b : .i port .b @ .i host .)b .(b F .b S= \c .b inet6 \c .b : .i port .b @ .i host .)b .(b F .b S= \c .b local \c .b : .i path .)b The first two describe an IPv4 or IPv6 socket listening on a certain .i port at a given .i host or IP address. The final form describes a named socket on the filesystem at the given .i path . .pp The following flags may be set in the filter description. .nr ii 4n .ip R Reject connection if filter unavailable. .ip T Temporary fail connection if filter unavailable. .pp If neither F=R nor F=T is specified, the message is passed through .i sendmail in case of filter errors as if the failing filters were not present. .pp The timeouts can be set using the four fields inside of the .b T= equate: .nr ii 4n .ip C Timeout for connecting to a filter. If set to 0, the system's .i connect() timeout will be used. .ip S Timeout for sending information from the MTA to a filter. .ip R Timeout for reading reply from the filter. .ip E Overall timeout between sending end-of-message to filter and waiting for the final acknowledgment. .pp Note the separator between each timeout field is a .b ';' . The default values (if not set) are: .b T=C:5m;S:10s;R:10s;E:5m where .b s is seconds and .b m is minutes. .pp Examples: .(b Xfilter1, S=local:/var/run/f1.sock, F=R Xfilter2, S=inet6:999@localhost, F=T, T=S:1s;R:1s;E:5m Xfilter3, S=inet:3333@localhost, T=C:2m .)b .sh 2 "The User Database" .pp The user database is deprecated in favor of ``virtusertable'' and ``genericstable'' as explained in the file .b cf/README . If you have a version of .i sendmail with the user database package compiled in, the handling of sender and recipient addresses is modified. .pp The location of this database is controlled with the .b UserDatabaseSpec option. .sh 3 "Structure of the user database" .pp The database is a sorted (BTree-based) structure. User records are stored with the key: .(b \fIuser-name\fP\fB:\fP\fIfield-name\fP .)b The sorted database format ensures that user records are clustered together. Meta-information is always stored with a leading colon. .pp Field names define both the syntax and semantics of the value. Defined fields include: .nr ii 1i .ip maildrop The delivery address for this user. There may be multiple values of this record. In particular, mailing lists will have one .i maildrop record for each user on the list. .ip "mailname" The outgoing mailname for this user. For each outgoing name, there should be an appropriate .i maildrop record for that name to allow return mail. See also .i :default:mailname . .ip mailsender Changes any mail sent to this address to have the indicated envelope sender. This is intended for mailing lists, and will normally be the name of an appropriate -request address. It is very similar to the owner-\c .i list syntax in the alias file. .ip fullname The full name of the user. .ip office-address The office address for this user. .ip office-phone The office phone number for this user. .ip office-fax The office FAX number for this user. .ip home-address The home address for this user. .ip home-phone The home phone number for this user. .ip home-fax The home FAX number for this user. .ip project A (short) description of the project this person is affiliated with. In the University this is often just the name of their graduate advisor. .ip plan A pointer to a file from which plan information can be gathered. .pp As of this writing, only a few of these fields are actually being used by .i sendmail : .i maildrop and .i mailname . A .i finger program that uses the other fields is planned. .sh 3 "User database semantics" .pp When the rewriting rules submit an address to the local mailer, the user name is passed through the alias file. If no alias is found (or if the alias points back to the same address), the name (with .q :maildrop appended) is then used as a key in the user database. If no match occurs (or if the maildrop points at the same address), forwarding is tried. .pp If the first token of the user name returned by ruleset 0 is an .q @ sign, the user database lookup is skipped. The intent is that the user database will act as a set of defaults for a cluster (in our case, the Computer Science Division); mail sent to a specific machine should ignore these defaults. .pp When mail is sent, the name of the sending user is looked up in the database. If that user has a .q mailname record, the value of that record is used as their outgoing name. For example, I might have a record: .(b eric:mailname Eric.Allman@CS.Berkeley.EDU .)b This would cause my outgoing mail to be sent as Eric.Allman. .pp If a .q maildrop is found for the user, but no corresponding .q mailname record exists, the record .q :default:mailname is consulted. If present, this is the name of a host to override the local host. For example, in our case we would set it to .q CS.Berkeley.EDU . The effect is that anyone known in the database gets their outgoing mail stamped as .q user@CS.Berkeley.EDU , but people not listed in the database use the local hostname. .sh 3 "Creating the database\**" .(f \**These instructions are known to be incomplete. Other features are available which provide similar functionality, e.g., virtual hosting and mapping local addresses into a generic form as explained in cf/README. .)f .pp The user database is built from a text file using the .i makemap utility (in the distribution in the makemap subdirectory). The text file is a series of lines corresponding to userdb records; each line has a key and a value separated by white space. The key is always in the format described above \*- for example: .(b eric:maildrop .)b This file is normally installed in a system directory; for example, it might be called .i /etc/mail/userdb . To make the database version of the map, run the program: .(b makemap btree /etc/mail/userdb < /etc/mail/userdb .)b Then create a config file that uses this. For example, using the V8 M4 configuration, include the following line in your .mc file: .(b define(\`confUSERDB_SPEC\', /etc/mail/userdb) .)b .sh 1 "OTHER CONFIGURATION" .pp There are some configuration changes that can be made by recompiling .i sendmail . This section describes what changes can be made and what has to be modified to make them. In most cases this should be unnecessary unless you are porting .i sendmail to a new environment. .sh 2 "Parameters in devtools/OS/$oscf" .pp These parameters are intended to describe the compilation environment, not site policy, and should normally be defined in the operating system configuration file. .b "This section needs a complete rewrite." .ip NDBM If set, the new version of the DBM library that allows multiple databases will be used. If neither NDBM nor NEWDB are set, a much less efficient method of alias lookup is used. .ip NEWDB If set, use the new database package from Berkeley (from 4.4BSD). This package is substantially faster than DBM or NDBM. If NEWDB and NDBM are both set, .i sendmail will read DBM files, but will create and use NEWDB files. .ip NIS Include support for NIS. If set together with .i both NEWDB and NDBM, .i sendmail will create both DBM and NEWDB files if and only if an alias file includes the substring .q /yp/ in the name. This is intended for compatibility with Sun Microsystems' .i mkalias program used on YP masters. .ip NISPLUS Compile in support for NIS+. .ip NETINFO Compile in support for NetInfo (NeXT stations). .ip LDAPMAP Compile in support for LDAP X500 queries. Requires libldap and liblber from the Umich LDAP 3.2 or 3.3 release or equivalent libraries for other LDAP libraries such as OpenLDAP. .ip HESIOD Compile in support for Hesiod. .ip MAP_NSD Compile in support for IRIX NSD lookups. .ip MAP_REGEX Compile in support for regular expression matching. .ip DNSMAP Compile in support for DNS map lookups in the .i sendmail.cf file. .ip PH_MAP Compile in support for ph lookups. .ip SASL Compile in support for SASL, a required component for SMTP Authentication support. .ip STARTTLS Compile in support for STARTTLS. .ip EGD Compile in support for the "Entropy Gathering Daemon" to provide better random data for TLS. .ip TCPWRAPPERS Compile in support for TCP Wrappers. .ip _PATH_SENDMAILCF The pathname of the sendmail.cf file. .ip _PATH_SENDMAILPID The pathname of the sendmail.pid file. .ip SM_CONF_SHM Compile in support for shared memory, see section about "/var/spool/mqueue". .ip MILTER Compile in support for contacting external mail filters built with the Milter API. .pp There are also several compilation flags to indicate the environment such as .q _AIX3 and .q _SCO_unix_ . See the sendmail/README file for the latest scoop on these flags. .sh 2 "Parameters in sendmail/conf.h" .pp Parameters and compilation options are defined in conf.h. Most of these need not normally be tweaked; common parameters are all in sendmail.cf. However, the sizes of certain primitive vectors, etc., are included in this file. The numbers following the parameters are their default value. .pp This document is not the best source of information for compilation flags in conf.h \(em see sendmail/README or sendmail/conf.h itself. .nr ii 1.2i .ip "MAXLINE [2048]" The maximum line length of any input line. If message lines exceed this length they will still be processed correctly; however, header lines, configuration file lines, alias lines, etc., must fit within this limit. .ip "MAXNAME [256]" The maximum length of any name, such as a host or a user name. .ip "MAXPV [256]" The maximum number of parameters to any mailer. This limits the number of recipients that may be passed in one transaction. It can be set to any arbitrary number above about 10, since .i sendmail will break up a delivery into smaller batches as needed. A higher number may reduce load on your system, however. .ip "MAXQUEUEGROUPS [50]" The maximum number of queue groups. .ip "MAXATOM [1000]" The maximum number of atoms (tokens) in a single address. For example, the address .q "eric@CS.Berkeley.EDU" is seven atoms. .ip "MAXMAILERS [25]" The maximum number of mailers that may be defined in the configuration file. This value is defined in include/sendmail/sendmail.h. .ip "MAXRWSETS [200]" The maximum number of rewriting sets that may be defined. The first half of these are reserved for numeric specification (e.g., ``S92''), while the upper half are reserved for auto-numbering (e.g., ``Sfoo''). Thus, with a value of 200 an attempt to use ``S99'' will succeed, but ``S100'' will fail. .ip "MAXPRIORITIES [25]" The maximum number of values for the .q Precedence: field that may be defined (using the .b P line in sendmail.cf). .ip "MAXUSERENVIRON [100]" The maximum number of items in the user environment that will be passed to subordinate mailers. .ip "MAXMXHOSTS [100]" The maximum number of MX records we will accept for any single host. .ip "MAXMAPSTACK [12]" The maximum number of maps that may be "stacked" in a .b sequence class map. .ip "MAXMIMEARGS [20]" The maximum number of arguments in a MIME Content-Type: header; additional arguments will be ignored. .ip "MAXMIMENESTING [20]" The maximum depth to which MIME messages may be nested (that is, nested Message or Multipart documents; this does not limit the number of components in a single Multipart document). .ip "MAXDAEMONS [10]" The maximum number of sockets sendmail will open for accepting connections on different ports. .ip "MAXMACNAMELEN [25]" The maximum length of a macro name. .lp A number of other compilation options exist. These specify whether or not specific code should be compiled in. Ones marked with \(dg are 0/1 valued. .nr ii 1.2i .ip NETINET\(dg If set, support for Internet protocol networking is compiled in. Previous versions of .i sendmail referred to this as .sm DAEMON ; this old usage is now incorrect. Defaults on; turn it off in the Makefile if your system doesn't support the Internet protocols. .ip NETINET6\(dg If set, support for IPv6 networking is compiled in. It must be separately enabled by adding .b DaemonPortOptions settings. .ip NETISO\(dg If set, support for ISO protocol networking is compiled in (it may be appropriate to #define this in the Makefile instead of conf.h). .ip NETUNIX\(dg If set, support for UNIX domain sockets is compiled in. This is used for control socket support. .ip LOG If set, the .i syslog routine in use at some sites is used. This makes an informational log record for each message processed, and makes a higher priority log record for internal system errors. .b "STRONGLY RECOMMENDED" \(em if you want no logging, turn it off in the configuration file. .ip MATCHGECOS\(dg Compile in the code to do ``fuzzy matching'' on the GECOS field in /etc/passwd. This also requires that the .b MatchGECOS option be turned on. .ip NAMED_BIND\(dg Compile in code to use the Berkeley Internet Name Domain (BIND) server to resolve TCP/IP host names. .ip NOTUNIX If you are using a non-UNIX mail format, you can set this flag to turn off special processing of UNIX-style .q "From " lines. .ip USERDB\(dg Include the .b experimental Berkeley user information database package. This adds a new level of local name expansion between aliasing and forwarding. It also uses the NEWDB package. This may change in future releases. .lp The following options are normally turned on in per-operating-system clauses in conf.h. .ip IDENTPROTO\(dg Compile in the IDENT protocol as defined in RFC 1413. This defaults on for all systems except Ultrix, which apparently has the interesting .q feature that when it receives a .q "host unreachable" message it closes all open connections to that host. Since some firewall gateways send this error code when you access an unauthorized port (such as 113, used by IDENT), Ultrix cannot receive email from such hosts. .ip SYSTEM5 Set all of the compilation parameters appropriate for System V. .ip HASFLOCK\(dg Use Berkeley-style .b flock instead of System V .b lockf to do file locking. Due to the highly unusual semantics of locks across forks in .b lockf , this should always be used if at all possible. .ip HASINITGROUPS Set this if your system has the .i initgroups() call (if you have multiple group support). This is the default if SYSTEM5 is .i not defined or if you are on HPUX. .ip HASUNAME Set this if you have the .i uname (2) system call (or corresponding library routine). Set by default if SYSTEM5 is set. .ip HASGETDTABLESIZE Set this if you have the .i getdtablesize (2) system call. .ip HASWAITPID Set this if you have the .i haswaitpid (2) system call. .ip FAST_PID_RECYCLE Set this if your system can possibly reuse the same pid in the same second of time. .ip SFS_TYPE The mechanism that can be used to get file system capacity information. The values can be one of SFS_USTAT (use the ustat(2) syscall), SFS_4ARGS (use the four argument statfs(2) syscall), SFS_VFS (use the two argument statfs(2) syscall including ), SFS_MOUNT (use the two argument statfs(2) syscall including ), SFS_STATFS (use the two argument statfs(2) syscall including ), SFS_STATVFS (use the two argument statfs(2) syscall including ), or SFS_NONE (no way to get this information). .ip LA_TYPE The load average type. Details are described below. .lp The are several built-in ways of computing the load average. .i Sendmail tries to auto-configure them based on imperfect guesses; you can select one using the .i cc option .b \-DLA_TYPE= \c .i type , where .i type is: .ip LA_INT The kernel stores the load average in the kernel as an array of long integers. The actual values are scaled by a factor FSCALE (default 256). .ip LA_SHORT The kernel stores the load average in the kernel as an array of short integers. The actual values are scaled by a factor FSCALE (default 256). .ip LA_FLOAT The kernel stores the load average in the kernel as an array of double precision floats. .ip LA_MACH Use MACH-style load averages. .ip LA_SUBR Call the .i getloadavg routine to get the load average as an array of doubles. .ip LA_ZERO Always return zero as the load average. This is the fallback case. .lp If type .sm LA_INT , .sm LA_SHORT , or .sm LA_FLOAT is specified, you may also need to specify .sm _PATH_UNIX (the path to your system binary) and .sm LA_AVENRUN (the name of the variable containing the load average in the kernel; usually .q _avenrun or .q avenrun ). .sh 2 "Configuration in sendmail/conf.c" .pp The following changes can be made in conf.c. .sh 3 "Built-in Header Semantics" .pp Not all header semantics are defined in the configuration file. Header lines that should only be included by certain mailers (as well as other more obscure semantics) must be specified in the .i HdrInfo table in .i conf.c . This table contains the header name (which should be in all lower case) and a set of header control flags (described below), The flags are: .ip H_ACHECK Normally when the check is made to see if a header line is compatible with a mailer, .i sendmail will not delete an existing line. If this flag is set, .i sendmail will delete even existing header lines. That is, if this bit is set and the mailer does not have flag bits set that intersect with the required mailer flags in the header definition in sendmail.cf, the header line is .i always deleted. .ip H_EOH If this header field is set, treat it like a blank line, i.e., it will signal the end of the header and the beginning of the message text. .ip H_FORCE Add this header entry even if one existed in the message before. If a header entry does not have this bit set, .i sendmail will not add another header line if a header line of this name already existed. This would normally be used to stamp the message by everyone who handled it. .ip H_TRACE If set, this is a timestamp (trace) field. If the number of trace fields in a message exceeds a preset amount the message is returned on the assumption that it has an aliasing loop. .ip H_RCPT If set, this field contains recipient addresses. This is used by the .b \-t flag to determine who to send to when it is collecting recipients from the message. .ip H_FROM This flag indicates that this field specifies a sender. The order of these fields in the .i HdrInfo table specifies .i sendmail 's preference for which field to return error messages to. .ip H_ERRORSTO Addresses in this header should receive error messages. .ip H_CTE This header is a Content-Transfer-Encoding header. .ip H_CTYPE This header is a Content-Type header. .ip H_STRIPVAL Strip the value from the header (for Bcc:). .nr ii 5n .lp Let's look at a sample .i HdrInfo specification: .(b .ta 4n +\w'"content-transfer-encoding", 'u struct hdrinfo HdrInfo[] = \&{ /* originator fields, most to least significant */ "resent-sender", H_FROM, "resent-from", H_FROM, "sender", H_FROM, "from", H_FROM, "full-name", H_ACHECK, "errors-to", H_FROM\^|\^H_ERRORSTO, /* destination fields */ "to", H_RCPT, "resent-to", H_RCPT, "cc", H_RCPT, "bcc", H_RCPT\^|\^H_STRIPVAL, /* message identification and control */ "message", H_EOH, "text", H_EOH, /* trace fields */ "received", H_TRACE\^|\^H_FORCE, /* miscellaneous fields */ "content-transfer-encoding", H_CTE, "content-type", H_CTYPE, NULL, 0, }; .)b This structure indicates that the .q To: , .q Resent-To: , and .q Cc: fields all specify recipient addresses. Any .q Full-Name: field will be deleted unless the required mailer flag (indicated in the configuration file) is specified. The .q Message: and .q Text: fields will terminate the header; these are used by random dissenters around the network world. The .q Received: field will always be added, and can be used to trace messages. .pp There are a number of important points here. First, header fields are not added automatically just because they are in the .i HdrInfo structure; they must be specified in the configuration file in order to be added to the message. Any header fields mentioned in the configuration file but not mentioned in the .i HdrInfo structure have default processing performed; that is, they are added unless they were in the message already. Second, the .i HdrInfo structure only specifies cliched processing; certain headers are processed specially by ad hoc code regardless of the status specified in .i HdrInfo . For example, the .q Sender: and .q From: fields are always scanned on ARPANET mail to determine the sender\**; .(f \**Actually, this is no longer true in SMTP; this information is contained in the envelope. The older ARPANET protocols did not completely distinguish envelope from header. .)f this is used to perform the .q "return to sender" function. The .q "From:" and .q "Full-Name:" fields are used to determine the full name of the sender if possible; this is stored in the macro .b $x and used in a number of ways. .sh 3 "Restricting Use of Email" .pp If it is necessary to restrict mail through a relay, the .i checkcompat routine can be modified. This routine is called for every recipient address. It returns an exit status indicating the status of the message. The status .sm EX_OK accepts the address, .sm EX_TEMPFAIL queues the message for a later try, and other values (commonly .sm EX_UNAVAILABLE ) reject the message. It is up to .i checkcompat to print an error message (using .i usrerr ) if the message is rejected. For example, .i checkcompat could read: .(b .re .sz -1 .ta 4n +4n +4n +4n +4n +4n +4n int checkcompat(to, e) register ADDRESS *to; register ENVELOPE *e; \&{ register STAB *s; s = stab("private", ST_MAILER, ST_FIND); if (s != NULL && e\->e_from.q_mailer != LocalMailer && to->q_mailer == s->s_mailer) { usrerr("No private net mail allowed through this machine"); return (EX_UNAVAILABLE); } if (MsgSize > 50000 && bitnset(M_LOCALMAILER, to\->q_mailer)) { usrerr("Message too large for non-local delivery"); e\->e_flags |= EF_NORETURN; return (EX_UNAVAILABLE); } return (EX_OK); } .sz .)b This would reject messages greater than 50000 bytes unless they were local. The .i EF_NORETURN flag can be set in .i e\(->e_flags to suppress the return of the actual body of the message in the error return. The actual use of this routine is highly dependent on the implementation, and use should be limited. .sh 3 "New Database Map Classes" .pp New key maps can be added by creating a class initialization function and a lookup function. These are then added to the routine .i setupmaps. .pp The initialization function is called as .(b \fIxxx\fP_map_init(MAP *map, char *args) .)b The .i map is an internal data structure. The .i args is a pointer to the portion of the configuration file line following the map class name; flags and filenames can be extracted from this line. The initialization function must return .sm true if it successfully opened the map, .sm false otherwise. .pp The lookup function is called as .(b \fIxxx\fP_map_lookup(MAP *map, char buf[], char **av, int *statp) .)b The .i map defines the map internally. The .i buf has the input key. This may be (and often is) used destructively. The .i av is a list of arguments passed in from the rewrite line. The lookup function should return a pointer to the new value. If the map lookup fails, .i *statp should be set to an exit status code; in particular, it should be set to .sm EX_TEMPFAIL if recovery is to be attempted by the higher level code. .sh 3 "Queueing Function" .pp The routine .i shouldqueue is called to decide if a message should be queued or processed immediately. Typically this compares the message priority to the current load average. The default definition is: .(b bool shouldqueue(pri, ctime) long pri; time_t ctime; { if (CurrentLA < QueueLA) return false; return (pri > (QueueFactor / (CurrentLA \- QueueLA + 1))); } .)b If the current load average (global variable .i CurrentLA , which is set before this function is called) is less than the low threshold load average (option .b x , variable .i QueueLA ), .i shouldqueue returns .sm false immediately (that is, it should .i not queue). If the current load average exceeds the high threshold load average (option .b X , variable .i RefuseLA ), .i shouldqueue returns .sm true immediately. Otherwise, it computes the function based on the message priority, the queue factor (option .b q , global variable .i QueueFactor ), and the current and threshold load averages. .pp An implementation wishing to take the actual age of the message into account can also use the .i ctime parameter, which is the time that the message was first submitted to .i sendmail . Note that the .i pri parameter is already weighted by the number of times the message has been tried (although this tends to lower the priority of the message with time); the expectation is that the .i ctime would be used as an .q "escape clause" to ensure that messages are eventually processed. .sh 3 "Refusing Incoming SMTP Connections" .pp The function .i refuseconnections returns .sm true if incoming SMTP connections should be refused. The current implementation is based exclusively on the current load average and the refuse load average option (option .b X , global variable .i RefuseLA ): .(b bool refuseconnections() { return (RefuseLA > 0 && CurrentLA >= RefuseLA); } .)b A more clever implementation could look at more system resources. .sh 3 "Load Average Computation" .pp The routine .i getla returns the current load average (as a rounded integer). The distribution includes several possible implementations. If you are porting to a new environment you may need to add some new tweaks.\** .(f \**If you do, please send updates to sendmail@Sendmail.ORG. .)f .sh 2 "Configuration in sendmail/daemon.c" .pp The file .i sendmail/daemon.c contains a number of routines that are dependent on the local networking environment. The version supplied assumes you have BSD style sockets. .pp In previous releases, we recommended that you modify the routine .i maphostname if you wanted to generalize .b $[ \&...\& .b $] lookups. We now recommend that you create a new keyed map instead. .sh 2 "LDAP" .pp In this section we assume that .i sendmail has been compiled with support for LDAP. .sh 3 "LDAP Recursion" .pp LDAP Recursion allows you to add types to the search attributes on an LDAP map specification. The syntax is: .ip "\-v \fIATTRIBUTE\fP[:\fITYPE\fP[:\fIOBJECTCLASS\fP[|\fIOBJECTCLASS\fP|...]]] .pp The new \fITYPE\fPs are: .nr ii 1i .ip NORMAL This attribute type specifies the attribute to add to the results string. This is the default. .ip DN Any matches for this attribute are expected to have a value of a fully qualified distinguished name. .i sendmail will lookup that DN and apply the attributes requested to the returned DN record. .ip FILTER Any matches for this attribute are expected to have a value of an LDAP search filter. .i sendmail will perform a lookup with the same parameters as the original search but replaces the search filter with the one specified here. .ip URL Any matches for this attribute are expected to have a value of an LDAP URL. .i sendmail will perform a lookup of that URL and use the results from the attributes named in that URL. Note however that the search is done using the current LDAP connection, regardless of what is specified as the scheme, LDAP host, and LDAP port in the LDAP URL. .lp Any untyped attributes are considered .sm NORMAL attributes as described above. .pp The optional \fIOBJECTCLASS\fP (| separated) list contains the objectClass values for which that attribute applies. If the list is given, the attribute named will only be used if the LDAP record being returned is a member of that object class. Note that if these new value attribute \fITYPE\fPs are used in an AliasFile option setting, it will need to be double quoted to prevent .i sendmail from misparsing the colons. .pp Note that LDAP recursion attributes which do not ultimately point to an LDAP record are not considered an error. .sh 4 "Example" .pp Since examples usually help clarify, here is an example which uses all four of the new types: .(b O LDAPDefaultSpec=-h ldap.example.com -b dc=example,dc=com Kexample ldap -z, -k (&(objectClass=sendmailMTAAliasObject)(sendmailMTAKey=%0)) -v sendmailMTAAliasValue,mail:NORMAL:inetOrgPerson, uniqueMember:DN:groupOfUniqueNames, sendmailMTAAliasSearch:FILTER:sendmailMTAAliasObject, sendmailMTAAliasURL:URL:sendmailMTAAliasObject .)b .pp That definition specifies that: .bu Any value in a .sm sendmailMTAAliasValue attribute will be added to the result string regardless of object class. .bu The .sm mail attribute will be added to the result string if the LDAP record is a member of the .sm inetOrgPerson object class. .bu The .sm uniqueMember attribute is a recursive attribute, used only in .sm groupOfUniqueNames records, and should contain an LDAP DN pointing to another LDAP record. The desire here is to return the .sm mail attribute from those DNs. .bu The .sm sendmailMTAAliasSearch attribute and .sm sendmailMTAAliasURL are both used only if referenced in a .sm sendmailMTAAliasObject . They are both recursive, the first for a new LDAP search string and the latter for an LDAP URL. .sh 2 "STARTTLS" .pp In this section we assume that .i sendmail has been compiled with support for STARTTLS. To properly understand the use of STARTTLS in .i sendmail , it is necessary to understand at least some basics about X.509 certificates and public key cryptography. This information can be found in books about SSL/TLS or on WWW sites, e.g., .q http://www.OpenSSL.org/ . .sh 3 "Certificates for STARTTLS" .pp When acting as a server, .i sendmail requires X.509 certificates to support STARTTLS: one as certificate for the server (ServerCertFile and corresponding private ServerKeyFile) at least one root CA (CACertFile), i.e., a certificate that is used to sign other certificates, and a path to a directory which contains other CAs (CACertPath). The file specified via CACertFile can contain several certificates of CAs. The DNs of these certificates are sent to the client during the TLS handshake (as part of the CertificateRequest) as the list of acceptable CAs. However, do not list too many root CAs in that file, otherwise the TLS handshake may fail; e.g., .(b error:14094417:SSL routines:SSL3_READ_BYTES: sslv3 alert illegal parameter:s3_pkt.c:964:SSL alert number 47 .)b You should probably put only the CA cert into that file that signed your own cert(s), or at least only those you trust. The CACertPath directory must contain the hashes of each CA certificate as filenames (or as links to them). Symbolic links can be generated with the following two (Bourne) shell commands: .(b C=FileName_of_CA_Certificate ln -s $C `openssl x509 -noout -hash < $C`.0 .)b An X.509 certificate is also required for authentication in client mode (ClientCertFile and corresponding private ClientKeyFile), however, .i sendmail will always use STARTTLS when offered by a server. The client and server certificates can be identical. Certificates can be obtained from a certificate authority or created with the help of OpenSSL. The required format for certificates and private keys is PEM. To allow for automatic startup of sendmail, private keys (ServerKeyFile, ClientKeyFile) must be stored unencrypted. The keys are only protected by the permissions of the file system. Never make a private key available to a third party. .sh 3 "PRNG for STARTTLS" .pp STARTTLS requires a strong pseudo random number generator (PRNG) to operate properly. Depending on the TLS library you use, it may be required to explicitly initialize the PRNG with random data. OpenSSL makes use of .b /dev/urandom(4) if available (this corresponds to the compile flag HASURANDOMDEV). On systems which lack this support, a random file must be specified in the .i sendmail.cf file using the option RandFile. It is .b strongly advised to use the "Entropy Gathering Daemon" EGD from Brian Warner on those systems to provide useful random data. In this case, .i sendmail must be compiled with the flag EGD, and the RandFile option must point to the EGD socket. If neither .b /dev/urandom(4) nor EGD are available, you have to make sure that useful random data is available all the time in RandFile. If the file hasn't been modified in the last 10 minutes before it is supposed to be used by .i sendmail the content is considered obsolete. One method for generating this file is: .(b openssl rand -out /etc/mail/randfile -rand \c .i /path/to/file:... \c 256 .)b See the OpenSSL documentation for more information. In this case, the PRNG for TLS is only seeded with other random data if the .b DontBlameSendmail option .b InsufficientEntropy is set. This is most likely not sufficient for certain actions, e.g., generation of (temporary) keys. .pp Please see the OpenSSL documentation or other sources for further information about certificates, their creation and their usage, the importance of a good PRNG, and other aspects of TLS. .sh 2 "Encoding of STARTTLS and AUTH related Macros" .pp Macros that contain STARTTLS and AUTH related data which comes from outside sources, e.g., all macros containing information from certificates, are encoded to avoid problems with non-printable or special characters. The latter are '\\', '<', '>', '(', ')', '"', '+', and ' '. All of these characters are replaced by their value in hexadecimal with a leading '+'. For example: .(b /C=US/ST=California/O=endmail.org/OU=private/CN=Darth Mail (Cert)/ Email=darth+cert@endmail.org .)b is encoded as: .(b /C=US/ST=California/O=endmail.org/OU=private/ CN=Darth+20Mail+20+28Cert+29/Email=darth+2Bcert@endmail.org .)b (line breaks have been inserted for readability). The macros which are subject to this encoding are {cert_subject}, {cert_issuer}, {cn_subject}, {cn_issuer}, as well as {auth_authen} and {auth_author}. .sh 1 "ACKNOWLEDGEMENTS" .pp I've worked on .i sendmail for many years, and many employers have been remarkably patient about letting me work on a large project that was not part of my official job. This includes time on the INGRES Project at the University of California at Berkeley, at Britton Lee, and again on the Mammoth and Titan Projects at Berkeley. .pp Much of the second wave of improvements resulting in version 8.1 should be credited to Bryan Costales of the International Computer Science Institute. As he passed me drafts of his book on .i sendmail I was inspired to start working on things again. Bryan was also available to bounce ideas off of. .pp Gregory Neil Shapiro of Worcester Polytechnic Institute has become instrumental in all phases of .i sendmail support and development, and was largely responsible for getting versions 8.8 and 8.9 out the door. .pp Many, many people contributed chunks of code and ideas to .i sendmail . It has proven to be a group network effort. Version 8 in particular was a group project. The following people and organizations made notable contributions: .(l Claus Assmann John Beck, Hewlett-Packard & Sun Microsystems Keith Bostic, CSRG, University of California, Berkeley Andrew Cheng, Sun Microsystems Michael J. Corrigan, University of California, San Diego Bryan Costales, International Computer Science Institute & InfoBeat Pa\*:r (Pell) Emanuelsson Craig Everhart, Transarc Corporation Per Hedeland, Ericsson Tom Ivar Helbekkmo, Norwegian School of Economics Kari Hurtta, Finnish Meteorological Institute Allan E. Johannesen, WPI Jonathan Kamens, OpenVision Technologies, Inc. Takahiro Kanbe, Fuji Xerox Information Systems Co., Ltd. Brian Kantor, University of California, San Diego John Kennedy, Cal State University, Chico Murray S. Kucherawy, HookUp Communication Corp. Bruce Lilly, Sony U.S. Karl London Motonori Nakamura, Ritsumeikan University & Kyoto University John Gardiner Myers, Carnegie Mellon University Neil Rickert, Northern Illinois University Gregory Neil Shapiro, WPI Eric Schnoebelen, Convex Computer Corp. Eric Wassenaar, National Institute for Nuclear and High Energy Physics, Amsterdam Randall Winchester, University of Maryland Christophe Wolfhugel, Pasteur Institute & Herve Schauer Consultants (Paris) Exactis.com, Inc. .)l I apologize for anyone I have omitted, misspelled, misattributed, or otherwise missed. At this point, I suspect that at least a hundred people have contributed code, and many more have contributed ideas, comments, and encouragement. I've tried to list them in the RELEASE_NOTES in the distribution directory. I appreciate their contribution as well. .pp Special thanks are reserved for Michael Corrigan and Christophe Wolfhugel, who besides being wonderful guinea pigs and contributors have also consented to be added to the ``sendmail@Sendmail.ORG'' list and, by answering the bulk of the questions sent to that list, have freed me up to do other work. .++ A .+c "COMMAND LINE FLAGS" .ba 0 .nr ii 1i .pp Arguments must be presented with flags before addresses. The flags are: .ip \-A\fIx\fP Select an alternative .cf file which is either .i sendmail.cf for .b \-Am or .i submit.cf for .b \-Ac . By default the .cf file is chosen based on the operation mode. For .b -bm (default), .b -bs , and .b -t it is .i submit.cf if it exists, for all others it is .i sendmail.cf . .ip \-b\fIx\fP Set operation mode to .i x . Operation modes are: .(b .ta 4n m Deliver mail (default) s Speak SMTP on input side a\(dg ``Arpanet'' mode (get envelope sender information from header) d Run as a daemon in background D Run as a daemon in foreground t Run in test mode v Just verify addresses, don't collect or deliver i Initialize the alias database p Print the mail queue P Print overview over the mail queue (requires shared memory) h Print the persistent host status database H Purge expired entries from the persistent host status database .)b .(f \(dgDeprecated. .)f .ip \-B\fItype\fP Indicate body type. .ip \-C\fIfile\fP Use a different configuration file. .i Sendmail runs as the invoking user (rather than root) when this flag is specified. .ip "\-D \fIlogfile\fP" Send debugging output to the indicated .i logfile instead of stdout. .ip \-d\fIlevel\fP Set debugging level. .ip "\-f\ \fIaddr\fP" The envelope sender address is set to .i addr . This address may also be used in the From: header if that header is missing during initial submission. The envelope sender address is used as the recipient for delivery status notifications and may also appear in a Return-Path: header. .ip \-F\ \fIname\fP Sets the full name of this user to .i name . .ip \-G When accepting messages via the command line, indicate that they are for relay (gateway) submission. sendmail may complain about syntactically invalid messages, e.g., unqualified host names, rather than fixing them when this flag is set. sendmail will not do any canonicalization in this mode. .ip "\-h\ \fIcnt\fP" Sets the .q "hop count" to .i cnt . This represents the number of times this message has been processed by .i sendmail (to the extent that it is supported by the underlying networks). .i Cnt is incremented during processing, and if it reaches MAXHOP (currently 25) .i sendmail throws away the message with an error. .ip "\-L \fItag\fP" Sets the identifier used for syslog. Note that this identifier is set as early as possible. However, .i sendmail may be used if problems arise before the command line arguments are processed. .ip \-n Don't do aliasing or forwarding. .ip "\-N \fInotifications\fP" Tag all addresses being sent as wanting the indicated .i notifications , which consists of the word .q NEVER or a comma-separated list of .q SUCCESS , .q FAILURE , and .q DELAY for successful delivery, failure, and a message that is stuck in a queue somewhere. The default is .q FAILURE,DELAY . .ip "\-r\ \fIaddr\fP" An obsolete form of .b \-f . .ip \-o\fIx\|value\fP Set option .i x to the specified .i value . These options are described in Section 5.6. .ip \-O\fIoption\fP\fB=\fP\fIvalue\fP Set .i option to the specified .i value (for long form option names). These options are described in Section 5.6. .ip \-M\fIx\|value\fP Set macro .i x to the specified .i value . .ip \-p\fIprotocol\fP Set the sending protocol. Programs are encouraged to set this. The protocol field can be in the form .i protocol \c .b : \c .i host to set both the sending protocol and sending host. For example, .q \-pUUCP:uunet sets the sending protocol to UUCP and the sending host to uunet. (Some existing programs use \-oM to set the r and s macros; this is equivalent to using \-p.) .ip \-q\fItime\fP Try to process the queued up mail. If the time is given, a .i sendmail will start one or more processes to run through the queue(s) at the specified time interval to deliver queued mail; otherwise, it only runs once. Each of these processes acts on a workgroup. These processes are also known as workgroup processes or WGP's for short. Each workgroup is responsible for controlling the processing of one or more queues; workgroups help manage the use of system resources by sendmail. Each workgroup may have one or more children concurrently processing queues depending on the setting of \fIMaxQueueChildren\fP. .ip \-qp\fItime\fP Similar to \-q with a time argument, except that instead of periodically starting WGP's sendmail starts persistent WGP's that alternate between processing queues and sleeping. The sleep time is specified by the time argument; it defaults to 1 second, except that a WGP always sleeps at least 5 seconds if their queues were empty in the previous run. Persistent processes are managed by a queue control process (QCP). The QCP is the parent process of the WGP's. Typically the QCP will be the sendmail daemon (when started with \-bd or \-bD) or a special process (named Queue control) (when started without \-bd or \-bD). If a persistent WGP ceases to be active for some reason another WGP will be started by the QCP for the same workgroup in most cases. When a persistent WGP has core dumped, the debug flag \fIno_persistent_restart\fP is set or the specific persistent WGP has been restarted too many times already then the WGP will not be started again and a message will be logged to this effect. To stop (SIGTERM) or restart (SIGHUP) persistent WGP's the appropriate signal should be sent to the QCP. The QCP will propagate the signal to all of the WGP's and if appropriate restart the persistent WGP's. .ip \-q\fIGname\fP Run the jobs in the queue group .i name once. .ip \-q[!]\fIXstring\fP Run the queue once, limiting the jobs to those matching .i Xstring . The key letter .i X can be .b I to limit based on queue identifier, .b R to limit based on recipient, .b S to limit based on sender, or .b Q to limit based on quarantine reason for quarantined jobs. A particular queued job is accepted if one of the corresponding attributes contains the indicated .i string . The optional ! character negates the condition tested. Multiple .i \-q\fIX\fP flags are permitted, with items with the same key letter .q or'ed together, and items with different key letters .q and'ed together. .ip "\-Q[reason]" Quarantine a normal queue items with the given reason or unquarantine quarantined queue items if no reason is given. This should only be used with some sort of item matching using .b \-q[!]\fIXstring\fP as described above. .ip "\-R ret" What information you want returned if the message bounces; .i ret can be .q HDRS for headers only or .q FULL for headers plus body. This is a request only; the other end is not required to honor the parameter. If .q HDRS is specified local bounces also return only the headers. .ip \-t Read the header for .q To: , .q Cc: , and .q Bcc: lines, and send to everyone listed in those lists. The .q Bcc: line will be deleted before sending. Any addresses in the argument vector will be deleted from the send list. .ip "\-V envid" The indicated .i envid is passed with the envelope of the message and returned if the message bounces. .ip "\-X \fIlogfile\fP" Log all traffic in and out of .i sendmail in the indicated .i logfile for debugging mailer problems. This produces a lot of data very quickly and should be used sparingly. .pp There are a number of options that may be specified as primitive flags. These are the e, i, m, and v options. Also, the f option may be specified as the .b \-s flag. The DSN related options .q "\-N" , .q "\-R" , and .q "\-V" have no effects on .i sendmail running as daemon. .+c "QUEUE FILE FORMATS" .pp This appendix describes the format of the queue files. These files live in a queue directory. The individual qf, hf, Qf, df, and xf files may be stored in separate .i qf/ , .i df/ , and .i xf/ subdirectories if they are present in the queue directory. .pp All queue files have the name .i ttYMDhmsNNppppp where .i YMDhmsNNppppp is the .i id for this message and the .i tt is a type. The individual letters in the .i id are: .nr ii 0.5i .ip Y Encoded year .ip M Encoded month .ip D Encoded day .ip h Encoded hour .ip m Encoded minute .ip s Encoded second .ip NN Encoded envelope number .ip ppppp At least five decimal digits of the process ID .pp All files with the same id collectively define one message. Due to the use of memory-buffered files, some of these files may never appear on disk. .pp The types are: .nr ii 0.5i .ip qf The queue control file. This file contains the information necessary to process the job. .ip hf The same as a queue control file, but for a quarantined queue job. .ip df The data file. The message body (excluding the header) is kept in this file. Sometimes the df file is not stored in the same directory as the qf file; in this case, the qf file contains a `d' record which names the queue directory that contains the df file. .ip tf A temporary file. This is an image of the .b qf file when it is being rebuilt. It should be renamed to a .b qf file very quickly. .ip xf A transcript file, existing during the life of a session showing everything that happens during that session. Sometimes the xf file must be generated before a queue group has been selected; in this case, the xf file will be stored in a directory of the default queue group. .ip Qf A ``lost'' queue control file. .i sendmail renames a .b qf file to .b Qf if there is a severe (configuration) problem that cannot be solved without human intervention. Search the logfile for the queue file id to figure out what happened. After you resolved the problem, you can rename the .b Qf file to .b qf and send it again. .pp The queue control file is structured as a series of lines each beginning with a code letter. The lines are as follows: .ip V The version number of the queue file format, used to allow new .i sendmail binaries to read queue files created by older versions. Defaults to version zero. Must be the first line of the file if present. For 8.12 the version number is 6. .ip A The information given by the AUTH= parameter of the .q "MAIL FROM:" command or $f@$j if sendmail has been called directly. .ip H A header definition. There may be any number of these lines. The order is important: they represent the order in the final message. These use the same syntax as header definitions in the configuration file. .ip C The controlling address. The syntax is .q localuser:aliasname . Recipient addresses following this line will be flagged so that deliveries will be run as the .i localuser (a user name from the /etc/passwd file); .i aliasname is the name of the alias that expanded to this address (used for printing messages). .ip q The quarantine reason for quarantined queue items. .ip Q The ``original recipient'', specified by the ORCPT= field in an ESMTP transaction. Used exclusively for Delivery Status Notifications. It applies only to the following `R' line. .ip r The ``final recipient'' used for Delivery Status Notifications. It applies only to the following `R' line. .ip R A recipient address. This will normally be completely aliased, but is actually realiased when the job is processed. There will be one line for each recipient. Version 1 qf files also include a leading colon-terminated list of flags, which can be `S' to return a message on successful final delivery, `F' to return a message on failure, `D' to return a message if the message is delayed, `B' to indicate that the body should be returned, `N' to suppress returning the body, and `P' to declare this as a ``primary'' (command line or SMTP-session) address. .ip S The sender address. There may only be one of these lines. .ip T The job creation time. This is used to compute when to time out the job. .ip P The current message priority. This is used to order the queue. Higher numbers mean lower priorities. The priority changes as the message sits in the queue. The initial priority depends on the message class and the size of the message. .ip M A message. This line is printed by the .i mailq command, and is generally used to store status information. It can contain any text. .ip F Flag bits, represented as one letter per flag. Defined flag bits are .b r indicating that this is a response message and .b w indicating that a warning message has been sent announcing that the mail has been delayed. Other flag bits are: .b 8 : the body contains 8bit data, .b b : a Bcc: header should be removed, .b d : the mail has RET parameters (see RFC 1894), .b n : the body of the message should not be returned in case of an error, .b s : the envelope has been split. .ip N The total number of delivery attempts. .ip K The time (as seconds since January 1, 1970) of the last delivery attempt. .ip d If the df file is in a different directory than the qf file, then a `d' record is present, specifying the directory in which the df file resides. .ip I The i-number of the data file; this can be used to recover your mail queue after a disastrous disk crash. .ip $ A macro definition. The values of certain macros are passed through to the queue run phase. .ip B The body type. The remainder of the line is a text string defining the body type. If this field is missing, the body type is assumed to be .q "undefined" and no special processing is attempted. Legal values are .q 7BIT and .q 8BITMIME . .ip Z The original envelope id (from the ESMTP transaction). For Deliver Status Notifications only. .pp As an example, the following is a queue file sent to .q eric@mammoth.Berkeley.EDU and .q bostic@okeeffe.CS.Berkeley.EDU \**: .(f \**This example is contrived and probably inaccurate for your environment. Glance over it to get an idea; nothing can replace looking at what your own system generates. .)f .(b V4 T711358135 K904446490 N0 P2100941 $_eric@localhost ${daemon_flags} Seric Ceric:100:1000:sendmail@vangogh.CS.Berkeley.EDU RPFD:eric@mammoth.Berkeley.EDU RPFD:bostic@okeeffe.CS.Berkeley.EDU H?P?Return-path: <^g> H??Received: by vangogh.CS.Berkeley.EDU (5.108/2.7) id AAA06703; Fri, 17 Jul 1992 00:28:55 -0700 H??Received: from mail.CS.Berkeley.EDU by vangogh.CS.Berkeley.EDU (5.108/2.7) id AAA06698; Fri, 17 Jul 1992 00:28:54 -0700 H??Received: from [128.32.31.21] by mail.CS.Berkeley.EDU (5.96/2.5) id AA22777; Fri, 17 Jul 1992 03:29:14 -0400 H??Received: by foo.bar.baz.de (5.57/Ultrix3.0-C) id AA22757; Fri, 17 Jul 1992 09:31:25 GMT H?F?From: eric@foo.bar.baz.de (Eric Allman) H?x?Full-name: Eric Allman H??Message-id: <9207170931.AA22757@foo.bar.baz.de> H??To: sendmail@vangogh.CS.Berkeley.EDU H??Subject: this is an example message .)b This shows the person who sent the message, the submission time (in seconds since January 1, 1970), the message priority, the message class, the recipients, and the headers for the message. .+c "SUMMARY OF SUPPORT FILES" .pp This is a summary of the support files that .i sendmail creates or generates. Many of these can be changed by editing the sendmail.cf file; check there to find the actual pathnames. .nr ii 1i .ip "/usr/\*(SD/sendmail" The binary of .i sendmail . .ip /usr/\*(SB/newaliases A link to /usr/\*(SD/sendmail; causes the alias database to be rebuilt. Running this program is completely equivalent to giving .i sendmail the .b \-bi flag. .ip /usr/\*(SB/mailq Prints a listing of the mail queue. This program is equivalent to using the .b \-bp flag to .i sendmail . .ip /etc/mail/sendmail.cf The configuration file, in textual form. .ip /etc/mail/helpfile The SMTP help file. .ip /etc/mail/statistics A statistics file; need not be present. .ip /etc/mail/sendmail.pid Created in daemon mode; it contains the process id of the current SMTP daemon. If you use this in scripts; use ``head \-1'' to get just the first line; the second line contains the command line used to invoke the daemon, and later versions of .i sendmail may add more information to subsequent lines. .ip /etc/mail/aliases The textual version of the alias file. .ip /etc/mail/aliases.db The alias file in .i hash \|(3) format. .ip /etc/mail/aliases.{pag,dir} The alias file in .i ndbm \|(3) format. .ip /var/spool/mqueue The directory in which the mail queue(s) and temporary files reside. .ip /var/spool/mqueue/qf* Control (queue) files for messages. .ip /var/spool/mqueue/df* Data files. .ip /var/spool/mqueue/tf* Temporary versions of the qf files, used during queue file rebuild. .ip /var/spool/mqueue/xf* A transcript of the current session. .if o \ \{\ . bp . rs . sp |4i . ce 2 This page intentionally left blank; replace it with a blank sheet for double-sided output. .\} .\".ro .\".ls 1 .\".tp .\".sp 2i .\".in 0 .\".ce 100 .\".sz 24 .\".b SENDMAIL .\".sz 14 .\".sp .\"INSTALLATION AND OPERATION GUIDE .\".sp .\".sz 10 .\"Eric Allman .\".sp -.\"Version $Revision: 8.749 $ +.\"Version $Revision: 8.751 $ .\".ce 0 .bp 3 .ce .sz 12 TABLE OF CONTENTS .sz 10 .sp .\" remove some things to avoid "out of temp file space" problem .rm sh .rm (x .rm )x .rm ip .rm pp .rm lp .rm he .rm fo .rm eh .rm oh .rm ef .rm of .xp .if o \ \{\ . bp . rs . sp |4i . ce 2 This page intentionally left blank; replace it with a blank sheet for double-sided output. .\} Index: head/contrib/sendmail/include/sm/config.h =================================================================== --- head/contrib/sendmail/include/sm/config.h (revision 249728) +++ head/contrib/sendmail/include/sm/config.h (revision 249729) @@ -1,187 +1,189 @@ /* * Copyright (c) 2000-2003 Sendmail, Inc. and its suppliers. * All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * - * $Id: config.h,v 1.47 2004/10/26 21:41:07 gshapiro Exp $ + * $Id: config.h,v 1.48 2013/03/22 22:48:57 gshapiro Exp $ */ /* ** libsm configuration macros. ** The values of these macros are platform dependent. ** The default values are given here. ** If the default is incorrect, then the correct value can be specified ** in the m4 configuration file in devtools/OS. */ #ifndef SM_CONFIG_H # define SM_CONFIG_H # include "sm_os.h" /* ** SM_CONF_STDBOOL_H is 1 if exists +** +** Note, unlike gcc, clang doesn't apply full prototypes to K&R definitions. */ # ifndef SM_CONF_STDBOOL_H -# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +# if !defined(__clang__) && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L # define SM_CONF_STDBOOL_H 1 -# else /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L */ +# else /* !defined(__clang__) && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L */ # define SM_CONF_STDBOOL_H 0 -# endif /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L */ +# endif /* !defined(__clang__) && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L */ # endif /* ! SM_CONF_STDBOOL_H */ /* ** Configuration macros that specify how __P is defined. */ # ifndef SM_CONF_SYS_CDEFS_H # define SM_CONF_SYS_CDEFS_H 0 # endif /* ! SM_CONF_SYS_CDEFS_H */ /* ** SM_CONF_STDDEF_H is 1 if exists */ # ifndef SM_CONF_STDDEF_H # define SM_CONF_STDDEF_H 1 # endif /* ! SM_CONF_STDDEF_H */ /* ** Configuration macro that specifies whether strlcpy/strlcat are available. ** Note: this is the default so that the libsm version (optimized) will ** be used by default (sm_strlcpy/sm_strlcat). */ # ifndef SM_CONF_STRL # define SM_CONF_STRL 0 # endif /* ! SM_CONF_STRL */ /* ** Configuration macro indicating that setitimer is available */ # ifndef SM_CONF_SETITIMER # define SM_CONF_SETITIMER 1 # endif /* ! SM_CONF_SETITIMER */ /* ** Does define uid_t and gid_t? */ # ifndef SM_CONF_UID_GID # define SM_CONF_UID_GID 1 # endif /* ! SM_CONF_UID_GID */ /* ** Does define ssize_t? */ # ifndef SM_CONF_SSIZE_T # define SM_CONF_SSIZE_T 1 # endif /* ! SM_CONF_SSIZE_T */ /* ** Does the C compiler support long long? */ # ifndef SM_CONF_LONGLONG # if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L # define SM_CONF_LONGLONG 1 # else /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L */ # if defined(__GNUC__) # define SM_CONF_LONGLONG 1 # else /* defined(__GNUC__) */ # define SM_CONF_LONGLONG 0 # endif /* defined(__GNUC__) */ # endif /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L */ # endif /* ! SM_CONF_LONGLONG */ /* ** Does define quad_t and u_quad_t? ** We only care if long long is not available. */ # ifndef SM_CONF_QUAD_T # define SM_CONF_QUAD_T 0 # endif /* ! SM_CONF_QUAD_T */ /* ** Configuration macro indicating that shared memory is available */ # ifndef SM_CONF_SHM # define SM_CONF_SHM 0 # endif /* ! SM_CONF_SHM */ /* ** Does define sigsetjmp? */ # ifndef SM_CONF_SIGSETJMP # define SM_CONF_SIGSETJMP 1 # endif /* ! SM_CONF_SIGSETJMP */ /* ** Does exist, and define the EX_* macros with values ** that differ from the default BSD values in ? */ # ifndef SM_CONF_SYSEXITS_H # define SM_CONF_SYSEXITS_H 0 # endif /* ! SM_CONF_SYSEXITS_H */ /* has memchr() prototype? (if not: needs memory.h) */ # ifndef SM_CONF_MEMCHR # define SM_CONF_MEMCHR 1 # endif /* ! SM_CONF_MEMCHR */ /* try LLONG tests in libsm/t-types.c? */ # ifndef SM_CONF_TEST_LLONG # define SM_CONF_TEST_LLONG 1 # endif /* !SM_CONF_TEST_LLONG */ /* LDAP Checks */ # if LDAPMAP # include # include /* Does the LDAP library have ldap_memfree()? */ # ifndef SM_CONF_LDAP_MEMFREE /* ** The new LDAP C API (draft-ietf-ldapext-ldap-c-api-04.txt) includes ** ldap_memfree() in the API. That draft states to use LDAP_API_VERSION ** of 2004 to identify the API. */ # if USING_NETSCAPE_LDAP || LDAP_API_VERSION >= 2004 # define SM_CONF_LDAP_MEMFREE 1 # else /* USING_NETSCAPE_LDAP || LDAP_API_VERSION >= 2004 */ # define SM_CONF_LDAP_MEMFREE 0 # endif /* USING_NETSCAPE_LDAP || LDAP_API_VERSION >= 2004 */ # endif /* ! SM_CONF_LDAP_MEMFREE */ /* Does the LDAP library have ldap_initialize()? */ # ifndef SM_CONF_LDAP_INITIALIZE /* ** Check for ldap_initialize() support for support for LDAP URI's with ** non-ldap:// schemes. */ /* OpenLDAP does it with LDAP_OPT_URI */ # ifdef LDAP_OPT_URI # define SM_CONF_LDAP_INITIALIZE 1 # endif /* LDAP_OPT_URI */ # endif /* !SM_CONF_LDAP_INITIALIZE */ # endif /* LDAPMAP */ /* don't use strcpy() */ # ifndef DO_NOT_USE_STRCPY # define DO_NOT_USE_STRCPY 1 # endif /* ! DO_NOT_USE_STRCPY */ #endif /* ! SM_CONFIG_H */ Index: head/contrib/sendmail/include/sm/io.h =================================================================== --- head/contrib/sendmail/include/sm/io.h (revision 249728) +++ head/contrib/sendmail/include/sm/io.h (revision 249729) @@ -1,389 +1,389 @@ /* - * Copyright (c) 2000-2002, 2004 Sendmail, Inc. and its suppliers. + * Copyright (c) 2000-2002, 2004, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1990 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * - * $Id: io.h,v 1.24 2004/03/03 19:14:49 ca Exp $ + * $Id: io.h,v 1.25 2013/03/12 15:24:49 ca Exp $ */ /*- * @(#)stdio.h 5.17 (Berkeley) 6/3/91 */ #ifndef SM_IO_H #define SM_IO_H #include #include #include /* mode for sm io (exposed) */ #define SM_IO_RDWR 1 /* read-write */ #define SM_IO_RDONLY 2 /* read-only */ #define SM_IO_WRONLY 3 /* write-only */ #define SM_IO_APPEND 4 /* write-only from eof */ #define SM_IO_APPENDRW 5 /* read-write from eof */ #define SM_IO_RDWRTR 6 /* read-write with truncation indicated */ # define SM_IO_BINARY 0x0 /* binary mode: not used in Unix */ #define SM_IS_BINARY(mode) (((mode) & SM_IO_BINARY) != 0) #define SM_IO_MODE(mode) ((mode) & 0x0f) #define SM_IO_RDWR_B (SM_IO_RDWR|SM_IO_BINARY) #define SM_IO_RDONLY_B (SM_IO_RDONLY|SM_IO_BINARY) #define SM_IO_WRONLY_B (SM_IO_WRONLY|SM_IO_BINARY) #define SM_IO_APPEND_B (SM_IO_APPEND|SM_IO_BINARY) #define SM_IO_APPENDRW_B (SM_IO_APPENDRW|SM_IO_BINARY) #define SM_IO_RDWRTR_B (SM_IO_RDWRTR|SM_IO_BINARY) /* for sm_io_fseek, et al api's (exposed) */ #define SM_IO_SEEK_SET 0 #define SM_IO_SEEK_CUR 1 #define SM_IO_SEEK_END 2 /* flags for info what's with different types (exposed) */ #define SM_IO_WHAT_MODE 1 #define SM_IO_WHAT_VECTORS 2 #define SM_IO_WHAT_FD 3 #define SM_IO_WHAT_TYPE 4 #define SM_IO_WHAT_ISTYPE 5 #define SM_IO_IS_READABLE 6 #define SM_IO_WHAT_TIMEOUT 7 #define SM_IO_WHAT_SIZE 8 /* info flags (exposed) */ #define SM_IO_FTYPE_CREATE 1 #define SM_IO_FTYPE_MODIFY 2 #define SM_IO_FTYPE_DELETE 3 #define SM_IO_SL_PRIO 1 #define SM_IO_OPEN_MAX 20 /* for internal buffers */ struct smbuf { unsigned char *smb_base; int smb_size; }; /* ** sm I/O state variables (internal only). ** ** The following always hold: ** ** if (flags&(SMLBF|SMWR)) == (SMLBF|SMWR), ** lbfsize is -bf.size, else lbfsize is 0 ** if flags&SMRD, w is 0 ** if flags&SMWR, r is 0 ** ** This ensures that the getc and putc macros (or inline functions) never ** try to write or read from a file that is in `read' or `write' mode. ** (Moreover, they can, and do, automatically switch from read mode to ** write mode, and back, on "r+" and "w+" files.) ** ** lbfsize is used only to make the inline line-buffered output stream ** code as compact as possible. ** ** ub, up, and ur are used when ungetc() pushes back more characters ** than fit in the current bf, or when ungetc() pushes back a character ** that does not match the previous one in bf. When this happens, ** ub.base becomes non-nil (i.e., a stream has ungetc() data iff ** ub.base!=NULL) and up and ur save the current values of p and r. */ typedef struct sm_file SM_FILE_T; struct sm_file { const char *sm_magic; /* This SM_FILE_T is free when NULL */ unsigned char *f_p; /* current position in (some) buffer */ int f_r; /* read space left for getc() */ int f_w; /* write space left for putc() */ long f_flags; /* flags, below */ short f_file; /* fileno, if Unix fd, else -1 */ struct smbuf f_bf; /* the buffer (>= 1 byte, if !NULL) */ int f_lbfsize; /* 0 or -bf.size, for inline putc */ /* These can be used for any purpose by a file type implementation: */ void *f_cookie; int f_ival; /* operations */ int (*f_close) __P((SM_FILE_T *)); ssize_t (*f_read) __P((SM_FILE_T *, char *, size_t)); off_t (*f_seek) __P((SM_FILE_T *, off_t, int)); ssize_t (*f_write) __P((SM_FILE_T *, const char *, size_t)); int (*f_open) __P((SM_FILE_T *, const void *, int, const void *)); int (*f_setinfo) __P((SM_FILE_T *, int , void *)); int (*f_getinfo) __P((SM_FILE_T *, int , void *)); int f_timeout; int f_timeoutstate; /* either blocking or non-blocking */ char *f_type; /* for by-type lookups */ struct sm_file *f_flushfp; /* flush this before reading parent */ struct sm_file *f_modefp; /* sync mode with this fp */ /* separate buffer for long sequences of ungetc() */ struct smbuf f_ub; /* ungetc buffer */ unsigned char *f_up; /* saved f_p when f_p is doing ungetc */ int f_ur; /* saved f_r when f_r is counting ungetc */ /* tricks to meet minimum requirements even when malloc() fails */ unsigned char f_ubuf[3]; /* guarantee an ungetc() buffer */ unsigned char f_nbuf[1]; /* guarantee a getc() buffer */ /* Unix stdio files get aligned to block boundaries on fseek() */ int f_blksize; /* stat.st_blksize (may be != bf.size) */ off_t f_lseekoff; /* current lseek offset */ int f_dup_cnt; /* count file dup'd */ }; __BEGIN_DECLS extern SM_FILE_T SmIoF[]; extern const char SmFileMagic[]; extern SM_FILE_T SmFtStdio_def; extern SM_FILE_T SmFtStdiofd_def; extern SM_FILE_T SmFtString_def; extern SM_FILE_T SmFtSyslog_def; extern SM_FILE_T SmFtRealStdio_def; #define SMIOIN_FILENO 0 #define SMIOOUT_FILENO 1 #define SMIOERR_FILENO 2 #define SMIOSTDIN_FILENO 3 #define SMIOSTDOUT_FILENO 4 #define SMIOSTDERR_FILENO 5 /* Common predefined and already (usually) open files (exposed) */ #define smioin (&SmIoF[SMIOIN_FILENO]) #define smioout (&SmIoF[SMIOOUT_FILENO]) #define smioerr (&SmIoF[SMIOERR_FILENO]) #define smiostdin (&SmIoF[SMIOSTDIN_FILENO]) #define smiostdout (&SmIoF[SMIOSTDOUT_FILENO]) #define smiostderr (&SmIoF[SMIOSTDERR_FILENO]) #define SmFtStdio (&SmFtStdio_def) #define SmFtStdiofd (&SmFtStdiofd_def) #define SmFtString (&SmFtString_def) #define SmFtSyslog (&SmFtSyslog_def) #define SmFtRealStdio (&SmFtRealStdio_def) #ifdef __STDC__ # define SM_IO_SET_TYPE(f, name, open, close, read, write, seek, get, set, timeout) \ (f) = {SmFileMagic, (unsigned char *) 0, 0, 0, 0L, -1, {0}, 0, (void *) 0,\ 0, (close), (read), (seek), (write), (open), (set), (get), (timeout),\ 0, (name)} # define SM_IO_INIT_TYPE(f, name, open, close, read, write, seek, get, set, timeout) #else /* __STDC__ */ # define SM_IO_SET_TYPE(f, name, open, close, read, write, seek, get, set, timeout) (f) # define SM_IO_INIT_TYPE(f, name, open, close, read, write, seek, get, set, timeout) \ (f).sm_magic = SmFileMagic; \ (f).f_p = (unsigned char *) 0; \ (f).f_r = 0; \ (f).f_w = 0; \ (f).f_flags = 0L; \ (f).f_file = 0; \ (f).f_bf.smb_base = (unsigned char *) 0; \ (f).f_bf.smb_size = 0; \ (f).f_lbfsize = 0; \ (f).f_cookie = (void *) 0; \ (f).f_ival = 0; \ (f).f_close = (close); \ (f).f_read = (read); \ (f).f_seek = (seek); \ (f).f_write = (write); \ (f).f_open = (open); \ (f).f_setinfo = (set); \ (f).f_getinfo = (get); \ (f).f_timeout = (timeout); \ (f).f_timeoutstate = 0; \ (f).f_type = (name); #endif /* __STDC__ */ __END_DECLS /* Internal flags */ #define SMFBF 0x000001 /* XXXX fully buffered */ #define SMLBF 0x000002 /* line buffered */ #define SMNBF 0x000004 /* unbuffered */ #define SMNOW 0x000008 /* Flush each write; take read now */ #define SMRD 0x000010 /* OK to read */ #define SMWR 0x000020 /* OK to write */ /* RD and WR are never simultaneously asserted */ #define SMRW 0x000040 /* open for reading & writing */ #define SMFEOF 0x000080 /* found EOF */ #define SMERR 0x000100 /* found error */ #define SMMBF 0x000200 /* buf is from malloc */ #define SMAPP 0x000400 /* fdopen()ed in append mode */ #define SMSTR 0x000800 /* this is an snprintf string */ #define SMOPT 0x001000 /* do fseek() optimisation */ #define SMNPT 0x002000 /* do not do fseek() optimisation */ #define SMOFF 0x004000 /* set iff offset is in fact correct */ #define SMALC 0x010000 /* allocate string space dynamically */ #define SMMODEMASK 0x0070 /* read/write mode */ /* defines for timeout constants */ #define SM_TIME_IMMEDIATE (0) #define SM_TIME_FOREVER (-1) #define SM_TIME_DEFAULT (-2) /* timeout state for blocking */ #define SM_TIME_BLOCK (0) /* XXX just bool? */ #define SM_TIME_NONBLOCK (1) /* Exposed buffering type flags */ #define SM_IO_FBF 0 /* setvbuf should set fully buffered */ #define SM_IO_LBF 1 /* setvbuf should set line buffered */ #define SM_IO_NBF 2 /* setvbuf should set unbuffered */ /* setvbuf buffered, but through at lower file type layers */ #define SM_IO_NOW 3 /* ** size of buffer used by setbuf. ** If underlying filesystem blocksize is discoverable that is used instead */ #define SM_IO_BUFSIZ 4096 #define SM_IO_EOF (-1) /* Functions defined in ANSI C standard. */ __BEGIN_DECLS SM_FILE_T *sm_io_autoflush __P((SM_FILE_T *, SM_FILE_T *)); void sm_io_automode __P((SM_FILE_T *, SM_FILE_T *)); void sm_io_clearerr __P((SM_FILE_T *)); int sm_io_close __P((SM_FILE_T *, int SM_NONVOLATILE)); SM_FILE_T *sm_io_dup __P((SM_FILE_T *)); int sm_io_eof __P((SM_FILE_T *)); int sm_io_error __P((SM_FILE_T *)); -char *sm_io_fgets __P((SM_FILE_T *, int, char *, int)); +int sm_io_fgets __P((SM_FILE_T *, int, char *, int)); int sm_io_flush __P((SM_FILE_T *, int SM_NONVOLATILE)); int PRINTFLIKE(3, 4) sm_io_fprintf __P((SM_FILE_T *, int, const char *, ...)); int sm_io_fputs __P((SM_FILE_T *, int, const char *)); int SCANFLIKE(3, 4) sm_io_fscanf __P((SM_FILE_T *, int, const char *, ...)); int sm_io_getc __P((SM_FILE_T *, int)); int sm_io_getinfo __P((SM_FILE_T *, int, void *)); SM_FILE_T *sm_io_open __P((const SM_FILE_T *, int SM_NONVOLATILE, const void *, int, const void *)); int sm_io_purge __P((SM_FILE_T *)); int sm_io_putc __P((SM_FILE_T *, int, int)); size_t sm_io_read __P((SM_FILE_T *, int, void *, size_t)); SM_FILE_T *sm_io_reopen __P((const SM_FILE_T *, int SM_NONVOLATILE, const void *, int, const void *, SM_FILE_T *)); void sm_io_rewind __P((SM_FILE_T *, int)); int sm_io_seek __P((SM_FILE_T *, int SM_NONVOLATILE, long SM_NONVOLATILE, int SM_NONVOLATILE)); int sm_io_setinfo __P((SM_FILE_T *, int, void *)); int sm_io_setvbuf __P((SM_FILE_T *, int, char *, int, size_t)); int SCANFLIKE(2, 3) sm_io_sscanf __P((const char *, char const *, ...)); long sm_io_tell __P((SM_FILE_T *, int SM_NONVOLATILE)); int sm_io_ungetc __P((SM_FILE_T *, int, int)); int sm_io_vfprintf __P((SM_FILE_T *, int, const char *, va_list)); size_t sm_io_write __P((SM_FILE_T *, int, const void *, size_t)); void sm_strio_init __P((SM_FILE_T *, char *, size_t)); extern SM_FILE_T * sm_io_fopen __P(( char *_pathname, int _flags, ...)); extern SM_FILE_T * sm_io_stdioopen __P(( FILE *_stream, char *_mode)); extern int sm_vasprintf __P(( char **_str, const char *_fmt, va_list _ap)); extern int sm_vsnprintf __P(( char *, size_t, const char *, va_list)); extern void sm_perror __P(( const char *)); __END_DECLS /* ** Functions internal to the implementation. */ __BEGIN_DECLS int sm_rget __P((SM_FILE_T *, int)); int sm_vfscanf __P((SM_FILE_T *, int SM_NONVOLATILE, const char *, va_list SM_NONVOLATILE)); int sm_wbuf __P((SM_FILE_T *, int, int)); __END_DECLS /* ** The macros are here so that we can ** define function versions in the library. */ #define sm_getc(f, t) \ (--(f)->f_r < 0 ? \ sm_rget(f, t) : \ (int)(*(f)->f_p++)) /* ** This has been tuned to generate reasonable code on the vax using pcc. ** (It also generates reasonable x86 code using gcc.) */ #define sm_putc(f, t, c) \ (--(f)->f_w < 0 ? \ (f)->f_w >= (f)->f_lbfsize ? \ (*(f)->f_p = (c)), *(f)->f_p != '\n' ? \ (int)*(f)->f_p++ : \ sm_wbuf(f, t, '\n') : \ sm_wbuf(f, t, (int)(c)) : \ (*(f)->f_p = (c), (int)*(f)->f_p++)) #define sm_eof(p) (((p)->f_flags & SMFEOF) != 0) #define sm_error(p) (((p)->f_flags & SMERR) != 0) #define sm_clearerr(p) ((void)((p)->f_flags &= ~(SMERR|SMFEOF))) #define sm_io_eof(p) sm_eof(p) #define sm_io_error(p) sm_error(p) #define sm_io_clearerr(p) sm_clearerr(p) #ifndef lint # ifndef _POSIX_SOURCE # define sm_io_getc(fp, t) sm_getc(fp, t) # define sm_io_putc(fp, t, x) sm_putc(fp, t, x) # endif /* _POSIX_SOURCE */ #endif /* lint */ #endif /* SM_IO_H */ Index: head/contrib/sendmail/libmilter/Makefile.m4 =================================================================== --- head/contrib/sendmail/libmilter/Makefile.m4 (revision 249728) +++ head/contrib/sendmail/libmilter/Makefile.m4 (revision 249729) @@ -1,40 +1,40 @@ -dnl $Id: Makefile.m4,v 8.88 2012/09/25 17:40:32 ca Exp $ +dnl $Id: Makefile.m4,v 8.92 2013/04/16 20:19:54 ca Exp $ include(confBUILDTOOLSDIR`/M4/switch.m4') dnl only required for compilation of EXTRAS define(`confREQUIRE_SM_OS_H', `true') define(`confMT', `true') # sendmail dir SMSRCDIR=ifdef(`confSMSRCDIR', `confSMSRCDIR', `${SRCDIR}/sendmail') PREPENDDEF(`confINCDIRS', `-I${SMSRCDIR} ') bldPRODUCT_START(`library', `libmilter') define(`bldINSTALLABLE', `true') define(`LIBMILTER_EXTRAS', `errstring.c strl.c') APPENDDEF(`confENVDEF', `-DNOT_SENDMAIL -Dsm_snprintf=snprintf') define(`bldSOURCES', `main.c engine.c listener.c worker.c handler.c comm.c smfi.c signal.c sm_gethost.c monitor.c LIBMILTER_EXTRAS ') define(`confBEFORE', `LIBMILTER_EXTRAS') bldPUSH_INSTALL_TARGET(`install-mfapi') bldPRODUCT_END PUSHDIVERT(3) errstring.c: ${LN} ${LNOPTS} ${SRCDIR}/libsm/errstring.c . strl.c: ${LN} ${LNOPTS} ${SRCDIR}/libsm/strl.c . POPDIVERT divert(bldTARGETS_SECTION) # Install the API header files MFAPI= ${SRCDIR}/inc`'lude/libmilter/mfapi.h MFDEF= ${SRCDIR}/inc`'lude/libmilter/mfdef.h install-mfapi: ${MFAPI} if [ ! -d ${DESTDIR}${INCLUDEDIR}/libmilter ]; then mkdir -p ${DESTDIR}${INCLUDEDIR}/libmilter; else :; fi ${INSTALL} -c -o ${INCOWN} -g ${INCGRP} -m ${INCMODE} ${MFAPI} ${DESTDIR}${INCLUDEDIR}/libmilter/mfapi.h ${INSTALL} -c -o ${INCOWN} -g ${INCGRP} -m ${INCMODE} ${MFDEF} ${DESTDIR}${INCLUDEDIR}/libmilter/mfdef.h divert(0) bldFINISH Index: head/contrib/sendmail/libmilter/sm_gethost.c =================================================================== --- head/contrib/sendmail/libmilter/sm_gethost.c (revision 249728) +++ head/contrib/sendmail/libmilter/sm_gethost.c (revision 249729) @@ -1,150 +1,155 @@ /* - * Copyright (c) 1999-2001, 2004, 2010 Sendmail, Inc. and its suppliers. + * Copyright (c) 1999-2001, 2004, 2010, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: sm_gethost.c,v 8.29 2010/07/27 01:09:31 ca Exp $") +SM_RCSID("@(#)$Id: sm_gethost.c,v 8.30 2013/02/22 22:43:33 gshapiro Exp $") #include #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ #include "libmilter.h" /* ** MI_GETHOSTBY{NAME,ADDR} -- compatibility routines for gethostbyXXX ** ** Some operating systems have wierd problems with the gethostbyXXX ** routines. For example, Solaris versions at least through 2.3 ** don't properly deliver a canonical h_name field. This tries to ** work around these problems. ** ** Support IPv6 as well as IPv4. */ #if NETINET6 && NEEDSGETIPNODE static struct hostent *sm_getipnodebyname __P((const char *, int, int, int *)); # ifndef AI_ADDRCONFIG # define AI_ADDRCONFIG 0 /* dummy */ # endif /* ! AI_ADDRCONFIG */ # ifndef AI_ALL # define AI_ALL 0 /* dummy */ # endif /* ! AI_ALL */ # ifndef AI_DEFAULT # define AI_DEFAULT 0 /* dummy */ # endif /* ! AI_DEFAULT */ static struct hostent * sm_getipnodebyname(name, family, flags, err) const char *name; int family; int flags; int *err; { bool resv6 = true; struct hostent *h; if (family == AF_INET6) { /* From RFC2133, section 6.1 */ resv6 = bitset(RES_USE_INET6, _res.options); _res.options |= RES_USE_INET6; } SM_SET_H_ERRNO(0); h = gethostbyname(name); if (family == AF_INET6 && !resv6) _res.options &= ~RES_USE_INET6; *err = h_errno; return h; } void freehostent(h) struct hostent *h; { /* ** Stub routine -- if they don't have getipnodeby*(), ** they probably don't have the free routine either. */ return; } #else /* NEEDSGETIPNODE && NETINET6 */ #define sm_getipnodebyname getipnodebyname #endif /* NEEDSGETIPNODE && NETINET6 */ struct hostent * mi_gethostbyname(name, family) char *name; int family; { struct hostent *h = NULL; #if (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) # if SOLARIS == 20300 || SOLARIS == 203 static struct hostent hp; static char buf[1000]; extern struct hostent *_switch_gethostbyname_r(); h = _switch_gethostbyname_r(name, &hp, buf, sizeof(buf), &h_errno); # else /* SOLARIS == 20300 || SOLARIS == 203 */ extern struct hostent *__switch_gethostbyname(); h = __switch_gethostbyname(name); # endif /* SOLARIS == 20300 || SOLARIS == 203 */ #else /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) */ # if NETINET6 - int flags = AI_DEFAULT|AI_ALL; +# ifndef SM_IPNODEBYNAME_FLAGS + /* For IPv4-mapped addresses, use: AI_DEFAULT|AI_ALL */ +# define SM_IPNODEBYNAME_FLAGS AI_ADDRCONFIG +# endif /* SM_IPNODEBYNAME_FLAGS */ + + int flags = SM_IPNODEBYNAME_FLAGS; int err; # endif /* NETINET6 */ # if NETINET6 # if ADDRCONFIG_IS_BROKEN flags &= ~AI_ADDRCONFIG; # endif /* ADDRCONFIG_IS_BROKEN */ h = sm_getipnodebyname(name, family, flags, &err); SM_SET_H_ERRNO(err); # else /* NETINET6 */ h = gethostbyname(name); # endif /* NETINET6 */ #endif /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) */ return h; } #if NETINET6 /* ** MI_INET_PTON -- convert printed form to network address. ** ** Wrapper for inet_pton() which handles IPv6: labels. ** ** Parameters: ** family -- address family ** src -- string ** dst -- destination address structure ** ** Returns: ** 1 if the address was valid ** 0 if the address wasn't parseable ** -1 if error */ int mi_inet_pton(family, src, dst) int family; const char *src; void *dst; { if (family == AF_INET6 && strncasecmp(src, "IPv6:", 5) == 0) src += 5; return inet_pton(family, src, dst); } #endif /* NETINET6 */ Index: head/contrib/sendmail/libsm/Makefile.m4 =================================================================== --- head/contrib/sendmail/libsm/Makefile.m4 (revision 249728) +++ head/contrib/sendmail/libsm/Makefile.m4 (revision 249729) @@ -1,44 +1,45 @@ -dnl $Id: Makefile.m4,v 1.72 2006/08/16 21:06:31 ca Exp $ +dnl $Id: Makefile.m4,v 1.73 2013/03/12 15:24:50 ca Exp $ define(`confREQUIRE_LIBUNIX') include(confBUILDTOOLSDIR`/M4/switch.m4') define(`confREQUIRE_LIBSM', `true') define(`confREQUIRE_SM_OS_H', `true') PREPENDDEF(`confENVDEF', `confMAPDEF') bldPRODUCT_START(`library', `libsm') define(`bldSOURCES', ` assert.c debug.c errstring.c exc.c heap.c match.c rpool.c strdup.c strerror.c strl.c clrerr.c fclose.c feof.c ferror.c fflush.c fget.c fpos.c findfp.c flags.c fopen.c fprintf.c fpurge.c fput.c fread.c fscanf.c fseek.c fvwrite.c fwalk.c fwrite.c get.c makebuf.c put.c refill.c rewind.c setvbuf.c smstdio.c snprintf.c sscanf.c stdio.c strio.c ungetc.c vasprintf.c vfprintf.c vfscanf.c vprintf.c vsnprintf.c wbuf.c wsetup.c string.c stringf.c xtrap.c strto.c test.c path.c strcasecmp.c strrevcmp.c signal.c clock.c config.c shm.c sem.c mbdb.c strexit.c cf.c ldap.c niprop.c mpeix.c memstat.c util.c ') bldPRODUCT_END dnl msg.c dnl syslogio.c define(`confCHECK_LIBS',`libsm.a')dnl include(confBUILDTOOLSDIR`/M4/'bldM4_TYPE_DIR`/check.m4') smcheck(`t-event', `compile-run') smcheck(`t-exc', `compile-run') smcheck(`t-rpool', `compile-run') smcheck(`t-string', `compile-run') smcheck(`t-smstdio', `compile-run') +smcheck(`t-fget', `compile-run') smcheck(`t-match', `compile-run') smcheck(`t-strio', `compile-run') smcheck(`t-heap', `compile-run') smcheck(`t-fopen', `compile-run') smcheck(`t-strl', `compile-run') smcheck(`t-strrevcmp', `compile-run') smcheck(`t-types', `compile-run') smcheck(`t-path', `compile-run') smcheck(`t-float', `compile-run') smcheck(`t-scanf', `compile-run') smcheck(`t-shm', `compile-run') smcheck(`t-sem', `compile-run') dnl smcheck(`t-msg', `compile-run') smcheck(`t-cf') smcheck(`b-strcmp') dnl SM_CONF_STRL cannot be turned off dnl smcheck(`b-strl') smcheck(`t-memstat') smcheck(`t-qic', `compile-run') divert(bldTARGETS_SECTION) divert(0) bldFINISH Index: head/contrib/sendmail/libsm/cf.c =================================================================== --- head/contrib/sendmail/libsm/cf.c (revision 249728) +++ head/contrib/sendmail/libsm/cf.c (revision 249729) @@ -1,100 +1,100 @@ /* * Copyright (c) 2001 Sendmail, Inc. and its suppliers. * All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: cf.c,v 1.6 2001/09/11 04:04:47 gshapiro Exp $") +SM_RCSID("@(#)$Id: cf.c,v 1.7 2013/03/12 15:24:50 ca Exp $") #include #include #include #include #include #include /* ** SM_CF_GETOPT -- look up option values in the sendmail.cf file ** ** Open the sendmail.cf file and parse all of the 'O' directives. ** Each time one of the options named in the option vector optv ** is found, store a malloced copy of the option value in optv. ** ** Parameters: ** path -- pathname of sendmail.cf file ** optc -- size of option vector ** optv -- pointer to option vector ** ** Results: ** 0 on success, or an errno value on failure. ** An exception is raised on malloc failure. */ int sm_cf_getopt(path, optc, optv) char *path; int optc; SM_CF_OPT_T *optv; { SM_FILE_T *cfp; char buf[2048]; char *p; char *id; char *idend; char *val; int i; cfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, path, SM_IO_RDONLY, NULL); if (cfp == NULL) return errno; - while (sm_io_fgets(cfp, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(cfp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { p = strchr(buf, '\n'); if (p != NULL) *p = '\0'; if (buf[0] != 'O' || buf[1] != ' ') continue; id = &buf[2]; val = strchr(id, '='); if (val == NULL) val = idend = id + strlen(id); else { idend = val; ++val; while (*val == ' ') ++val; while (idend > id && idend[-1] == ' ') --idend; *idend = '\0'; } for (i = 0; i < optc; ++i) { if (sm_strcasecmp(optv[i].opt_name, id) == 0) { optv[i].opt_val = sm_strdup_x(val); break; } } } if (sm_io_error(cfp)) { int save_errno = errno; (void) sm_io_close(cfp, SM_TIME_DEFAULT); errno = save_errno; return errno; } (void) sm_io_close(cfp, SM_TIME_DEFAULT); return 0; } Index: head/contrib/sendmail/libsm/fget.c =================================================================== --- head/contrib/sendmail/libsm/fget.c (revision 249728) +++ head/contrib/sendmail/libsm/fget.c (revision 249729) @@ -1,110 +1,113 @@ /* - * Copyright (c) 2000-2001 Sendmail, Inc. and its suppliers. + * Copyright (c) 2000-2001, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. */ #include -SM_RCSID("@(#)$Id: fget.c,v 1.24 2001/09/11 04:04:48 gshapiro Exp $") +SM_RCSID("@(#)$Id: fget.c,v 1.25 2013/03/12 15:24:50 ca Exp $") #include #include #include #include #include "local.h" /* ** SM_IO_FGETS -- get a string from a file ** ** Read at most n-1 characters from the given file. ** Stop when a newline has been read, or the count ('n') runs out. ** ** Parameters: ** fp -- the file to read from ** timeout -- time to complete reading the string in milliseconds ** buf -- buffer to place read string in ** n -- size of 'buf' ** ** Returns: -** success: returns value of 'buf' -** failure: NULL (no characters were read) -** timeout: NULL and errno set to EAGAIN +** success: number of characters +** failure: -1 +** timeout: -1 and errno set to EAGAIN ** ** Side Effects: ** may move the file pointer */ -char * +int sm_io_fgets(fp, timeout, buf, n) register SM_FILE_T *fp; int timeout; char *buf; register int n; { - register int len; - register char *s; - register unsigned char *p, *t; + int len, r; + char *s; + unsigned char *p, *t; SM_REQUIRE_ISA(fp, SmFileMagic); if (n <= 0) /* sanity check */ - return NULL; + return -1; s = buf; n--; /* leave space for NUL */ + r = 0; while (n > 0) { /* If the buffer is empty, refill it. */ if ((len = fp->f_r) <= 0) { /* ** Timeout is only passed if we can't get the data ** from the buffer (which is counted as immediately). */ if (sm_refill(fp, timeout) != 0) { /* EOF/error: stop with partial or no line */ if (s == buf) - return NULL; + return -1; break; } len = fp->f_r; } p = fp->f_p; /* ** Scan through at most n bytes of the current buffer, ** looking for '\n'. If found, copy up to and including ** newline, and stop. Otherwise, copy entire chunk ** and loop. */ if (len > n) len = n; t = (unsigned char *) memchr((void *) p, '\n', len); if (t != NULL) { len = ++t - p; + r += len; fp->f_r -= len; fp->f_p = t; (void) memcpy((void *) s, (void *) p, len); s[len] = 0; - return buf; + return r; } fp->f_r -= len; fp->f_p += len; (void) memcpy((void *) s, (void *) p, len); s += len; + r += len; n -= len; } *s = 0; - return buf; + return r; } Index: head/contrib/sendmail/libsm/t-fget.c =================================================================== --- head/contrib/sendmail/libsm/t-fget.c (nonexistent) +++ head/contrib/sendmail/libsm/t-fget.c (revision 249729) @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2013 Sendmail, Inc. and its suppliers. + * All rights reserved. + * + * By using this file, you agree to the terms and conditions set + * forth in the LICENSE file which can be found at the top level of + * the sendmail distribution. + */ + +#include +SM_IDSTR(id, "@(#)$Id: t-fget.c,v 1.1 2013/03/12 15:24:50 ca Exp $") + +#include +#include +#include +#include + +void +check(char *msg, int l) +{ + SM_FILE_T *wfp, *rfp; + char buf[256]; + size_t n; + int r, i; + static char fn[] = "tfget"; + + wfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, fn, + SM_IO_WRONLY_B, NULL); + SM_TEST(wfp != NULL); + for (i = 0; i < l; i++) + { + r = sm_io_putc(wfp, SM_TIME_DEFAULT, msg[i]); + SM_TEST(r >= 0); + } + r = sm_io_close(wfp, SM_TIME_DEFAULT); + SM_TEST(r == 0); + + rfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, fn, + SM_IO_RDONLY_B, NULL); + SM_TEST(rfp != NULL); + n = sizeof(buf); + r = sm_io_fgets(rfp, SM_TIME_DEFAULT, buf, n); + if (l == 0) + { + SM_TEST(r == -1); + SM_TEST(errno == 0); + } + else + { + SM_TEST(r == l); + if (r != l) + fprintf(stderr, "buf='%s', in='%s', r=%d, l=%d\n", + buf, msg, r, l); + } + SM_TEST(memcmp(buf, msg, l) == 0); + r = sm_io_close(rfp, SM_TIME_DEFAULT); + SM_TEST(r == 0); +} + + +int +main(argc, argv) + int argc; + char **argv; +{ + char res[256]; + int l; + + sm_test_begin(argc, argv, "test fget"); + + check("", strlen("")); + check("\n", strlen("\n")); + check("test\n", strlen("test\n")); + + l = snprintf(res, sizeof(res), "%c%s\n", '\0', "test ing"); + check(res, l); + + l = snprintf(res, sizeof(res), "%c%s%c\n", '\0', "test ing", '\0'); + check(res, l); + + l = snprintf(res, sizeof(res), "%c%s%c%s\n", + '\0', "test ing", '\0', "eol"); + check(res, l); + + return sm_test_end(); +} Property changes on: head/contrib/sendmail/libsm/t-fget.c ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Index: head/contrib/sendmail/mailstats/mailstats.c =================================================================== --- head/contrib/sendmail/mailstats/mailstats.c (revision 249728) +++ head/contrib/sendmail/mailstats/mailstats.c (revision 249729) @@ -1,368 +1,372 @@ /* - * Copyright (c) 1998-2002 Sendmail, Inc. and its suppliers. + * Copyright (c) 1998-2002, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * * */ #include SM_IDSTR(copyright, "@(#) Copyright (c) 1998-2002 Sendmail, Inc. and its suppliers.\n\ All rights reserved.\n\ Copyright (c) 1988, 1993\n\ The Regents of the University of California. All rights reserved.\n") -SM_IDSTR(id, "@(#)$Id: mailstats.c,v 8.100 2002/06/27 23:24:06 gshapiro Exp $") +SM_IDSTR(id, "@(#)$Id: mailstats.c,v 8.102 2013/03/12 15:24:50 ca Exp $") #include #include #include #include #include #include #ifdef EX_OK # undef EX_OK /* unistd.h may have another use for this */ #endif /* EX_OK */ #include #include #include #include #include #include #define MNAMELEN 20 /* max length of mailer name */ int main(argc, argv) int argc; char **argv; { register int i; int mno; int save_errno; int ch, fd; char *sfile; char *cfile; SM_FILE_T *cfp; bool mnames; bool progmode; bool trunc; long frmsgs = 0, frbytes = 0, tomsgs = 0, tobytes = 0, rejmsgs = 0; long dismsgs = 0; long quarmsgs = 0; time_t now; char mtable[MAXMAILERS][MNAMELEN + 1]; char sfilebuf[MAXPATHLEN]; char buf[MAXLINE]; struct statistics stats; extern char *ctime(); extern char *optarg; extern int optind; +# define MSOPTS "cC:f:opP" cfile = getcfname(0, 0, SM_GET_SENDMAIL_CF, NULL); sfile = NULL; mnames = true; progmode = false; trunc = false; - while ((ch = getopt(argc, argv, "cC:f:opP")) != -1) + while ((ch = getopt(argc, argv, MSOPTS)) != -1) { switch (ch) { case 'c': cfile = getcfname(0, 0, SM_GET_SUBMIT_CF, NULL); break; case 'C': cfile = optarg; break; case 'f': sfile = optarg; break; + case 'o': mnames = false; break; case 'p': trunc = true; /* FALLTHROUGH */ case 'P': progmode = true; break; + case '?': default: usage: (void) sm_io_fputs(smioerr, SM_TIME_DEFAULT, "usage: mailstats [-C cffile] [-c] [-P] [-f stfile] [-o] [-p]\n"); exit(EX_USAGE); } } argc -= optind; argv += optind; if (argc != 0) goto usage; if ((cfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, cfile, SM_IO_RDONLY, NULL)) == NULL) { save_errno = errno; (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "mailstats: "); errno = save_errno; sm_perror(cfile); exit(EX_NOINPUT); } mno = 0; (void) sm_strlcpy(mtable[mno++], "prog", MNAMELEN + 1); (void) sm_strlcpy(mtable[mno++], "*file*", MNAMELEN + 1); (void) sm_strlcpy(mtable[mno++], "*include*", MNAMELEN + 1); - while (sm_io_fgets(cfp, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(cfp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { register char *b; char *s; register char *m; b = strchr(buf, '#'); if (b == NULL) b = strchr(buf, '\n'); if (b == NULL) b = &buf[strlen(buf)]; while (isascii(*--b) && isspace(*b)) continue; *++b = '\0'; b = buf; switch (*b++) { case 'M': /* mailer definition */ break; case 'O': /* option -- see if .st file */ if (sm_strncasecmp(b, " StatusFile", 11) == 0 && !(isascii(b[11]) && isalnum(b[11]))) { /* new form -- find value */ b = strchr(b, '='); if (b == NULL) continue; while (isascii(*++b) && isspace(*b)) continue; } else if (*b++ != 'S') { /* something else boring */ continue; } /* this is the S or StatusFile option -- save it */ if (sm_strlcpy(sfilebuf, b, sizeof sfilebuf) >= sizeof sfilebuf) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "StatusFile filename too long: %.30s...\n", b); exit(EX_CONFIG); } if (sfile == NULL) sfile = sfilebuf; default: continue; } if (mno >= MAXMAILERS) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "Too many mailers defined, %d max.\n", MAXMAILERS); exit(EX_SOFTWARE); } m = mtable[mno]; s = m + MNAMELEN; /* is [MNAMELEN + 1] */ while (*b != ',' && !(isascii(*b) && isspace(*b)) && *b != '\0' && m < s) *m++ = *b++; *m = '\0'; for (i = 0; i < mno; i++) { if (strcmp(mtable[i], mtable[mno]) == 0) break; } if (i == mno) mno++; } (void) sm_io_close(cfp, SM_TIME_DEFAULT); for (; mno < MAXMAILERS; mno++) mtable[mno][0] = '\0'; if (sfile == NULL) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "mailstats: no statistics file located\n"); exit(EX_OSFILE); } fd = open(sfile, O_RDONLY, 0600); if ((fd < 0) || (i = read(fd, &stats, sizeof stats)) < 0) { save_errno = errno; (void) sm_io_fputs(smioerr, SM_TIME_DEFAULT, "mailstats: "); errno = save_errno; sm_perror(sfile); exit(EX_NOINPUT); } if (i == 0) { (void) sleep(1); if ((i = read(fd, &stats, sizeof stats)) < 0) { save_errno = errno; (void) sm_io_fputs(smioerr, SM_TIME_DEFAULT, "mailstats: "); errno = save_errno; sm_perror(sfile); exit(EX_NOINPUT); } else if (i == 0) { memset((ARBPTR_T) &stats, '\0', sizeof stats); (void) time(&stats.stat_itime); } } if (i != 0) { if (stats.stat_magic != STAT_MAGIC) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "mailstats: incorrect magic number in %s\n", sfile); exit(EX_OSERR); } else if (stats.stat_version != STAT_VERSION) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "mailstats version (%d) incompatible with %s version (%d)\n", STAT_VERSION, sfile, stats.stat_version); exit(EX_OSERR); } else if (i != sizeof stats || stats.stat_size != sizeof(stats)) { (void) sm_io_fputs(smioerr, SM_TIME_DEFAULT, "mailstats: file size changed.\n"); exit(EX_OSERR); } } + if (progmode) { (void) time(&now); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%ld %ld\n", (long) stats.stat_itime, (long) now); } else { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Statistics from %s", ctime(&stats.stat_itime)); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " M msgsfr bytes_from msgsto bytes_to msgsrej msgsdis"); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " msgsqur"); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s\n", mnames ? " Mailer" : ""); } for (i = 0; i < MAXMAILERS; i++) { if (stats.stat_nf[i] || stats.stat_nt[i] || stats.stat_nq[i] || stats.stat_nr[i] || stats.stat_nd[i]) { char *format; if (progmode) format = "%2d %8ld %10ld %8ld %10ld %6ld %6ld"; else format = "%2d %8ld %10ldK %8ld %10ldK %6ld %6ld"; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, format, i, stats.stat_nf[i], stats.stat_bf[i], stats.stat_nt[i], stats.stat_bt[i], stats.stat_nr[i], stats.stat_nd[i]); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " %6ld", stats.stat_nq[i]); if (mnames) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " %s", mtable[i]); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n"); frmsgs += stats.stat_nf[i]; frbytes += stats.stat_bf[i]; tomsgs += stats.stat_nt[i]; tobytes += stats.stat_bt[i]; rejmsgs += stats.stat_nr[i]; dismsgs += stats.stat_nd[i]; quarmsgs += stats.stat_nq[i]; } } if (progmode) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " T %8ld %10ld %8ld %10ld %6ld %6ld", frmsgs, frbytes, tomsgs, tobytes, rejmsgs, dismsgs); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " %6ld", quarmsgs); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n"); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " C %8ld %8ld %6ld\n", stats.stat_cf, stats.stat_ct, stats.stat_cr); (void) close(fd); if (trunc) { fd = open(sfile, O_RDWR | O_TRUNC, 0600); if (fd >= 0) (void) close(fd); } } else { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "============================================================="); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "========"); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n"); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " T %8ld %10ldK %8ld %10ldK %6ld %6ld", frmsgs, frbytes, tomsgs, tobytes, rejmsgs, dismsgs); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " %6ld", quarmsgs); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n"); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " C %8ld %10s %8ld %10s %6ld\n", stats.stat_cf, "", stats.stat_ct, "", stats.stat_cr); } exit(EX_OK); /* NOTREACHED */ return EX_OK; } Index: head/contrib/sendmail/makemap/makemap.c =================================================================== --- head/contrib/sendmail/makemap/makemap.c (revision 249728) +++ head/contrib/sendmail/makemap/makemap.c (revision 249729) @@ -1,529 +1,529 @@ /* * Copyright (c) 1998-2002, 2004, 2008 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1992 Eric P. Allman. All rights reserved. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include SM_IDSTR(copyright, "@(#) Copyright (c) 1998-2002, 2004 Sendmail, Inc. and its suppliers.\n\ All rights reserved.\n\ Copyright (c) 1992 Eric P. Allman. All rights reserved.\n\ Copyright (c) 1992, 1993\n\ The Regents of the University of California. All rights reserved.\n") -SM_IDSTR(id, "@(#)$Id: makemap.c,v 8.180 2010/11/23 02:35:08 gshapiro Exp $") +SM_IDSTR(id, "@(#)$Id: makemap.c,v 8.181 2013/03/12 15:24:51 ca Exp $") #include #ifndef ISC_UNIX # include #endif /* ! ISC_UNIX */ #include #include #include #ifdef EX_OK # undef EX_OK /* unistd.h may have another use for this */ #endif /* EX_OK */ #include #include #include #include uid_t RealUid; gid_t RealGid; char *RealUserName; uid_t RunAsUid; gid_t RunAsGid; char *RunAsUserName; int Verbose = 2; bool DontInitGroups = false; uid_t TrustedUid = 0; BITMAP256 DontBlameSendmail; #define BUFSIZE 1024 #define ISSEP(c) (sep == '\0' ? isascii(c) && isspace(c) : (c) == sep) static void usage __P((char *)); static void usage(progname) char *progname; { sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "Usage: %s [-C cffile] [-N] [-c cachesize] [-D commentchar]\n", progname); sm_io_fprintf(smioerr, SM_TIME_DEFAULT, " %*s [-d] [-e] [-f] [-l] [-o] [-r] [-s] [-t delimiter]\n", (int) strlen(progname), ""); sm_io_fprintf(smioerr, SM_TIME_DEFAULT, " %*s [-u] [-v] type mapname\n", (int) strlen(progname), ""); exit(EX_USAGE); } int main(argc, argv) int argc; char **argv; { char *progname; char *cfile; bool inclnull = false; bool notrunc = false; bool allowreplace = false; bool allowempty = false; bool verbose = false; bool foldcase = true; bool unmake = false; char sep = '\0'; char comment = '#'; int exitstat; int opt; char *typename = NULL; char *mapname = NULL; unsigned int lineno; int st; int mode; int smode; int putflags = 0; long sff = SFF_ROOTOK|SFF_REGONLY; struct passwd *pw; SMDB_DATABASE *database; SMDB_CURSOR *cursor; SMDB_DBENT db_key, db_val; SMDB_DBPARAMS params; SMDB_USER_INFO user_info; char ibuf[BUFSIZE]; #if HASFCHOWN SM_FILE_T *cfp; char buf[MAXLINE]; #endif /* HASFCHOWN */ static char rnamebuf[MAXNAME]; /* holds RealUserName */ extern char *optarg; extern int optind; memset(¶ms, '\0', sizeof params); params.smdbp_cache_size = 1024 * 1024; progname = strrchr(argv[0], '/'); if (progname != NULL) progname++; else progname = argv[0]; cfile = getcfname(0, 0, SM_GET_SENDMAIL_CF, NULL); clrbitmap(DontBlameSendmail); RunAsUid = RealUid = getuid(); RunAsGid = RealGid = getgid(); pw = getpwuid(RealUid); if (pw != NULL) (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof rnamebuf); else (void) sm_snprintf(rnamebuf, sizeof rnamebuf, "Unknown UID %d", (int) RealUid); RunAsUserName = RealUserName = rnamebuf; user_info.smdbu_id = RunAsUid; user_info.smdbu_group_id = RunAsGid; (void) sm_strlcpy(user_info.smdbu_name, RunAsUserName, SMDB_MAX_USER_NAME_LEN); #define OPTIONS "C:D:Nc:deflorst:uv" while ((opt = getopt(argc, argv, OPTIONS)) != -1) { switch (opt) { case 'C': cfile = optarg; break; case 'N': inclnull = true; break; case 'c': params.smdbp_cache_size = atol(optarg); break; case 'd': params.smdbp_allow_dup = true; break; case 'e': allowempty = true; break; case 'f': foldcase = false; break; case 'D': comment = *optarg; break; case 'l': smdb_print_available_types(); exit(EX_OK); break; case 'o': notrunc = true; break; case 'r': allowreplace = true; break; case 's': setbitn(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail); setbitn(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail); setbitn(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail); setbitn(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail); break; case 't': if (optarg == NULL || *optarg == '\0') { sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "Invalid separator\n"); break; } sep = *optarg; break; case 'u': unmake = true; break; case 'v': verbose = true; break; default: usage(progname); /* NOTREACHED */ } } if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail)) sff |= SFF_NOSLINK; if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail)) sff |= SFF_NOHLINK; if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; argc -= optind; argv += optind; if (argc != 2) { usage(progname); /* NOTREACHED */ } else { typename = argv[0]; mapname = argv[1]; } #if HASFCHOWN /* Find TrustedUser value in sendmail.cf */ if ((cfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, cfile, SM_IO_RDONLY, NULL)) == NULL) { sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "makemap: %s: %s\n", cfile, sm_errstring(errno)); exit(EX_NOINPUT); } - while (sm_io_fgets(cfp, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(cfp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { register char *b; if ((b = strchr(buf, '\n')) != NULL) *b = '\0'; b = buf; switch (*b++) { case 'O': /* option */ if (strncasecmp(b, " TrustedUser", 12) == 0 && !(isascii(b[12]) && isalnum(b[12]))) { b = strchr(b, '='); if (b == NULL) continue; while (isascii(*++b) && isspace(*b)) continue; if (isascii(*b) && isdigit(*b)) TrustedUid = atoi(b); else { TrustedUid = 0; pw = getpwnam(b); if (pw == NULL) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "TrustedUser: unknown user %s\n", b); else TrustedUid = pw->pw_uid; } # ifdef UID_MAX if (TrustedUid > UID_MAX) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "TrustedUser: uid value (%ld) > UID_MAX (%ld)", (long) TrustedUid, (long) UID_MAX); TrustedUid = 0; } # endif /* UID_MAX */ break; } default: continue; } } (void) sm_io_close(cfp, SM_TIME_DEFAULT); #endif /* HASFCHOWN */ if (!params.smdbp_allow_dup && !allowreplace) putflags = SMDBF_NO_OVERWRITE; if (unmake) { mode = O_RDONLY; smode = S_IRUSR; } else { mode = O_RDWR; if (!notrunc) { mode |= O_CREAT|O_TRUNC; sff |= SFF_CREAT; } smode = S_IWUSR; } params.smdbp_num_elements = 4096; errno = smdb_open_database(&database, mapname, mode, smode, sff, typename, &user_info, ¶ms); if (errno != SMDBE_OK) { char *hint; if (errno == SMDBE_UNSUPPORTED_DB_TYPE && (hint = smdb_db_definition(typename)) != NULL) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: Need to recompile with -D%s for %s support\n", progname, hint, typename); else (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: error opening type %s map %s: %s\n", progname, typename, mapname, sm_errstring(errno)); exit(EX_CANTCREAT); } (void) database->smdb_sync(database, 0); if (!unmake && geteuid() == 0 && TrustedUid != 0) { errno = database->smdb_set_owner(database, TrustedUid, -1); if (errno != SMDBE_OK) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "WARNING: ownership change on %s failed %s", mapname, sm_errstring(errno)); } } /* ** Copy the data */ exitstat = EX_OK; if (unmake) { errno = database->smdb_cursor(database, &cursor, 0); if (errno != SMDBE_OK) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: cannot make cursor for type %s map %s\n", progname, typename, mapname); exit(EX_SOFTWARE); } memset(&db_key, '\0', sizeof db_key); memset(&db_val, '\0', sizeof db_val); for (lineno = 0; ; lineno++) { errno = cursor->smdbc_get(cursor, &db_key, &db_val, SMDB_CURSOR_GET_NEXT); if (errno != SMDBE_OK) break; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s%c%.*s\n", (int) db_key.size, (char *) db_key.data, (sep != '\0') ? sep : '\t', (int) db_val.size, (char *)db_val.data); } (void) cursor->smdbc_close(cursor); } else { lineno = 0; while (sm_io_fgets(smioin, SM_TIME_DEFAULT, ibuf, sizeof ibuf) - != NULL) + >= 0) { register char *p; lineno++; /* ** Parse the line. */ p = strchr(ibuf, '\n'); if (p != NULL) *p = '\0'; else if (!sm_io_eof(smioin)) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: %s: line %u: line too long (%ld bytes max)\n", progname, mapname, lineno, (long) sizeof ibuf); exitstat = EX_DATAERR; continue; } if (ibuf[0] == '\0' || ibuf[0] == comment) continue; if (sep == '\0' && isascii(ibuf[0]) && isspace(ibuf[0])) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: %s: line %u: syntax error (leading space)\n", progname, mapname, lineno); exitstat = EX_DATAERR; continue; } memset(&db_key, '\0', sizeof db_key); memset(&db_val, '\0', sizeof db_val); db_key.data = ibuf; for (p = ibuf; *p != '\0' && !(ISSEP(*p)); p++) { if (foldcase && isascii(*p) && isupper(*p)) *p = tolower(*p); } db_key.size = p - ibuf; if (inclnull) db_key.size++; if (*p != '\0') *p++ = '\0'; while (*p != '\0' && ISSEP(*p)) p++; if (!allowempty && *p == '\0') { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: %s: line %u: no RHS for LHS %s\n", progname, mapname, lineno, (char *) db_key.data); exitstat = EX_DATAERR; continue; } db_val.data = p; db_val.size = strlen(p); if (inclnull) db_val.size++; /* ** Do the database insert. */ if (verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "key=`%s', val=`%s'\n", (char *) db_key.data, (char *) db_val.data); } errno = database->smdb_put(database, &db_key, &db_val, putflags); switch (errno) { case SMDBE_KEY_EXIST: st = 1; break; case 0: st = 0; break; default: st = -1; break; } if (st < 0) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: %s: line %u: key %s: put error: %s\n", progname, mapname, lineno, (char *) db_key.data, sm_errstring(errno)); exitstat = EX_IOERR; } else if (st > 0) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: %s: line %u: key %s: duplicate key\n", progname, mapname, lineno, (char *) db_key.data); exitstat = EX_DATAERR; } } } /* ** Now close the database. */ errno = database->smdb_close(database); if (errno != SMDBE_OK) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: close(%s): %s\n", progname, mapname, sm_errstring(errno)); exitstat = EX_IOERR; } smdb_free_database(database); exit(exitstat); /* NOTREACHED */ return exitstat; } Index: head/contrib/sendmail/praliases/praliases.c =================================================================== --- head/contrib/sendmail/praliases/praliases.c (revision 249728) +++ head/contrib/sendmail/praliases/praliases.c (revision 249729) @@ -1,398 +1,398 @@ /* * Copyright (c) 1998-2001, 2008 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include SM_IDSTR(copyright, "@(#) Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers.\n\ All rights reserved.\n\ Copyright (c) 1983 Eric P. Allman. All rights reserved.\n\ Copyright (c) 1988, 1993\n\ The Regents of the University of California. All rights reserved.\n") -SM_IDSTR(id, "@(#)$Id: praliases.c,v 8.96 2008/07/10 20:13:10 ca Exp $") +SM_IDSTR(id, "@(#)$Id: praliases.c,v 8.97 2013/03/12 15:24:51 ca Exp $") #include #include #include #include #ifdef EX_OK # undef EX_OK /* unistd.h may have another use for this */ #endif /* EX_OK */ #include #ifndef NOT_SENDMAIL # define NOT_SENDMAIL #endif /* ! NOT_SENDMAIL */ #include #include #include static void praliases __P((char *, int, char **)); uid_t RealUid; gid_t RealGid; char *RealUserName; uid_t RunAsUid; gid_t RunAsGid; char *RunAsUserName; int Verbose = 2; bool DontInitGroups = false; uid_t TrustedUid = 0; BITMAP256 DontBlameSendmail; # define DELIMITERS " ,/" # define PATH_SEPARATOR ':' int main(argc, argv) int argc; char **argv; { char *cfile; char *filename = NULL; SM_FILE_T *cfp; int ch; char afilebuf[MAXLINE]; char buf[MAXLINE]; struct passwd *pw; static char rnamebuf[MAXNAME]; extern char *optarg; extern int optind; clrbitmap(DontBlameSendmail); RunAsUid = RealUid = getuid(); RunAsGid = RealGid = getgid(); pw = getpwuid(RealUid); if (pw != NULL) { if (strlen(pw->pw_name) > MAXNAME - 1) pw->pw_name[MAXNAME] = 0; sm_snprintf(rnamebuf, sizeof rnamebuf, "%s", pw->pw_name); } else (void) sm_snprintf(rnamebuf, sizeof rnamebuf, "Unknown UID %d", (int) RealUid); RunAsUserName = RealUserName = rnamebuf; cfile = getcfname(0, 0, SM_GET_SENDMAIL_CF, NULL); while ((ch = getopt(argc, argv, "C:f:")) != -1) { switch ((char)ch) { case 'C': cfile = optarg; break; case 'f': filename = optarg; break; case '?': default: (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "usage: praliases [-C cffile] [-f aliasfile]" " [key ...]\n"); exit(EX_USAGE); } } argc -= optind; argv += optind; if (filename != NULL) { praliases(filename, argc, argv); exit(EX_OK); } if ((cfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, cfile, SM_IO_RDONLY, NULL)) == NULL) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "praliases: %s: %s\n", cfile, sm_errstring(errno)); exit(EX_NOINPUT); } - while (sm_io_fgets(cfp, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(cfp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { register char *b, *p; b = strchr(buf, '\n'); if (b != NULL) *b = '\0'; b = buf; switch (*b++) { case 'O': /* option -- see if alias file */ if (sm_strncasecmp(b, " AliasFile", 10) == 0 && !(isascii(b[10]) && isalnum(b[10]))) { /* new form -- find value */ b = strchr(b, '='); if (b == NULL) continue; while (isascii(*++b) && isspace(*b)) continue; } else if (*b++ != 'A') { /* something else boring */ continue; } /* this is the A or AliasFile option -- save it */ if (sm_strlcpy(afilebuf, b, sizeof afilebuf) >= sizeof afilebuf) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "praliases: AliasFile filename too long: %.30s\n", b); (void) sm_io_close(cfp, SM_TIME_DEFAULT); exit(EX_CONFIG); } b = afilebuf; for (p = b; p != NULL; ) { while (isascii(*p) && isspace(*p)) p++; if (*p == '\0') break; b = p; p = strpbrk(p, DELIMITERS); /* find end of spec */ if (p != NULL) { bool quoted = false; for (; *p != '\0'; p++) { /* ** Don't break into a quoted ** string. */ if (*p == '"') quoted = !quoted; else if (*p == ',' && !quoted) break; } /* No more alias specs follow */ if (*p == '\0') { /* chop trailing whitespace */ while (isascii(*p) && isspace(*p) && p > b) p--; *p = '\0'; p = NULL; } } if (p != NULL) { char *e = p - 1; /* chop trailing whitespace */ while (isascii(*e) && isspace(*e) && e > b) e--; *++e = '\0'; *p++ = '\0'; } praliases(b, argc, argv); } default: continue; } } (void) sm_io_close(cfp, SM_TIME_DEFAULT); exit(EX_OK); /* NOTREACHED */ return EX_OK; } static void praliases(filename, argc, argv) char *filename; int argc; char **argv; { int result; char *colon; char *db_name; char *db_type; SMDB_DATABASE *database = NULL; SMDB_CURSOR *cursor = NULL; SMDB_DBENT db_key, db_value; SMDB_DBPARAMS params; SMDB_USER_INFO user_info; colon = strchr(filename, PATH_SEPARATOR); if (colon == NULL) { db_name = filename; db_type = SMDB_TYPE_DEFAULT; } else { *colon = '\0'; db_name = colon + 1; db_type = filename; } /* clean off arguments */ for (;;) { while (isascii(*db_name) && isspace(*db_name)) db_name++; if (*db_name != '-') break; while (*db_name != '\0' && !(isascii(*db_name) && isspace(*db_name))) db_name++; } /* Skip non-file based DB types */ if (db_type != NULL && *db_type != '\0') { if (db_type != SMDB_TYPE_DEFAULT && strcmp(db_type, "hash") != 0 && strcmp(db_type, "btree") != 0 && strcmp(db_type, "dbm") != 0) { sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "praliases: Skipping non-file based alias type %s\n", db_type); return; } } if (*db_name == '\0' || (db_type != NULL && *db_type == '\0')) { if (colon != NULL) *colon = ':'; (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "praliases: illegal alias specification: %s\n", filename); goto fatal; } memset(¶ms, '\0', sizeof params); params.smdbp_cache_size = 1024 * 1024; user_info.smdbu_id = RunAsUid; user_info.smdbu_group_id = RunAsGid; (void) sm_strlcpy(user_info.smdbu_name, RunAsUserName, SMDB_MAX_USER_NAME_LEN); result = smdb_open_database(&database, db_name, O_RDONLY, 0, SFF_ROOTOK, db_type, &user_info, ¶ms); if (result != SMDBE_OK) { sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "praliases: %s: open: %s\n", db_name, sm_errstring(result)); goto fatal; } if (argc == 0) { memset(&db_key, '\0', sizeof db_key); memset(&db_value, '\0', sizeof db_value); result = database->smdb_cursor(database, &cursor, 0); if (result != SMDBE_OK) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "praliases: %s: set cursor: %s\n", db_name, sm_errstring(result)); goto fatal; } while ((result = cursor->smdbc_get(cursor, &db_key, &db_value, SMDB_CURSOR_GET_NEXT)) == SMDBE_OK) { #if 0 /* skip magic @:@ entry */ if (db_key.size == 2 && db_key.data[0] == '@' && db_key.data[1] == '\0' && db_value.size == 2 && db_value.data[0] == '@' && db_value.data[1] == '\0') continue; #endif /* 0 */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s:%.*s\n", (int) db_key.size, (char *) db_key.data, (int) db_value.size, (char *) db_value.data); } if (result != SMDBE_OK && result != SMDBE_LAST_ENTRY) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "praliases: %s: get value at cursor: %s\n", db_name, sm_errstring(result)); goto fatal; } } else for (; *argv != NULL; ++argv) { int get_res; memset(&db_key, '\0', sizeof db_key); memset(&db_value, '\0', sizeof db_value); db_key.data = *argv; db_key.size = strlen(*argv); get_res = database->smdb_get(database, &db_key, &db_value, 0); if (get_res == SMDBE_NOT_FOUND) { db_key.size++; get_res = database->smdb_get(database, &db_key, &db_value, 0); } if (get_res == SMDBE_OK) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s:%.*s\n", (int) db_key.size, (char *) db_key.data, (int) db_value.size, (char *) db_value.data); } else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: No such key\n", (char *)db_key.data); } fatal: if (cursor != NULL) (void) cursor->smdbc_close(cursor); if (database != NULL) (void) database->smdb_close(database); if (colon != NULL) *colon = ':'; return; } Index: head/contrib/sendmail/rmail/rmail.c =================================================================== --- head/contrib/sendmail/rmail/rmail.c (revision 249728) +++ head/contrib/sendmail/rmail/rmail.c (revision 249729) @@ -1,439 +1,439 @@ /* * Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * * $FreeBSD$ * */ #include SM_IDSTR(copyright, "@(#) Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers.\n\ All rights reserved.\n\ Copyright (c) 1988, 1993\n\ The Regents of the University of California. All rights reserved.\n") -SM_IDSTR(id, "@(#)$Id: rmail.c,v 8.61 2001/09/18 21:45:29 gshapiro Exp $") +SM_IDSTR(id, "@(#)$Id: rmail.c,v 8.62 2013/03/12 15:24:52 ca Exp $") /* * RMAIL -- UUCP mail server. * * This program reads the >From ... remote from ... lines that UUCP is so * fond of and turns them into something reasonable. It then execs sendmail * with various options built from these lines. * * The expected syntax is: * * := [-a-z0-9]+ * := ctime format * := [-a-z0-9!]+ * := "^\n$" * := "From" * [ "remote from" ] * := ">" * msg := * * * The output of rmail(8) compresses the lines into a single * from path. * * The err(3) routine is included here deliberately to make this code * a bit more portable. */ #include #include #include #include #include #include #include #include #include #include #ifdef EX_OK # undef EX_OK /* unistd.h may have another use for this */ #endif /* EX_OK */ #include #include #include #include static void err __P((int, const char *, ...)); static void usage __P((void)); static char *xalloc __P((int)); #define newstr(s) strcpy(xalloc(strlen(s) + 1), s) static char * xalloc(sz) register int sz; { register char *p; /* some systems can't handle size zero mallocs */ if (sz <= 0) sz = 1; p = malloc(sz); if (p == NULL) err(EX_TEMPFAIL, "out of memory"); return (p); } int main(argc, argv) int argc; char *argv[]; { int ch, debug, i, pdes[2], pid, status; size_t fplen = 0, fptlen = 0, len; off_t offset; SM_FILE_T *fp; char *addrp = NULL, *domain, *p, *t; char *from_path, *from_sys, *from_user; char **args, buf[2048], lbuf[2048]; struct stat sb; extern char *optarg; extern int optind; debug = 0; domain = "UUCP"; /* Default "domain". */ while ((ch = getopt(argc, argv, "D:T")) != -1) { switch (ch) { case 'T': debug = 1; break; case 'D': domain = optarg; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc < 1) usage(); from_path = from_sys = from_user = NULL; for (offset = 0; ; ) { /* Get and nul-terminate the line. */ if (sm_io_fgets(smioin, SM_TIME_DEFAULT, lbuf, - sizeof(lbuf)) == NULL) + sizeof(lbuf)) < 0) err(EX_DATAERR, "no data"); if ((p = strchr(lbuf, '\n')) == NULL) err(EX_DATAERR, "line too long"); *p = '\0'; /* Parse lines until reach a non-"From" line. */ if (!strncmp(lbuf, "From ", 5)) addrp = lbuf + 5; else if (!strncmp(lbuf, ">From ", 6)) addrp = lbuf + 6; else if (offset == 0) err(EX_DATAERR, "missing or empty From line: %s", lbuf); else { *p = '\n'; break; } if (addrp == NULL || *addrp == '\0') err(EX_DATAERR, "corrupted From line: %s", lbuf); /* Use the "remote from" if it exists. */ for (p = addrp; (p = strchr(p + 1, 'r')) != NULL; ) { if (!strncmp(p, "remote from ", 12)) { for (t = p += 12; *t != '\0'; ++t) { if (isascii(*t) && isspace(*t)) break; } *t = '\0'; if (debug) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "remote from: %s\n", p); break; } } /* Else use the string up to the last bang. */ if (p == NULL) { if (*addrp == '!') err(EX_DATAERR, "bang starts address: %s", addrp); else if ((t = strrchr(addrp, '!')) != NULL) { *t = '\0'; p = addrp; addrp = t + 1; if (*addrp == '\0') err(EX_DATAERR, "corrupted From line: %s", lbuf); if (debug) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "bang: %s\n", p); } } /* 'p' now points to any system string from this line. */ if (p != NULL) { /* Nul terminate it as necessary. */ for (t = p; *t != '\0'; ++t) { if (isascii(*t) && isspace(*t)) break; } *t = '\0'; /* If the first system, copy to the from_sys string. */ if (from_sys == NULL) { from_sys = newstr(p); if (debug) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "from_sys: %s\n", from_sys); } /* Concatenate to the path string. */ len = t - p; if (from_path == NULL) { fplen = 0; if ((from_path = malloc(fptlen = 256)) == NULL) err(EX_TEMPFAIL, "out of memory"); } if (fplen + len + 2 > fptlen) { fptlen += SM_MAX(fplen + len + 2, 256); if ((from_path = realloc(from_path, fptlen)) == NULL) err(EX_TEMPFAIL, "out of memory"); } memmove(from_path + fplen, p, len); fplen += len; from_path[fplen++] = '!'; from_path[fplen] = '\0'; } /* Save off from user's address; the last one wins. */ for (p = addrp; *p != '\0'; ++p) { if (isascii(*p) && isspace(*p)) break; } *p = '\0'; if (*addrp == '\0') addrp = "<>"; if (from_user != NULL) free(from_user); from_user = newstr(addrp); if (debug) { if (from_path != NULL) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "from_path: %s\n", from_path); (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "from_user: %s\n", from_user); } if (offset != -1) offset = (off_t)sm_io_tell(smioin, SM_TIME_DEFAULT); } /* Allocate args (with room for sendmail args as well as recipients */ args = (char **)xalloc(sizeof(*args) * (10 + argc)); i = 0; args[i++] = _PATH_SENDMAIL; /* Build sendmail's argument list. */ args[i++] = "-G"; /* relay submission */ args[i++] = "-oee"; /* No errors, just status. */ #ifdef QUEUE_ONLY args[i++] = "-odq"; /* Queue it, don't try to deliver. */ #else args[i++] = "-odi"; /* Deliver in foreground. */ #endif args[i++] = "-oi"; /* Ignore '.' on a line by itself. */ /* set from system and protocol used */ if (from_sys == NULL) sm_snprintf(buf, sizeof(buf), "-p%s", domain); else if (strchr(from_sys, '.') == NULL) sm_snprintf(buf, sizeof(buf), "-p%s:%s.%s", domain, from_sys, domain); else sm_snprintf(buf, sizeof(buf), "-p%s:%s", domain, from_sys); args[i++] = newstr(buf); /* Set name of ``from'' person. */ sm_snprintf(buf, sizeof(buf), "-f%s%s", from_path ? from_path : "", from_user); args[i++] = newstr(buf); /* ** Don't copy arguments beginning with - as they will be ** passed to sendmail and could be interpreted as flags. ** To prevent confusion of sendmail wrap < and > around ** the address (helps to pass addrs like @gw1,@gw2:aa@bb) */ while (*argv != NULL) { if (**argv == '-') err(EX_USAGE, "dash precedes argument: %s", *argv); if (strchr(*argv, ',') == NULL || strchr(*argv, '<') != NULL) args[i++] = *argv; else { len = strlen(*argv) + 3; if ((args[i] = malloc(len)) == NULL) err(EX_TEMPFAIL, "Cannot malloc"); sm_snprintf(args[i++], len, "<%s>", *argv); } argv++; argc--; /* Paranoia check, argc used for args[] bound */ if (argc < 0) err(EX_SOFTWARE, "Argument count mismatch"); } args[i] = NULL; if (debug) { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "Sendmail arguments:\n"); for (i = 0; args[i] != NULL; i++) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "\t%s\n", args[i]); } /* ** If called with a regular file as standard input, seek to the right ** position in the file and just exec sendmail. Could probably skip ** skip the stat, but it's not unreasonable to believe that a failed ** seek will cause future reads to fail. */ if (!fstat(STDIN_FILENO, &sb) && S_ISREG(sb.st_mode)) { if (lseek(STDIN_FILENO, offset, SEEK_SET) != offset) err(EX_TEMPFAIL, "stdin seek"); (void) execv(_PATH_SENDMAIL, args); err(EX_OSERR, "%s", _PATH_SENDMAIL); } if (pipe(pdes) < 0) err(EX_OSERR, "pipe failed"); switch (pid = fork()) { case -1: /* Err. */ err(EX_OSERR, "fork failed"); /* NOTREACHED */ case 0: /* Child. */ if (pdes[0] != STDIN_FILENO) { (void) dup2(pdes[0], STDIN_FILENO); (void) close(pdes[0]); } (void) close(pdes[1]); (void) execv(_PATH_SENDMAIL, args); err(EX_UNAVAILABLE, "%s", _PATH_SENDMAIL); /* NOTREACHED */ } if ((fp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &(pdes[1]), SM_IO_WRONLY, NULL)) == NULL) err(EX_OSERR, "sm_io_open failed"); (void) close(pdes[0]); /* Copy the file down the pipe. */ do { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s", lbuf); } while (sm_io_fgets(smioin, SM_TIME_DEFAULT, lbuf, - sizeof(lbuf)) != NULL); + sizeof(lbuf)) >= 0); if (sm_io_error(smioin)) err(EX_TEMPFAIL, "stdin: %s", sm_errstring(errno)); if (sm_io_close(fp, SM_TIME_DEFAULT)) err(EX_OSERR, "sm_io_close failed"); if ((waitpid(pid, &status, 0)) == -1) err(EX_OSERR, "%s", _PATH_SENDMAIL); if (!WIFEXITED(status)) err(EX_OSERR, "%s: did not terminate normally", _PATH_SENDMAIL); if (WEXITSTATUS(status)) err(status, "%s: terminated with %d (non-zero) status", _PATH_SENDMAIL, WEXITSTATUS(status)); exit(EX_OK); /* NOTREACHED */ return EX_OK; } static void usage() { (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "usage: rmail [-T] [-D domain] user ...\n"); exit(EX_USAGE); } static void #ifdef __STDC__ err(int eval, const char *fmt, ...) #else /* __STDC__ */ err(eval, fmt, va_alist) int eval; const char *fmt; va_dcl #endif /* __STDC__ */ { SM_VA_LOCAL_DECL if (fmt != NULL) { SM_VA_START(ap, fmt); (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "rmail: "); (void) sm_io_vfprintf(smioerr, SM_TIME_DEFAULT, fmt, ap); SM_VA_END(ap); (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "\n"); } exit(eval); } Index: head/contrib/sendmail/src/Makefile.m4 =================================================================== --- head/contrib/sendmail/src/Makefile.m4 (revision 249728) +++ head/contrib/sendmail/src/Makefile.m4 (revision 249729) @@ -1,103 +1,103 @@ -dnl $Id: Makefile.m4,v 8.132 2012/09/11 20:02:44 ca Exp $ +dnl $Id: Makefile.m4,v 8.139 2013/04/17 17:15:54 ca Exp $ include(confBUILDTOOLSDIR`/M4/switch.m4') define(`confREQUIRE_LIBSM', `true') define(`confREQUIRE_SM_OS_H', `true') bldPRODUCT_START(`executable', `sendmail') define(`bldBIN_TYPE', `G') define(`bldINSTALL_DIR', `') define(`bldSOURCES', `main.c alias.c arpadate.c bf.c collect.c conf.c control.c convtime.c daemon.c deliver.c domain.c envelope.c err.c headers.c macro.c map.c mci.c milter.c mime.c parseaddr.c queue.c ratectrl.c readcf.c recipient.c sasl.c savemail.c sfsasl.c shmticklib.c sm_resolve.c srvrsmtp.c stab.c stats.c sysexits.c timers.c tls.c trace.c udb.c usersmtp.c util.c version.c ') PREPENDDEF(`confENVDEF', `confMAPDEF') bldPUSH_SMLIB(`sm') bldPUSH_SMLIB(`smutil') dnl hack: /etc/mail is not defined as "location of .cf" in the build system define(`bldTARGET_INST_DEP', ifdef(`confINST_DEP', `confINST_DEP', `${DESTDIR}/etc/mail/submit.cf ${DESTDIR}${MSPQ}'))dnl define(`bldTARGET_LINKS', ifdef(`confLINKS', `confLINKS', `${DESTDIR}${UBINDIR}/newaliases ${DESTDIR}${UBINDIR}/mailq ${DESTDIR}${UBINDIR}/hoststat ${DESTDIR}${UBINDIR}/purgestat') )dnl # location of sendmail statistics file (usually /etc/mail/ or /var/log) STDIR= ifdef(`confSTDIR', `confSTDIR', `/etc/mail') # statistics file name STFILE= ifdef(`confSTFILE', `confSTFILE', `statistics') MSPSTFILE=ifdef(`confMSP_STFILE', `confMSP_STFILE', `sm-client.st') # full path to installed statistics file (usually ${STDIR}/statistics) STPATH= ${STDIR}/${STFILE} # location of sendmail helpfile file (usually /etc/mail) HFDIR= ifdef(`confHFDIR', `confHFDIR', `/etc/mail') # full path to installed help file (usually ${HFDIR}/helpfile) HFFILE= ${HFDIR}/ifdef(`confHFFILE', `confHFFILE', `helpfile') ifdef(`confSMSRCADD', `APPENDDEF(`confSRCADD', `confSMSRCADD')') ifdef(`confSMOBJADD', `APPENDDEF(`confOBJADD', `confSMOBJADD')') bldPUSH_TARGET(`statistics') divert(bldTARGETS_SECTION) statistics: ${CP} /dev/null statistics ${DESTDIR}/etc/mail/submit.cf: @echo "Please read INSTALL if anything fails while installing the binary." @echo "${DESTDIR}/etc/mail/submit.cf will be installed now." cd ${SRCDIR}/cf/cf && make install-submit-cf MSPQ=ifdef(`confMSP_QUEUE_DIR', `confMSP_QUEUE_DIR', `/var/spool/clientmqueue') ${DESTDIR}${MSPQ}: @echo "Please read INSTALL if anything fails while installing the binary." @echo "You must have setup a new user ${MSPQOWN} and a new group ${GBINGRP}" @echo "as explained in sendmail/SECURITY." mkdir -p ${DESTDIR}${MSPQ} chown ${MSPQOWN} ${DESTDIR}${MSPQ} chgrp ${GBINGRP} ${DESTDIR}${MSPQ} chmod 0770 ${DESTDIR}${MSPQ} divert(0) ifdef(`confSETUSERID_INSTALL', `bldPUSH_INSTALL_TARGET(`install-set-user-id')') ifdef(`confMTA_INSTALL', `bldPUSH_INSTALL_TARGET(`install-sm-mta')') ifdef(`confNO_HELPFILE_INSTALL',, `bldPUSH_INSTALL_TARGET(`install-hf')') ifdef(`confNO_STATISTICS_INSTALL',, `bldPUSH_INSTALL_TARGET(`install-st')') divert(bldTARGETS_SECTION) install-set-user-id: bldCURRENT_PRODUCT ifdef(`confNO_HELPFILE_INSTALL',, `install-hf') ifdef(`confNO_STATISTICS_INSTALL',, `install-st') ifdef(`confNO_MAN_BUILD',, `install-docs') ${INSTALL} -c -o ${S`'BINOWN} -g ${S`'BINGRP} -m ${S`'BINMODE} bldCURRENT_PRODUCT ${DESTDIR}${M`'BINDIR} for i in ${sendmailTARGET_LINKS}; do \ rm -f $$i; \ ${LN} ${LNOPTS} ${M`'BINDIR}/sendmail $$i; \ done define(`confMTA_LINKS', `${DESTDIR}${UBINDIR}/newaliases ${DESTDIR}${UBINDIR}/mailq ${DESTDIR}${UBINDIR}/hoststat ${DESTDIR}${UBINDIR}/purgestat') install-sm-mta: bldCURRENT_PRODUCT ${INSTALL} -c -o ${M`'BINOWN} -g ${M`'BINGRP} -m ${M`'BINMODE} bldCURRENT_PRODUCT ${DESTDIR}${M`'BINDIR}/sm-mta for i in confMTA_LINKS; do \ rm -f $$i; \ ${LN} ${LNOPTS} ${M`'BINDIR}/sm-mta $$i; \ done install-hf: if [ ! -d ${DESTDIR}${HFDIR} ]; then mkdir -p ${DESTDIR}${HFDIR}; else :; fi ${INSTALL} -c -o ${UBINOWN} -g ${UBINGRP} -m 444 helpfile ${DESTDIR}${HFFILE} install-st: statistics if [ ! -d ${DESTDIR}${STDIR} ]; then mkdir -p ${DESTDIR}${STDIR}; else :; fi ${INSTALL} -c -o ${SBINOWN} -g ${UBINGRP} -m ifdef(`confSTMODE', `confSTMODE', `0600') statistics ${DESTDIR}${STPATH} install-submit-st: statistics ${DESTDIR}${MSPQ} ${INSTALL} -c -o ${MSPQOWN} -g ${GBINGRP} -m ifdef(`confSTMODE', `confSTMODE', `0600') statistics ${DESTDIR}${MSPQ}/${MSPSTFILE} divert(0) bldPRODUCT_END bldPRODUCT_START(`manpage', `sendmail') define(`bldSOURCES', `sendmail.8 aliases.5 mailq.1 newaliases.1') bldPRODUCT_END bldFINISH Index: head/contrib/sendmail/src/alias.c =================================================================== --- head/contrib/sendmail/src/alias.c (revision 249728) +++ head/contrib/sendmail/src/alias.c (revision 249729) @@ -1,1015 +1,1015 @@ /* * Copyright (c) 1998-2003 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: alias.c,v 8.219 2006/10/24 18:04:09 ca Exp $") +SM_RCSID("@(#)$Id: alias.c,v 8.220 2013/03/12 15:24:52 ca Exp $") #define SEPARATOR ':' # define ALIAS_SPEC_SEPARATORS " ,/:" static MAP *AliasFileMap = NULL; /* the actual aliases.files map */ static int NAliasFileMaps; /* the number of entries in AliasFileMap */ static char *aliaslookup __P((char *, int *, char *)); /* ** ALIAS -- Compute aliases. ** ** Scans the alias file for an alias for the given address. ** If found, it arranges to deliver to the alias list instead. ** Uses libdbm database if -DDBM. ** ** Parameters: ** a -- address to alias. ** sendq -- a pointer to the head of the send queue ** to put the aliases in. ** aliaslevel -- the current alias nesting depth. ** e -- the current envelope. ** ** Returns: ** none ** ** Side Effects: ** Aliases found are expanded. ** ** Deficiencies: ** It should complain about names that are aliased to ** nothing. */ void alias(a, sendq, aliaslevel, e) register ADDRESS *a; ADDRESS **sendq; int aliaslevel; register ENVELOPE *e; { register char *p; char *owner; auto int status = EX_OK; char obuf[MAXNAME + 7]; if (tTd(27, 1)) sm_dprintf("alias(%s)\n", a->q_user); /* don't realias already aliased names */ if (!QS_IS_OK(a->q_state)) return; if (NoAlias) return; e->e_to = a->q_paddr; /* ** Look up this name. ** ** If the map was unavailable, we will queue this message ** until the map becomes available; otherwise, we could ** bounce messages inappropriately. */ #if _FFR_REDIRECTEMPTY /* ** envelope <> can't be sent to mailing lists, only owner- ** send spam of this type to owner- of the list ** ---- to stop spam from going to mailing lists! */ if (e->e_sender != NULL && *e->e_sender == '\0') { /* Look for owner of alias */ (void) sm_strlcpyn(obuf, sizeof(obuf), 2, "owner-", a->q_user); if (aliaslookup(obuf, &status, a->q_host) != NULL) { if (LogLevel > 8) sm_syslog(LOG_WARNING, e->e_id, "possible spam from <> to list: %s, redirected to %s\n", a->q_user, obuf); a->q_user = sm_rpool_strdup_x(e->e_rpool, obuf); } } #endif /* _FFR_REDIRECTEMPTY */ p = aliaslookup(a->q_user, &status, a->q_host); if (status == EX_TEMPFAIL || status == EX_UNAVAILABLE) { a->q_state = QS_QUEUEUP; if (e->e_message == NULL) e->e_message = sm_rpool_strdup_x(e->e_rpool, "alias database unavailable"); /* XXX msg only per recipient? */ if (a->q_message == NULL) a->q_message = "alias database unavailable"; return; } if (p == NULL) return; /* ** Match on Alias. ** Deliver to the target list. */ if (tTd(27, 1)) sm_dprintf("%s (%s, %s) aliased to %s\n", a->q_paddr, a->q_host, a->q_user, p); if (bitset(EF_VRFYONLY, e->e_flags)) { a->q_state = QS_VERIFIED; return; } message("aliased to %s", shortenstring(p, MAXSHORTSTR)); if (LogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "alias %.100s => %s", a->q_paddr, shortenstring(p, MAXSHORTSTR)); a->q_flags &= ~QSELFREF; if (tTd(27, 5)) { sm_dprintf("alias: QS_EXPANDED "); printaddr(sm_debug_file(), a, false); } a->q_state = QS_EXPANDED; /* ** Always deliver aliased items as the default user. ** Setting q_gid to 0 forces deliver() to use DefUser ** instead of the alias name for the call to initgroups(). */ a->q_uid = DefUid; a->q_gid = 0; a->q_fullname = NULL; a->q_flags |= QGOODUID|QALIAS; (void) sendtolist(p, a, sendq, aliaslevel + 1, e); if (bitset(QSELFREF, a->q_flags) && QS_IS_EXPANDED(a->q_state)) a->q_state = QS_OK; /* ** Look for owner of alias */ if (strncmp(a->q_user, "owner-", 6) == 0 || strlen(a->q_user) > sizeof(obuf) - 7) (void) sm_strlcpy(obuf, "owner-owner", sizeof(obuf)); else (void) sm_strlcpyn(obuf, sizeof(obuf), 2, "owner-", a->q_user); owner = aliaslookup(obuf, &status, a->q_host); if (owner == NULL) return; /* reflect owner into envelope sender */ if (strpbrk(owner, ",:/|\"") != NULL) owner = obuf; a->q_owner = sm_rpool_strdup_x(e->e_rpool, owner); /* announce delivery to this alias; NORECEIPT bit set later */ if (e->e_xfp != NULL) (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Message delivered to mailing list %s\n", a->q_paddr); e->e_flags |= EF_SENDRECEIPT; a->q_flags |= QDELIVERED|QEXPANDED; } /* ** ALIASLOOKUP -- look up a name in the alias file. ** ** Parameters: ** name -- the name to look up. ** pstat -- a pointer to a place to put the status. ** av -- argument for %1 expansion. ** ** Returns: ** the value of name. ** NULL if unknown. ** ** Side Effects: ** none. ** ** Warnings: ** The return value will be trashed across calls. */ static char * aliaslookup(name, pstat, av) char *name; int *pstat; char *av; { static MAP *map = NULL; #if _FFR_ALIAS_DETAIL int i; char *argv[4]; #endif /* _FFR_ALIAS_DETAIL */ if (map == NULL) { STAB *s = stab("aliases", ST_MAP, ST_FIND); if (s == NULL) return NULL; map = &s->s_map; } DYNOPENMAP(map); /* special case POstMastER -- always use lower case */ if (sm_strcasecmp(name, "postmaster") == 0) name = "postmaster"; #if _FFR_ALIAS_DETAIL i = 0; argv[i++] = name; argv[i++] = av; /* XXX '+' is hardwired here as delimiter! */ if (av != NULL && *av == '+') argv[i++] = av + 1; argv[i++] = NULL; return (*map->map_class->map_lookup)(map, name, argv, pstat); #else /* _FFR_ALIAS_DETAIL */ return (*map->map_class->map_lookup)(map, name, NULL, pstat); #endif /* _FFR_ALIAS_DETAIL */ } /* ** SETALIAS -- set up an alias map ** ** Called when reading configuration file. ** ** Parameters: ** spec -- the alias specification ** ** Returns: ** none. */ void setalias(spec) char *spec; { register char *p; register MAP *map; char *class; STAB *s; if (tTd(27, 8)) sm_dprintf("setalias(%s)\n", spec); for (p = spec; p != NULL; ) { char buf[50]; while (isascii(*p) && isspace(*p)) p++; if (*p == '\0') break; spec = p; if (NAliasFileMaps >= MAXMAPSTACK) { syserr("Too many alias databases defined, %d max", MAXMAPSTACK); return; } if (AliasFileMap == NULL) { (void) sm_strlcpy(buf, "aliases.files sequence", sizeof(buf)); AliasFileMap = makemapentry(buf); if (AliasFileMap == NULL) { syserr("setalias: cannot create aliases.files map"); return; } } (void) sm_snprintf(buf, sizeof(buf), "Alias%d", NAliasFileMaps); s = stab(buf, ST_MAP, ST_ENTER); map = &s->s_map; memset(map, '\0', sizeof(*map)); map->map_mname = s->s_name; p = strpbrk(p, ALIAS_SPEC_SEPARATORS); if (p != NULL && *p == SEPARATOR) { /* map name */ *p++ = '\0'; class = spec; spec = p; } else { class = "implicit"; map->map_mflags = MF_INCLNULL; } /* find end of spec */ if (p != NULL) { bool quoted = false; for (; *p != '\0'; p++) { /* ** Don't break into a quoted string. ** Needed for ldap maps which use ** commas in their specifications. */ if (*p == '"') quoted = !quoted; else if (*p == ',' && !quoted) break; } /* No more alias specifications follow */ if (*p == '\0') p = NULL; } if (p != NULL) *p++ = '\0'; if (tTd(27, 20)) sm_dprintf(" map %s:%s %s\n", class, s->s_name, spec); /* look up class */ s = stab(class, ST_MAPCLASS, ST_FIND); if (s == NULL) { syserr("setalias: unknown alias class %s", class); } else if (!bitset(MCF_ALIASOK, s->s_mapclass.map_cflags)) { syserr("setalias: map class %s can't handle aliases", class); } else { map->map_class = &s->s_mapclass; map->map_mflags |= MF_ALIAS; if (map->map_class->map_parse(map, spec)) { map->map_mflags |= MF_VALID; AliasFileMap->map_stack[NAliasFileMaps++] = map; } } } } /* ** ALIASWAIT -- wait for distinguished @:@ token to appear. ** ** This can decide to reopen or rebuild the alias file ** ** Parameters: ** map -- a pointer to the map descriptor for this alias file. ** ext -- the filename extension (e.g., ".db") for the ** database file. ** isopen -- if set, the database is already open, and we ** should check for validity; otherwise, we are ** just checking to see if it should be created. ** ** Returns: ** true -- if the database is open when we return. ** false -- if the database is closed when we return. */ bool aliaswait(map, ext, isopen) MAP *map; char *ext; bool isopen; { bool attimeout = false; time_t mtime; struct stat stb; char buf[MAXPATHLEN]; if (tTd(27, 3)) sm_dprintf("aliaswait(%s:%s)\n", map->map_class->map_cname, map->map_file); if (bitset(MF_ALIASWAIT, map->map_mflags)) return isopen; map->map_mflags |= MF_ALIASWAIT; if (SafeAlias > 0) { auto int st; unsigned int sleeptime = 2; unsigned int loopcount = 0; /* only used for debugging */ time_t toolong = curtime() + SafeAlias; while (isopen && map->map_class->map_lookup(map, "@", NULL, &st) == NULL) { if (curtime() > toolong) { /* we timed out */ attimeout = true; break; } /* ** Close and re-open the alias database in case ** the one is mv'ed instead of cp'ed in. */ if (tTd(27, 2)) { loopcount++; sm_dprintf("aliaswait: sleeping for %u seconds (loopcount = %u)\n", sleeptime, loopcount); } map->map_mflags |= MF_CLOSING; map->map_class->map_close(map); map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING); (void) sleep(sleeptime); sleeptime *= 2; if (sleeptime > 60) sleeptime = 60; isopen = map->map_class->map_open(map, O_RDONLY); } } /* see if we need to go into auto-rebuild mode */ if (!bitset(MCF_REBUILDABLE, map->map_class->map_cflags)) { if (tTd(27, 3)) sm_dprintf("aliaswait: not rebuildable\n"); map->map_mflags &= ~MF_ALIASWAIT; return isopen; } if (stat(map->map_file, &stb) < 0) { if (tTd(27, 3)) sm_dprintf("aliaswait: no source file\n"); map->map_mflags &= ~MF_ALIASWAIT; return isopen; } mtime = stb.st_mtime; if (sm_strlcpyn(buf, sizeof(buf), 2, map->map_file, ext == NULL ? "" : ext) >= sizeof(buf)) { if (LogLevel > 3) sm_syslog(LOG_INFO, NOQID, "alias database %s%s name too long", map->map_file, ext == NULL ? "" : ext); message("alias database %s%s name too long", map->map_file, ext == NULL ? "" : ext); } if (stat(buf, &stb) < 0 || stb.st_mtime < mtime || attimeout) { if (LogLevel > 3) sm_syslog(LOG_INFO, NOQID, "alias database %s out of date", buf); message("Warning: alias database %s out of date", buf); } map->map_mflags &= ~MF_ALIASWAIT; return isopen; } /* ** REBUILDALIASES -- rebuild the alias database. ** ** Parameters: ** map -- the database to rebuild. ** automatic -- set if this was automatically generated. ** ** Returns: ** true if successful; false otherwise. ** ** Side Effects: ** Reads the text version of the database, builds the ** DBM or DB version. */ bool rebuildaliases(map, automatic) register MAP *map; bool automatic; { SM_FILE_T *af; bool nolock = false; bool success = false; long sff = SFF_OPENASROOT|SFF_REGONLY|SFF_NOLOCK; sigfunc_t oldsigint, oldsigquit; #ifdef SIGTSTP sigfunc_t oldsigtstp; #endif /* SIGTSTP */ if (!bitset(MCF_REBUILDABLE, map->map_class->map_cflags)) return false; if (!bitnset(DBS_LINKEDALIASFILEINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; if (!bitnset(DBS_GROUPWRITABLEALIASFILE, DontBlameSendmail)) sff |= SFF_NOGWFILES; if (!bitnset(DBS_WORLDWRITABLEALIASFILE, DontBlameSendmail)) sff |= SFF_NOWWFILES; /* try to lock the source file */ if ((af = safefopen(map->map_file, O_RDWR, 0, sff)) == NULL) { struct stat stb; if ((errno != EACCES && errno != EROFS) || automatic || (af = safefopen(map->map_file, O_RDONLY, 0, sff)) == NULL) { int saveerr = errno; if (tTd(27, 1)) sm_dprintf("Can't open %s: %s\n", map->map_file, sm_errstring(saveerr)); if (!automatic && !bitset(MF_OPTIONAL, map->map_mflags)) message("newaliases: cannot open %s: %s", map->map_file, sm_errstring(saveerr)); errno = 0; return false; } nolock = true; if (tTd(27, 1) || fstat(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), &stb) < 0 || bitset(S_IWUSR|S_IWGRP|S_IWOTH, stb.st_mode)) message("warning: cannot lock %s: %s", map->map_file, sm_errstring(errno)); } /* see if someone else is rebuilding the alias file */ if (!nolock && !lockfile(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), map->map_file, NULL, LOCK_EX|LOCK_NB)) { /* yes, they are -- wait until done */ message("Alias file %s is locked (maybe being rebuilt)", map->map_file); if (OpMode != MD_INITALIAS) { /* wait for other rebuild to complete */ (void) lockfile(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), map->map_file, NULL, LOCK_EX); } (void) sm_io_close(af, SM_TIME_DEFAULT); errno = 0; return false; } oldsigint = sm_signal(SIGINT, SIG_IGN); oldsigquit = sm_signal(SIGQUIT, SIG_IGN); #ifdef SIGTSTP oldsigtstp = sm_signal(SIGTSTP, SIG_IGN); #endif /* SIGTSTP */ if (map->map_class->map_open(map, O_RDWR)) { if (LogLevel > 7) { sm_syslog(LOG_NOTICE, NOQID, "alias database %s %srebuilt by %s", map->map_file, automatic ? "auto" : "", username()); } map->map_mflags |= MF_OPEN|MF_WRITABLE; map->map_pid = CurrentPid; readaliases(map, af, !automatic, true); success = true; } else { if (tTd(27, 1)) sm_dprintf("Can't create database for %s: %s\n", map->map_file, sm_errstring(errno)); if (!automatic) syserr("Cannot create database for alias file %s", map->map_file); } /* close the file, thus releasing locks */ (void) sm_io_close(af, SM_TIME_DEFAULT); /* add distinguished entries and close the database */ if (bitset(MF_OPEN, map->map_mflags)) { map->map_mflags |= MF_CLOSING; map->map_class->map_close(map); map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING); } /* restore the old signals */ (void) sm_signal(SIGINT, oldsigint); (void) sm_signal(SIGQUIT, oldsigquit); #ifdef SIGTSTP (void) sm_signal(SIGTSTP, oldsigtstp); #endif /* SIGTSTP */ return success; } /* ** READALIASES -- read and process the alias file. ** ** This routine implements the part of initaliases that occurs ** when we are not going to use the DBM stuff. ** ** Parameters: ** map -- the alias database descriptor. ** af -- file to read the aliases from. ** announcestats -- announce statistics regarding number of ** aliases, longest alias, etc. ** logstats -- lot the same info. ** ** Returns: ** none. ** ** Side Effects: ** Reads aliasfile into the symbol table. ** Optionally, builds the .dir & .pag files. */ void readaliases(map, af, announcestats, logstats) register MAP *map; SM_FILE_T *af; bool announcestats; bool logstats; { register char *p; char *rhs; bool skipping; long naliases, bytes, longest; ADDRESS al, bl; char line[BUFSIZ]; /* ** Read and interpret lines */ FileName = map->map_file; LineNumber = 0; naliases = bytes = longest = 0; skipping = false; - while (sm_io_fgets(af, SM_TIME_DEFAULT, line, sizeof(line)) != NULL) + while (sm_io_fgets(af, SM_TIME_DEFAULT, line, sizeof(line)) >= 0) { int lhssize, rhssize; int c; LineNumber++; p = strchr(line, '\n'); /* XXX what if line="a\\" ? */ while (p != NULL && p > line && p[-1] == '\\') { p--; if (sm_io_fgets(af, SM_TIME_DEFAULT, p, - SPACELEFT(line, p)) == NULL) + SPACELEFT(line, p)) < 0) break; LineNumber++; p = strchr(p, '\n'); } if (p != NULL) *p = '\0'; else if (!sm_io_eof(af)) { errno = 0; syserr("554 5.3.0 alias line too long"); /* flush to end of line */ while ((c = sm_io_getc(af, SM_TIME_DEFAULT)) != SM_IO_EOF && c != '\n') continue; /* skip any continuation lines */ skipping = true; continue; } switch (line[0]) { case '#': case '\0': skipping = false; continue; case ' ': case '\t': if (!skipping) syserr("554 5.3.5 Non-continuation line starts with space"); skipping = true; continue; } skipping = false; /* ** Process the LHS ** Find the colon separator, and parse the address. ** It should resolve to a local name -- this will ** be checked later (we want to optionally do ** parsing of the RHS first to maximize error ** detection). */ for (p = line; *p != '\0' && *p != ':' && *p != '\n'; p++) continue; if (*p++ != ':') { syserr("554 5.3.5 missing colon"); continue; } if (parseaddr(line, &al, RF_COPYALL, ':', NULL, CurEnv, true) == NULL) { syserr("554 5.3.5 %.40s... illegal alias name", line); continue; } /* ** Process the RHS. ** 'al' is the internal form of the LHS address. ** 'p' points to the text of the RHS. */ while (isascii(*p) && isspace(*p)) p++; rhs = p; for (;;) { register char *nlp; nlp = &p[strlen(p)]; if (nlp > p && nlp[-1] == '\n') *--nlp = '\0'; if (CheckAliases) { /* do parsing & compression of addresses */ while (*p != '\0') { auto char *delimptr; while ((isascii(*p) && isspace(*p)) || *p == ',') p++; if (*p == '\0') break; if (parseaddr(p, &bl, RF_COPYNONE, ',', &delimptr, CurEnv, true) == NULL) usrerr("553 5.3.5 %s... bad address", p); p = delimptr; } } else { p = nlp; } /* see if there should be a continuation line */ c = sm_io_getc(af, SM_TIME_DEFAULT); if (!sm_io_eof(af)) (void) sm_io_ungetc(af, SM_TIME_DEFAULT, c); if (c != ' ' && c != '\t') break; /* read continuation line */ if (sm_io_fgets(af, SM_TIME_DEFAULT, p, - sizeof(line) - (p-line)) == NULL) + sizeof(line) - (p-line)) < 0) break; LineNumber++; /* check for line overflow */ if (strchr(p, '\n') == NULL && !sm_io_eof(af)) { usrerr("554 5.3.5 alias too long"); while ((c = sm_io_getc(af, SM_TIME_DEFAULT)) != SM_IO_EOF && c != '\n') continue; skipping = true; break; } } if (skipping) continue; if (!bitnset(M_ALIASABLE, al.q_mailer->m_flags)) { syserr("554 5.3.5 %s... cannot alias non-local names", al.q_paddr); continue; } /* ** Insert alias into symbol table or database file. ** ** Special case pOStmaStER -- always make it lower case. */ if (sm_strcasecmp(al.q_user, "postmaster") == 0) makelower(al.q_user); lhssize = strlen(al.q_user); rhssize = strlen(rhs); if (rhssize > 0) { /* is RHS empty (just spaces)? */ p = rhs; while (isascii(*p) && isspace(*p)) p++; } if (rhssize == 0 || *p == '\0') { syserr("554 5.3.5 %.40s... missing value for alias", line); } else { map->map_class->map_store(map, al.q_user, rhs); /* statistics */ naliases++; bytes += lhssize + rhssize; if (rhssize > longest) longest = rhssize; } #if 0 /* ** address strings are now stored in the envelope rpool, ** and therefore cannot be freed. */ if (al.q_paddr != NULL) sm_free(al.q_paddr); /* disabled */ if (al.q_host != NULL) sm_free(al.q_host); /* disabled */ if (al.q_user != NULL) sm_free(al.q_user); /* disabled */ #endif /* 0 */ } CurEnv->e_to = NULL; FileName = NULL; if (Verbose || announcestats) message("%s: %ld aliases, longest %ld bytes, %ld bytes total", map->map_file, naliases, longest, bytes); if (LogLevel > 7 && logstats) sm_syslog(LOG_INFO, NOQID, "%s: %ld aliases, longest %ld bytes, %ld bytes total", map->map_file, naliases, longest, bytes); } /* ** FORWARD -- Try to forward mail ** ** This is similar but not identical to aliasing. ** ** Parameters: ** user -- the name of the user who's mail we would like ** to forward to. It must have been verified -- ** i.e., the q_home field must have been filled ** in. ** sendq -- a pointer to the head of the send queue to ** put this user's aliases in. ** aliaslevel -- the current alias nesting depth. ** e -- the current envelope. ** ** Returns: ** none. ** ** Side Effects: ** New names are added to send queues. */ void forward(user, sendq, aliaslevel, e) ADDRESS *user; ADDRESS **sendq; int aliaslevel; register ENVELOPE *e; { char *pp; char *ep; bool got_transient; if (tTd(27, 1)) sm_dprintf("forward(%s)\n", user->q_paddr); if (!bitnset(M_HASPWENT, user->q_mailer->m_flags) || !QS_IS_OK(user->q_state)) return; if (ForwardPath != NULL && *ForwardPath == '\0') return; if (user->q_home == NULL) { syserr("554 5.3.0 forward: no home"); user->q_home = "/no/such/directory"; } /* good address -- look for .forward file in home */ macdefine(&e->e_macro, A_PERM, 'z', user->q_home); macdefine(&e->e_macro, A_PERM, 'u', user->q_user); macdefine(&e->e_macro, A_PERM, 'h', user->q_host); if (ForwardPath == NULL) ForwardPath = newstr("\201z/.forward"); got_transient = false; for (pp = ForwardPath; pp != NULL; pp = ep) { int err; char buf[MAXPATHLEN]; struct stat st; ep = strchr(pp, SEPARATOR); if (ep != NULL) *ep = '\0'; expand(pp, buf, sizeof(buf), e); if (ep != NULL) *ep++ = SEPARATOR; if (buf[0] == '\0') continue; if (tTd(27, 3)) sm_dprintf("forward: trying %s\n", buf); err = include(buf, true, user, sendq, aliaslevel, e); if (err == 0) break; else if (transienterror(err)) { /* we may have to suspend this message */ got_transient = true; if (tTd(27, 2)) sm_dprintf("forward: transient error on %s\n", buf); if (LogLevel > 2) { char *curhost = CurHostName; CurHostName = NULL; sm_syslog(LOG_ERR, e->e_id, "forward %s: transient error: %s", buf, sm_errstring(err)); CurHostName = curhost; } } else { switch (err) { case ENOENT: break; case E_SM_WWDIR: case E_SM_GWDIR: /* check if it even exists */ if (stat(buf, &st) < 0 && errno == ENOENT) { if (bitnset(DBS_DONTWARNFORWARDFILEINUNSAFEDIRPATH, DontBlameSendmail)) break; } /* FALLTHROUGH */ #if _FFR_FORWARD_SYSERR case E_SM_NOSLINK: case E_SM_NOHLINK: case E_SM_REGONLY: case E_SM_ISEXEC: case E_SM_WWFILE: case E_SM_GWFILE: syserr("forward: %s: %s", buf, sm_errstring(err)); break; #endif /* _FFR_FORWARD_SYSERR */ default: if (LogLevel > (RunAsUid == 0 ? 2 : 10)) sm_syslog(LOG_WARNING, e->e_id, "forward %s: %s", buf, sm_errstring(err)); if (Verbose) message("forward: %s: %s", buf, sm_errstring(err)); break; } } } if (pp == NULL && got_transient) { /* ** There was no successful .forward open and at least one ** transient open. We have to defer this address for ** further delivery. */ message("transient .forward open error: message queued"); user->q_state = QS_QUEUEUP; return; } } Index: head/contrib/sendmail/src/collect.c =================================================================== --- head/contrib/sendmail/src/collect.c (revision 249728) +++ head/contrib/sendmail/src/collect.c (revision 249729) @@ -1,1106 +1,1124 @@ /* * Copyright (c) 1998-2006, 2008 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: collect.c,v 8.285 2012/06/14 23:54:02 ca Exp $") +SM_RCSID("@(#)$Id: collect.c,v 8.286 2013/03/15 17:54:12 ca Exp $") static void eatfrom __P((char *volatile, ENVELOPE *)); static void collect_doheader __P((ENVELOPE *)); static SM_FILE_T *collect_dfopen __P((ENVELOPE *)); static SM_FILE_T *collect_eoh __P((ENVELOPE *, int, int)); /* ** COLLECT_EOH -- end-of-header processing in collect() ** ** Called by collect() when it encounters the blank line ** separating the header from the message body, or when it ** encounters EOF in a message that contains only a header. ** ** Parameters: ** e -- envelope ** numhdrs -- number of headers ** hdrslen -- length of headers ** ** Results: ** NULL, or handle to open data file ** ** Side Effects: ** end-of-header check ruleset is invoked. ** envelope state is updated. ** headers may be added and deleted. ** selects the queue. ** opens the data file. */ static SM_FILE_T * collect_eoh(e, numhdrs, hdrslen) ENVELOPE *e; int numhdrs; int hdrslen; { char hnum[16]; char hsize[16]; /* call the end-of-header check ruleset */ (void) sm_snprintf(hnum, sizeof(hnum), "%d", numhdrs); (void) sm_snprintf(hsize, sizeof(hsize), "%d", hdrslen); if (tTd(30, 10)) sm_dprintf("collect: rscheck(\"check_eoh\", \"%s $| %s\")\n", hnum, hsize); (void) rscheck("check_eoh", hnum, hsize, e, RSF_UNSTRUCTURED|RSF_COUNT, 3, NULL, e->e_id, NULL); /* ** Process the header, ** select the queue, open the data file. */ collect_doheader(e); return collect_dfopen(e); } /* ** COLLECT_DOHEADER -- process header in collect() ** ** Called by collect() after it has finished parsing the header, ** but before it selects the queue and creates the data file. ** The results of processing the header will affect queue selection. ** ** Parameters: ** e -- envelope ** ** Results: ** none. ** ** Side Effects: ** envelope state is updated. ** headers may be added and deleted. */ static void collect_doheader(e) ENVELOPE *e; { /* ** Find out some information from the headers. ** Examples are who is the from person & the date. */ eatheader(e, true, false); if (GrabTo && e->e_sendqueue == NULL) usrerr("No recipient addresses found in header"); /* ** If we have a Return-Receipt-To:, turn it into a DSN. */ if (RrtImpliesDsn && hvalue("return-receipt-to", e->e_header) != NULL) { ADDRESS *q; for (q = e->e_sendqueue; q != NULL; q = q->q_next) if (!bitset(QHASNOTIFY, q->q_flags)) q->q_flags |= QHASNOTIFY|QPINGONSUCCESS; } /* ** Add an appropriate recipient line if we have none. */ if (hvalue("to", e->e_header) != NULL || hvalue("cc", e->e_header) != NULL || hvalue("apparently-to", e->e_header) != NULL) { /* have a valid recipient header -- delete Bcc: headers */ e->e_flags |= EF_DELETE_BCC; } else if (hvalue("bcc", e->e_header) == NULL) { /* no valid recipient headers */ register ADDRESS *q; char *hdr = NULL; /* create a recipient field */ switch (NoRecipientAction) { case NRA_ADD_APPARENTLY_TO: hdr = "Apparently-To"; break; case NRA_ADD_TO: hdr = "To"; break; case NRA_ADD_BCC: addheader("Bcc", " ", 0, e, true); break; case NRA_ADD_TO_UNDISCLOSED: addheader("To", "undisclosed-recipients:;", 0, e, true); break; } if (hdr != NULL) { for (q = e->e_sendqueue; q != NULL; q = q->q_next) { if (q->q_alias != NULL) continue; if (tTd(30, 3)) sm_dprintf("Adding %s: %s\n", hdr, q->q_paddr); addheader(hdr, q->q_paddr, 0, e, true); } } } } /* ** COLLECT_DFOPEN -- open the message data file ** ** Called by collect() after it has finished processing the header. ** Queue selection occurs at this point, possibly based on the ** envelope's recipient list and on header information. ** ** Parameters: ** e -- envelope ** ** Results: ** NULL, or a pointer to an open data file, ** into which the message body will be written by collect(). ** ** Side Effects: ** Calls syserr, sets EF_FATALERRS and returns NULL ** if there is insufficient disk space. ** Aborts process if data file could not be opened. ** Otherwise, the queue is selected, ** e->e_{dfino,dfdev,msgsize,flags} are updated, ** and a pointer to an open data file is returned. */ static SM_FILE_T * collect_dfopen(e) ENVELOPE *e; { MODE_T oldumask = 0; int dfd; struct stat stbuf; SM_FILE_T *df; char *dfname; if (!setnewqueue(e)) return NULL; dfname = queuename(e, DATAFL_LETTER); if (bitset(S_IWGRP, QueueFileMode)) oldumask = umask(002); df = bfopen(dfname, QueueFileMode, DataFileBufferSize, SFF_OPENASROOT); if (bitset(S_IWGRP, QueueFileMode)) (void) umask(oldumask); if (df == NULL) { syserr("@Cannot create %s", dfname); e->e_flags |= EF_NO_BODY_RETN; flush_errors(true); finis(false, true, ExitStat); /* NOTREACHED */ } dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL); if (dfd < 0 || fstat(dfd, &stbuf) < 0) e->e_dfino = -1; else { e->e_dfdev = stbuf.st_dev; e->e_dfino = stbuf.st_ino; } e->e_flags |= EF_HAS_DF; return df; } /* ** COLLECT -- read & parse message header & make temp file. ** ** Creates a temporary file name and copies the standard ** input to that file. Leading UNIX-style "From" lines are ** stripped off (after important information is extracted). ** ** Parameters: ** fp -- file to read. ** smtpmode -- if set, we are running SMTP: give an RFC821 ** style message to say we are ready to collect ** input, and never ignore a single dot to mean ** end of message. ** hdrp -- the location to stash the header. ** e -- the current envelope. ** rsetsize -- reset e_msgsize? ** ** Returns: ** none. ** ** Side Effects: ** If successful, ** - Data file is created and filled, and e->e_dfp is set. ** - The from person may be set. ** If the "enough disk space" check fails, ** - syserr is called. ** - e->e_dfp is NULL. ** - e->e_flags & EF_FATALERRS is set. ** - collect() returns. ** If data file cannot be created, the process is terminated. */ /* values for input state machine */ #define IS_NORM 0 /* middle of line */ #define IS_BOL 1 /* beginning of line */ #define IS_DOT 2 /* read a dot at beginning of line */ #define IS_DOTCR 3 /* read ".\r" at beginning of line */ #define IS_CR 4 /* read a carriage return */ /* values for message state machine */ #define MS_UFROM 0 /* reading Unix from line */ #define MS_HEADER 1 /* reading message header */ #define MS_BODY 2 /* reading message body */ #define MS_DISCARD 3 /* discarding rest of message */ void collect(fp, smtpmode, hdrp, e, rsetsize) SM_FILE_T *fp; bool smtpmode; HDR **hdrp; register ENVELOPE *e; bool rsetsize; { register SM_FILE_T *df; bool ignrdot; int dbto; register char *bp; int c; bool inputerr; bool headeronly; char *buf; int buflen; int istate; int mstate; int hdrslen; int numhdrs; int afd; unsigned char *pbp; unsigned char peekbuf[8]; char bufbuf[MAXLINE]; +#if _FFR_REJECT_NUL_BYTE + bool hasNUL; /* has at least one NUL input byte */ +#endif /* _FFR_REJECT_NUL_BYTE */ df = NULL; ignrdot = smtpmode ? false : IgnrDot; /* timeout for I/O functions is in milliseconds */ dbto = smtpmode ? ((int) TimeOuts.to_datablock * 1000) : SM_TIME_FOREVER; sm_io_setinfo(fp, SM_IO_WHAT_TIMEOUT, &dbto); set_tls_rd_tmo(TimeOuts.to_datablock); c = SM_IO_EOF; inputerr = false; headeronly = hdrp != NULL; hdrslen = 0; numhdrs = 0; HasEightBits = false; +#if _FFR_REJECT_NUL_BYTE + hasNUL = false; +#endif /* _FFR_REJECT_NUL_BYTE */ buf = bp = bufbuf; buflen = sizeof(bufbuf); pbp = peekbuf; istate = IS_BOL; mstate = SaveFrom ? MS_HEADER : MS_UFROM; /* ** Tell ARPANET to go ahead. */ if (smtpmode) message("354 Enter mail, end with \".\" on a line by itself"); /* simulate an I/O timeout when used as sink */ if (tTd(83, 101)) sleep(319); if (tTd(30, 2)) sm_dprintf("collect\n"); /* ** Read the message. ** ** This is done using two interleaved state machines. ** The input state machine is looking for things like ** hidden dots; the message state machine is handling ** the larger picture (e.g., header versus body). */ if (rsetsize) e->e_msgsize = 0; for (;;) { if (tTd(30, 35)) sm_dprintf("top, istate=%d, mstate=%d\n", istate, mstate); for (;;) { if (pbp > peekbuf) c = *--pbp; else { while (!sm_io_eof(fp) && !sm_io_error(fp)) { errno = 0; c = sm_io_getc(fp, SM_TIME_DEFAULT); if (c == SM_IO_EOF && errno == EINTR) { /* Interrupted, retry */ sm_io_clearerr(fp); continue; } /* timeout? */ if (c == SM_IO_EOF && errno == EAGAIN && smtpmode) { /* ** Override e_message in ** usrerr() as this is the ** reason for failure that ** should be logged for ** undelivered recipients. */ e->e_message = NULL; errno = 0; inputerr = true; goto readabort; } break; } if (TrafficLogFile != NULL && !headeronly) { if (istate == IS_BOL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d <<< ", (int) CurrentPid); if (c == SM_IO_EOF) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "[EOF]\n"); else (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, c); } +#if _FFR_REJECT_NUL_BYTE + if (c == '\0') + hasNUL = true; +#endif /* _FFR_REJECT_NUL_BYTE */ if (c == SM_IO_EOF) goto readerr; if (SevenBitInput) c &= 0x7f; else HasEightBits |= bitset(0x80, c); } if (tTd(30, 94)) sm_dprintf("istate=%d, c=%c (0x%x)\n", istate, (char) c, c); switch (istate) { case IS_BOL: if (c == '.') { istate = IS_DOT; continue; } break; case IS_DOT: if (c == '\n' && !ignrdot && !bitset(EF_NL_NOT_EOL, e->e_flags)) goto readerr; else if (c == '\r' && !bitset(EF_CRLF_NOT_EOL, e->e_flags)) { istate = IS_DOTCR; continue; } else if (ignrdot || (c != '.' && OpMode != MD_SMTP && OpMode != MD_DAEMON && OpMode != MD_ARPAFTP)) { SM_ASSERT(pbp < peekbuf + sizeof(peekbuf)); *pbp++ = c; c = '.'; } break; case IS_DOTCR: if (c == '\n' && !ignrdot) goto readerr; else { /* push back the ".\rx" */ SM_ASSERT(pbp < peekbuf + sizeof(peekbuf)); *pbp++ = c; if (OpMode != MD_SMTP && OpMode != MD_DAEMON && OpMode != MD_ARPAFTP) { SM_ASSERT(pbp < peekbuf + sizeof(peekbuf)); *pbp++ = '\r'; c = '.'; } else c = '\r'; } break; case IS_CR: if (c == '\n') istate = IS_BOL; else { (void) sm_io_ungetc(fp, SM_TIME_DEFAULT, c); c = '\r'; istate = IS_NORM; } goto bufferchar; } if (c == '\r' && !bitset(EF_CRLF_NOT_EOL, e->e_flags)) { istate = IS_CR; continue; } else if (c == '\n' && !bitset(EF_NL_NOT_EOL, e->e_flags)) istate = IS_BOL; else istate = IS_NORM; bufferchar: if (!headeronly) { /* no overflow? */ if (e->e_msgsize >= 0) { e->e_msgsize++; if (MaxMessageSize > 0 && !bitset(EF_TOOBIG, e->e_flags) && e->e_msgsize > MaxMessageSize) e->e_flags |= EF_TOOBIG; } } switch (mstate) { case MS_BODY: /* just put the character out */ if (!bitset(EF_TOOBIG, e->e_flags)) (void) sm_io_putc(df, SM_TIME_DEFAULT, c); /* FALLTHROUGH */ case MS_DISCARD: continue; } SM_ASSERT(mstate == MS_UFROM || mstate == MS_HEADER); /* header -- buffer up */ if (bp >= &buf[buflen - 2]) { char *obuf; /* out of space for header */ obuf = buf; if (buflen < MEMCHUNKSIZE) buflen *= 2; else buflen += MEMCHUNKSIZE; if (buflen <= 0) { sm_syslog(LOG_NOTICE, e->e_id, "header overflow from %s during message collect", CURHOSTNAME); errno = 0; e->e_flags |= EF_CLRQUEUE; e->e_status = "5.6.0"; usrerrenh(e->e_status, "552 Headers too large"); goto discard; } buf = xalloc(buflen); memmove(buf, obuf, bp - obuf); bp = &buf[bp - obuf]; if (obuf != bufbuf) sm_free(obuf); /* XXX */ } if (c != '\0') { *bp++ = c; ++hdrslen; if (!headeronly && MaxHeadersLength > 0 && hdrslen > MaxHeadersLength) { sm_syslog(LOG_NOTICE, e->e_id, "headers too large (%d max) from %s during message collect", MaxHeadersLength, CURHOSTNAME); errno = 0; e->e_flags |= EF_CLRQUEUE; e->e_status = "5.6.0"; usrerrenh(e->e_status, "552 Headers too large (%d max)", MaxHeadersLength); discard: mstate = MS_DISCARD; } } if (istate == IS_BOL) break; } *bp = '\0'; nextstate: if (tTd(30, 35)) sm_dprintf("nextstate, istate=%d, mstate=%d, line=\"%s\"\n", istate, mstate, buf); switch (mstate) { case MS_UFROM: mstate = MS_HEADER; #ifndef NOTUNIX if (strncmp(buf, "From ", 5) == 0) { bp = buf; eatfrom(buf, e); continue; } #endif /* ! NOTUNIX */ /* FALLTHROUGH */ case MS_HEADER: if (!isheader(buf)) { mstate = MS_BODY; goto nextstate; } /* check for possible continuation line */ do { sm_io_clearerr(fp); errno = 0; c = sm_io_getc(fp, SM_TIME_DEFAULT); /* timeout? */ if (c == SM_IO_EOF && errno == EAGAIN && smtpmode) { /* ** Override e_message in ** usrerr() as this is the ** reason for failure that ** should be logged for ** undelivered recipients. */ e->e_message = NULL; errno = 0; inputerr = true; goto readabort; } } while (c == SM_IO_EOF && errno == EINTR); if (c != SM_IO_EOF) (void) sm_io_ungetc(fp, SM_TIME_DEFAULT, c); if (c == ' ' || c == '\t') { /* yep -- defer this */ continue; } SM_ASSERT(bp > buf); /* guaranteed by isheader(buf) */ SM_ASSERT(*(bp - 1) != '\n' || bp > buf + 1); /* trim off trailing CRLF or NL */ if (*--bp != '\n' || *--bp != '\r') bp++; *bp = '\0'; if (bitset(H_EOH, chompheader(buf, CHHDR_CHECK | CHHDR_USER, hdrp, e))) { mstate = MS_BODY; goto nextstate; } numhdrs++; break; case MS_BODY: if (tTd(30, 1)) sm_dprintf("EOH\n"); if (headeronly) goto readerr; df = collect_eoh(e, numhdrs, hdrslen); if (df == NULL) e->e_flags |= EF_TOOBIG; bp = buf; /* toss blank line */ if ((!bitset(EF_CRLF_NOT_EOL, e->e_flags) && bp[0] == '\r' && bp[1] == '\n') || (!bitset(EF_NL_NOT_EOL, e->e_flags) && bp[0] == '\n')) { break; } /* if not a blank separator, write it out */ if (!bitset(EF_TOOBIG, e->e_flags)) { while (*bp != '\0') (void) sm_io_putc(df, SM_TIME_DEFAULT, *bp++); } break; } bp = buf; } readerr: if ((sm_io_eof(fp) && smtpmode) || sm_io_error(fp)) { const char *errmsg; if (sm_io_eof(fp)) errmsg = "unexpected close"; else errmsg = sm_errstring(errno); if (tTd(30, 1)) sm_dprintf("collect: premature EOM: %s\n", errmsg); if (LogLevel > 1) sm_syslog(LOG_WARNING, e->e_id, "collect: premature EOM: %s", errmsg); inputerr = true; } if (headeronly) return; if (mstate != MS_BODY) { /* no body or discard, so we never opened the data file */ SM_ASSERT(df == NULL); df = collect_eoh(e, numhdrs, hdrslen); } if (df == NULL) { /* skip next few clauses */ /* EMPTY */ } else if (sm_io_flush(df, SM_TIME_DEFAULT) != 0 || sm_io_error(df)) { dferror(df, "sm_io_flush||sm_io_error", e); flush_errors(true); finis(true, true, ExitStat); /* NOTREACHED */ } else if (SuperSafe == SAFE_NO || SuperSafe == SAFE_INTERACTIVE || (SuperSafe == SAFE_REALLY_POSTMILTER && smtpmode)) { /* skip next few clauses */ /* EMPTY */ /* Note: updfs() is not called in this case! */ } else if (sm_io_setinfo(df, SM_BF_COMMIT, NULL) < 0 && errno != EINVAL) { int save_errno = errno; if (save_errno == EEXIST) { char *dfile; struct stat st; int dfd; dfile = queuename(e, DATAFL_LETTER); if (stat(dfile, &st) < 0) st.st_size = -1; errno = EEXIST; syserr("@collect: bfcommit(%s): already on disk, size=%ld", dfile, (long) st.st_size); dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL); if (dfd >= 0) dumpfd(dfd, true, true); } errno = save_errno; dferror(df, "bfcommit", e); flush_errors(true); finis(save_errno != EEXIST, true, ExitStat); } else if ((afd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL)) < 0) { dferror(df, "sm_io_getinfo", e); flush_errors(true); finis(true, true, ExitStat); /* NOTREACHED */ } else if (fsync(afd) < 0) { dferror(df, "fsync", e); flush_errors(true); finis(true, true, ExitStat); /* NOTREACHED */ } else if (sm_io_close(df, SM_TIME_DEFAULT) < 0) { dferror(df, "sm_io_close", e); flush_errors(true); finis(true, true, ExitStat); /* NOTREACHED */ } else { /* everything is happily flushed to disk */ df = NULL; /* remove from available space in filesystem */ updfs(e, 0, 1, "collect"); } /* An EOF when running SMTP is an error */ readabort: if (inputerr && (OpMode == MD_SMTP || OpMode == MD_DAEMON)) { char *host; char *problem; ADDRESS *q; host = RealHostName; if (host == NULL) host = "localhost"; if (sm_io_eof(fp)) problem = "unexpected close"; else if (sm_io_error(fp)) problem = "I/O error"; else problem = "read timeout"; if (LogLevel > 0 && sm_io_eof(fp)) sm_syslog(LOG_NOTICE, e->e_id, "collect: %s on connection from %.100s, sender=%s", problem, host, shortenstring(e->e_from.q_paddr, MAXSHORTSTR)); if (sm_io_eof(fp)) usrerr("421 4.4.1 collect: %s on connection from %s, from=%s", problem, host, shortenstring(e->e_from.q_paddr, MAXSHORTSTR)); else syserr("421 4.4.1 collect: %s on connection from %s, from=%s", problem, host, shortenstring(e->e_from.q_paddr, MAXSHORTSTR)); flush_errors(true); /* don't return an error indication */ e->e_to = NULL; e->e_flags &= ~EF_FATALERRS; e->e_flags |= EF_CLRQUEUE; /* Don't send any message notification to sender */ for (q = e->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_DEAD(q->q_state)) continue; q->q_state = QS_FATALERR; } (void) sm_io_close(df, SM_TIME_DEFAULT); df = NULL; finis(true, true, ExitStat); /* NOTREACHED */ } /* Log collection information. */ if (tTd(92, 2)) sm_dprintf("collect: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n", e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel); if (bitset(EF_LOGSENDER, e->e_flags) && LogLevel > 4) { logsender(e, e->e_msgid); e->e_flags &= ~EF_LOGSENDER; } /* check for message too large */ if (bitset(EF_TOOBIG, e->e_flags)) { e->e_flags |= EF_NO_BODY_RETN|EF_CLRQUEUE; if (!bitset(EF_FATALERRS, e->e_flags)) { e->e_status = "5.2.3"; usrerrenh(e->e_status, "552 Message exceeds maximum fixed size (%ld)", MaxMessageSize); if (LogLevel > 6) sm_syslog(LOG_NOTICE, e->e_id, "message size (%ld) exceeds maximum (%ld)", PRT_NONNEGL(e->e_msgsize), MaxMessageSize); } } /* check for illegal 8-bit data */ if (HasEightBits) { e->e_flags |= EF_HAS8BIT; if (!bitset(MM_PASS8BIT|MM_MIME8BIT, MimeMode) && !bitset(EF_IS_MIME, e->e_flags)) { e->e_status = "5.6.1"; usrerrenh(e->e_status, "554 Eight bit data not allowed"); } } else { /* if it claimed to be 8 bits, well, it lied.... */ if (e->e_bodytype != NULL && sm_strcasecmp(e->e_bodytype, "8BITMIME") == 0) e->e_bodytype = "7BIT"; } + +#if _FFR_REJECT_NUL_BYTE + if (hasNUL && RejectNUL) + { + e->e_status = "5.6.1"; + usrerrenh(e->e_status, "554 NUL byte not allowed"); + } +#endif /* _FFR_REJECT_NUL_BYTE */ if (SuperSafe == SAFE_REALLY && !bitset(EF_FATALERRS, e->e_flags)) { char *dfname = queuename(e, DATAFL_LETTER); if ((e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname, SM_IO_RDONLY_B, NULL)) == NULL) { /* we haven't acked receipt yet, so just chuck this */ syserr("@Cannot reopen %s", dfname); finis(true, true, ExitStat); /* NOTREACHED */ } } else e->e_dfp = df; /* collect statistics */ if (OpMode != MD_VERIFY) { /* ** Recalculate e_msgpriority, it is done at in eatheader() ** which is called (in 8.12) after the header is collected, ** hence e_msgsize is (most likely) incorrect. */ e->e_msgpriority = e->e_msgsize - e->e_class * WkClassFact + e->e_nrcpts * WkRecipFact; markstats(e, (ADDRESS *) NULL, STATS_NORMAL); } } /* ** DFERROR -- signal error on writing the data file. ** ** Called by collect(). Collect() always terminates the process ** immediately after calling dferror(), which means that the SMTP ** session will be terminated, which means that any error message ** issued by dferror must be a 421 error, as per RFC 821. ** ** Parameters: ** df -- the file pointer for the data file. ** msg -- detailed message. ** e -- the current envelope. ** ** Returns: ** none. ** ** Side Effects: ** Gives an error message. ** Arranges for following output to go elsewhere. */ void dferror(df, msg, e) SM_FILE_T *volatile df; char *msg; register ENVELOPE *e; { char *dfname; dfname = queuename(e, DATAFL_LETTER); setstat(EX_IOERR); if (errno == ENOSPC) { #if STAT64 > 0 struct stat64 st; #else /* STAT64 > 0 */ struct stat st; #endif /* STAT64 > 0 */ long avail; long bsize; e->e_flags |= EF_NO_BODY_RETN; if ( #if STAT64 > 0 fstat64(sm_io_getinfo(df, SM_IO_WHAT_FD, NULL), &st) #else /* STAT64 > 0 */ fstat(sm_io_getinfo(df, SM_IO_WHAT_FD, NULL), &st) #endif /* STAT64 > 0 */ < 0) st.st_size = 0; (void) sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, dfname, SM_IO_WRONLY_B, NULL, df); if (st.st_size <= 0) (void) sm_io_fprintf(df, SM_TIME_DEFAULT, "\n*** Mail could not be accepted"); else (void) sm_io_fprintf(df, SM_TIME_DEFAULT, "\n*** Mail of at least %llu bytes could not be accepted\n", (ULONGLONG_T) st.st_size); (void) sm_io_fprintf(df, SM_TIME_DEFAULT, "*** at %s due to lack of disk space for temp file.\n", MyHostName); avail = freediskspace(qid_printqueue(e->e_qgrp, e->e_qdir), &bsize); if (avail > 0) { if (bsize > 1024) avail *= bsize / 1024; else if (bsize < 1024) avail /= 1024 / bsize; (void) sm_io_fprintf(df, SM_TIME_DEFAULT, "*** Currently, %ld kilobytes are available for mail temp files.\n", avail); } #if 0 /* Wrong response code; should be 421. */ e->e_status = "4.3.1"; usrerrenh(e->e_status, "452 Out of disk space for temp file"); #else /* 0 */ syserr("421 4.3.1 Out of disk space for temp file"); #endif /* 0 */ } else syserr("421 4.3.0 collect: Cannot write %s (%s, uid=%d, gid=%d)", dfname, msg, (int) geteuid(), (int) getegid()); if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL, SM_IO_WRONLY, NULL, df) == NULL) sm_syslog(LOG_ERR, e->e_id, "dferror: sm_io_reopen(\"/dev/null\") failed: %s", sm_errstring(errno)); } /* ** EATFROM -- chew up a UNIX style from line and process ** ** This does indeed make some assumptions about the format ** of UNIX messages. ** ** Parameters: ** fm -- the from line. ** e -- envelope ** ** Returns: ** none. ** ** Side Effects: ** extracts what information it can from the header, ** such as the date. */ #ifndef NOTUNIX static char *DowList[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL }; static char *MonthList[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL }; static void eatfrom(fm, e) char *volatile fm; register ENVELOPE *e; { register char *p; register char **dt; if (tTd(30, 2)) sm_dprintf("eatfrom(%s)\n", fm); /* find the date part */ p = fm; while (*p != '\0') { /* skip a word */ while (*p != '\0' && *p != ' ') p++; while (*p == ' ') p++; if (strlen(p) < 17) { /* no room for the date */ return; } if (!(isascii(*p) && isupper(*p)) || p[3] != ' ' || p[13] != ':' || p[16] != ':') continue; /* we have a possible date */ for (dt = DowList; *dt != NULL; dt++) if (strncmp(*dt, p, 3) == 0) break; if (*dt == NULL) continue; for (dt = MonthList; *dt != NULL; dt++) { if (strncmp(*dt, &p[4], 3) == 0) break; } if (*dt != NULL) break; } if (*p != '\0') { char *q, buf[25]; /* we have found a date */ (void) sm_strlcpy(buf, p, sizeof(buf)); q = arpadate(buf); macdefine(&e->e_macro, A_TEMP, 'a', q); } } #endif /* ! NOTUNIX */ Index: head/contrib/sendmail/src/conf.c =================================================================== --- head/contrib/sendmail/src/conf.c (revision 249728) +++ head/contrib/sendmail/src/conf.c (revision 249729) @@ -1,6464 +1,6494 @@ /* - * Copyright (c) 1998-2012 Sendmail, Inc. and its suppliers. + * Copyright (c) 1998-2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: conf.c,v 8.1176 2012/12/07 03:59:54 ca Exp $") +SM_RCSID("@(#)$Id: conf.c,v 8.1182 2013/04/05 17:39:09 ca Exp $") #include #include #if NEWDB # include "sm/bdb.h" #endif /* NEWDB */ #include #include "map.h" #ifdef DEC # if NETINET6 /* for the IPv6 device lookup */ # define _SOCKADDR_LEN # include # endif /* NETINET6 */ #endif /* DEC */ # include # include #include #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ #if HASULIMIT && defined(HPUX11) # include #endif /* HASULIMIT && defined(HPUX11) */ static void setupmaps __P((void)); static void setupmailers __P((void)); static void setupqueues __P((void)); static int get_num_procs_online __P((void)); static int add_hostnames __P((SOCKADDR *)); #if NETINET6 && NEEDSGETIPNODE static struct hostent *sm_getipnodebyname __P((const char *, int, int, int *)); static struct hostent *sm_getipnodebyaddr __P((const void *, size_t, int, int *)); #else /* NETINET6 && NEEDSGETIPNODE */ #define sm_getipnodebyname getipnodebyname #define sm_getipnodebyaddr getipnodebyaddr #endif /* NETINET6 && NEEDSGETIPNODE */ /* ** CONF.C -- Sendmail Configuration Tables. ** ** Defines the configuration of this installation. ** ** Configuration Variables: ** HdrInfo -- a table describing well-known header fields. ** Each entry has the field name and some flags, ** which are described in sendmail.h. ** ** Notes: ** I have tried to put almost all the reasonable ** configuration information into the configuration ** file read at runtime. My intent is that anything ** here is a function of the version of UNIX you ** are running, or is really static -- for example ** the headers are a superset of widely used ** protocols. If you find yourself playing with ** this file too much, you may be making a mistake! */ /* ** Header info table ** Final (null) entry contains the flags used for any other field. ** ** Not all of these are actually handled specially by sendmail ** at this time. They are included as placeholders, to let ** you know that "someday" I intend to have sendmail do ** something with them. */ struct hdrinfo HdrInfo[] = { /* originator fields, most to least significant */ { "resent-sender", H_FROM|H_RESENT, NULL }, { "resent-from", H_FROM|H_RESENT, NULL }, { "resent-reply-to", H_FROM|H_RESENT, NULL }, { "sender", H_FROM, NULL }, { "from", H_FROM, NULL }, { "reply-to", H_FROM, NULL }, { "errors-to", H_FROM|H_ERRORSTO, NULL }, { "full-name", H_ACHECK, NULL }, { "return-receipt-to", H_RECEIPTTO, NULL }, { "delivery-receipt-to", H_RECEIPTTO, NULL }, { "disposition-notification-to", H_FROM, NULL }, /* destination fields */ { "to", H_RCPT, NULL }, { "resent-to", H_RCPT|H_RESENT, NULL }, { "cc", H_RCPT, NULL }, { "resent-cc", H_RCPT|H_RESENT, NULL }, { "bcc", H_RCPT|H_BCC, NULL }, { "resent-bcc", H_RCPT|H_BCC|H_RESENT, NULL }, { "apparently-to", H_RCPT, NULL }, /* message identification and control */ { "message-id", 0, NULL }, { "resent-message-id", H_RESENT, NULL }, { "message", H_EOH, NULL }, { "text", H_EOH, NULL }, /* date fields */ { "date", 0, NULL }, { "resent-date", H_RESENT, NULL }, /* trace fields */ { "received", H_TRACE|H_FORCE, NULL }, { "x400-received", H_TRACE|H_FORCE, NULL }, { "via", H_TRACE|H_FORCE, NULL }, { "mail-from", H_TRACE|H_FORCE, NULL }, /* miscellaneous fields */ { "comments", H_FORCE|H_ENCODABLE, NULL }, { "return-path", H_FORCE|H_ACHECK|H_BINDLATE, NULL }, { "content-transfer-encoding", H_CTE, NULL }, { "content-type", H_CTYPE, NULL }, { "content-length", H_ACHECK, NULL }, { "subject", H_ENCODABLE, NULL }, { "x-authentication-warning", H_FORCE, NULL }, { NULL, 0, NULL } }; /* ** Privacy values */ struct prival PrivacyValues[] = { { "public", PRIV_PUBLIC }, { "needmailhelo", PRIV_NEEDMAILHELO }, { "needexpnhelo", PRIV_NEEDEXPNHELO }, { "needvrfyhelo", PRIV_NEEDVRFYHELO }, { "noexpn", PRIV_NOEXPN }, { "novrfy", PRIV_NOVRFY }, { "restrictexpand", PRIV_RESTRICTEXPAND }, { "restrictmailq", PRIV_RESTRICTMAILQ }, { "restrictqrun", PRIV_RESTRICTQRUN }, { "noetrn", PRIV_NOETRN }, { "noverb", PRIV_NOVERB }, { "authwarnings", PRIV_AUTHWARNINGS }, { "noreceipts", PRIV_NORECEIPTS }, { "nobodyreturn", PRIV_NOBODYRETN }, { "goaway", PRIV_GOAWAY }, { "noactualrecipient", PRIV_NOACTUALRECIPIENT }, { NULL, 0 } }; /* ** DontBlameSendmail values */ struct dbsval DontBlameSendmailValues[] = { { "safe", DBS_SAFE }, { "assumesafechown", DBS_ASSUMESAFECHOWN }, { "groupwritabledirpathsafe", DBS_GROUPWRITABLEDIRPATHSAFE }, { "groupwritableforwardfilesafe", DBS_GROUPWRITABLEFORWARDFILESAFE }, { "groupwritableincludefilesafe", DBS_GROUPWRITABLEINCLUDEFILESAFE }, { "groupwritablealiasfile", DBS_GROUPWRITABLEALIASFILE }, { "worldwritablealiasfile", DBS_WORLDWRITABLEALIASFILE }, { "forwardfileinunsafedirpath", DBS_FORWARDFILEINUNSAFEDIRPATH }, { "includefileinunsafedirpath", DBS_INCLUDEFILEINUNSAFEDIRPATH }, { "mapinunsafedirpath", DBS_MAPINUNSAFEDIRPATH }, { "linkedaliasfileinwritabledir", DBS_LINKEDALIASFILEINWRITABLEDIR }, { "linkedclassfileinwritabledir", DBS_LINKEDCLASSFILEINWRITABLEDIR }, { "linkedforwardfileinwritabledir", DBS_LINKEDFORWARDFILEINWRITABLEDIR }, { "linkedincludefileinwritabledir", DBS_LINKEDINCLUDEFILEINWRITABLEDIR }, { "linkedmapinwritabledir", DBS_LINKEDMAPINWRITABLEDIR }, { "linkedserviceswitchfileinwritabledir", DBS_LINKEDSERVICESWITCHFILEINWRITABLEDIR }, { "filedeliverytohardlink", DBS_FILEDELIVERYTOHARDLINK }, { "filedeliverytosymlink", DBS_FILEDELIVERYTOSYMLINK }, { "writemaptohardlink", DBS_WRITEMAPTOHARDLINK }, { "writemaptosymlink", DBS_WRITEMAPTOSYMLINK }, { "writestatstohardlink", DBS_WRITESTATSTOHARDLINK }, { "writestatstosymlink", DBS_WRITESTATSTOSYMLINK }, { "forwardfileingroupwritabledirpath", DBS_FORWARDFILEINGROUPWRITABLEDIRPATH }, { "includefileingroupwritabledirpath", DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH }, { "classfileinunsafedirpath", DBS_CLASSFILEINUNSAFEDIRPATH }, { "errorheaderinunsafedirpath", DBS_ERRORHEADERINUNSAFEDIRPATH }, { "helpfileinunsafedirpath", DBS_HELPFILEINUNSAFEDIRPATH }, { "forwardfileinunsafedirpathsafe", DBS_FORWARDFILEINUNSAFEDIRPATHSAFE }, { "includefileinunsafedirpathsafe", DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE }, { "runprograminunsafedirpath", DBS_RUNPROGRAMINUNSAFEDIRPATH }, { "runwritableprogram", DBS_RUNWRITABLEPROGRAM }, { "nonrootsafeaddr", DBS_NONROOTSAFEADDR }, { "truststickybit", DBS_TRUSTSTICKYBIT }, { "dontwarnforwardfileinunsafedirpath", DBS_DONTWARNFORWARDFILEINUNSAFEDIRPATH }, { "insufficiententropy", DBS_INSUFFICIENTENTROPY }, { "groupreadablesasldbfile", DBS_GROUPREADABLESASLDBFILE }, { "groupwritablesasldbfile", DBS_GROUPWRITABLESASLDBFILE }, { "groupwritableforwardfile", DBS_GROUPWRITABLEFORWARDFILE }, { "groupwritableincludefile", DBS_GROUPWRITABLEINCLUDEFILE }, { "worldwritableforwardfile", DBS_WORLDWRITABLEFORWARDFILE }, { "worldwritableincludefile", DBS_WORLDWRITABLEINCLUDEFILE }, { "groupreadablekeyfile", DBS_GROUPREADABLEKEYFILE }, #if _FFR_GROUPREADABLEAUTHINFOFILE { "groupreadableadefaultauthinfofile", DBS_GROUPREADABLEAUTHINFOFILE }, #endif /* _FFR_GROUPREADABLEAUTHINFOFILE */ { NULL, 0 } }; /* ** Miscellaneous stuff. */ int DtableSize = 50; /* max open files; reset in 4.2bsd */ /* ** SETDEFAULTS -- set default values ** ** Some of these must be initialized using direct code since they ** depend on run-time values. So let's do all of them this way. ** ** Parameters: ** e -- the default envelope. ** ** Returns: ** none. ** ** Side Effects: ** Initializes a bunch of global variables to their ** default values. */ #define MINUTES * 60 #define HOURS * 60 MINUTES #define DAYS * 24 HOURS #ifndef MAXRULERECURSION # define MAXRULERECURSION 50 /* max ruleset recursion depth */ #endif /* ! MAXRULERECURSION */ void setdefaults(e) register ENVELOPE *e; { int i; int numprocs; struct passwd *pw; numprocs = get_num_procs_online(); SpaceSub = ' '; /* option B */ QueueLA = 8 * numprocs; /* option x */ RefuseLA = 12 * numprocs; /* option X */ WkRecipFact = 30000L; /* option y */ WkClassFact = 1800L; /* option z */ WkTimeFact = 90000L; /* option Z */ QueueFactor = WkRecipFact * 20; /* option q */ QueueMode = QM_NORMAL; /* what queue items to act upon */ FileMode = (RealUid != geteuid()) ? 0644 : 0600; /* option F */ QueueFileMode = (RealUid != geteuid()) ? 0644 : 0600; /* option QueueFileMode */ if (((pw = sm_getpwnam("mailnull")) != NULL && pw->pw_uid != 0) || ((pw = sm_getpwnam("sendmail")) != NULL && pw->pw_uid != 0) || ((pw = sm_getpwnam("daemon")) != NULL && pw->pw_uid != 0)) { DefUid = pw->pw_uid; /* option u */ DefGid = pw->pw_gid; /* option g */ DefUser = newstr(pw->pw_name); } else { DefUid = 1; /* option u */ DefGid = 1; /* option g */ setdefuser(); } TrustedUid = 0; if (tTd(37, 4)) sm_dprintf("setdefaults: DefUser=%s, DefUid=%d, DefGid=%d\n", DefUser != NULL ? DefUser : "<1:1>", (int) DefUid, (int) DefGid); CheckpointInterval = 10; /* option C */ MaxHopCount = 25; /* option h */ set_delivery_mode(SM_FORK, e); /* option d */ e->e_errormode = EM_PRINT; /* option e */ e->e_qgrp = NOQGRP; e->e_qdir = NOQDIR; e->e_xfqgrp = NOQGRP; e->e_xfqdir = NOQDIR; e->e_ctime = curtime(); SevenBitInput = false; /* option 7 */ MaxMciCache = 1; /* option k */ MciCacheTimeout = 5 MINUTES; /* option K */ LogLevel = 9; /* option L */ #if MILTER MilterLogLevel = -1; #endif /* MILTER */ inittimeouts(NULL, false); /* option r */ PrivacyFlags = PRIV_PUBLIC; /* option p */ MeToo = true; /* option m */ SendMIMEErrors = true; /* option f */ SuperSafe = SAFE_REALLY; /* option s */ clrbitmap(DontBlameSendmail); /* DontBlameSendmail option */ #if MIME8TO7 MimeMode = MM_CVTMIME|MM_PASS8BIT; /* option 8 */ #else /* MIME8TO7 */ MimeMode = MM_PASS8BIT; #endif /* MIME8TO7 */ for (i = 0; i < MAXTOCLASS; i++) { TimeOuts.to_q_return[i] = 5 DAYS; /* option T */ TimeOuts.to_q_warning[i] = 0; /* option T */ } ServiceSwitchFile = "/etc/mail/service.switch"; ServiceCacheMaxAge = (time_t) 10; HostsFile = _PATH_HOSTS; PidFile = newstr(_PATH_SENDMAILPID); MustQuoteChars = "@,;:\\()[].'"; MciInfoTimeout = 30 MINUTES; MaxRuleRecursion = MAXRULERECURSION; MaxAliasRecursion = 10; MaxMacroRecursion = 10; ColonOkInAddr = true; DontLockReadFiles = true; DontProbeInterfaces = DPI_PROBEALL; DoubleBounceAddr = "postmaster"; MaxHeadersLength = MAXHDRSLEN; MaxMimeHeaderLength = MAXLINE; MaxMimeFieldLength = MaxMimeHeaderLength / 2; MaxForwardEntries = 0; FastSplit = 1; MaxNOOPCommands = MAXNOOPCOMMANDS; #if SASL AuthMechanisms = newstr(AUTH_MECHANISMS); AuthRealm = NULL; MaxSLBits = INT_MAX; #endif /* SASL */ #if STARTTLS TLS_Srv_Opts = TLS_I_SRV; #endif /* STARTTLS */ #ifdef HESIOD_INIT HesiodContext = NULL; #endif /* HESIOD_INIT */ #if NETINET6 /* Detect if IPv6 is available at run time */ i = socket(AF_INET6, SOCK_STREAM, 0); if (i >= 0) { InetMode = AF_INET6; (void) close(i); } else InetMode = AF_INET; #else /* NETINET6 */ InetMode = AF_INET; #endif /* NETINET6 */ ControlSocketName = NULL; memset(&ConnectOnlyTo, '\0', sizeof(ConnectOnlyTo)); DataFileBufferSize = 4096; XscriptFileBufferSize = 4096; for (i = 0; i < MAXRWSETS; i++) RuleSetNames[i] = NULL; #if MILTER InputFilters[0] = NULL; #endif /* MILTER */ RejectLogInterval = 3 HOURS; #if REQUIRES_DIR_FSYNC RequiresDirfsync = true; #endif /* REQUIRES_DIR_FSYNC */ #if _FFR_RCPTTHROTDELAY BadRcptThrottleDelay = 1; #endif /* _FFR_RCPTTHROTDELAY */ ConnectionRateWindowSize = 60; setupmaps(); setupqueues(); setupmailers(); setupheaders(); } /* ** SETDEFUSER -- set/reset DefUser using DefUid (for initgroups()) */ void setdefuser() { struct passwd *defpwent; static char defuserbuf[40]; DefUser = defuserbuf; defpwent = sm_getpwuid(DefUid); (void) sm_strlcpy(defuserbuf, (defpwent == NULL || defpwent->pw_name == NULL) ? "nobody" : defpwent->pw_name, sizeof(defuserbuf)); if (tTd(37, 4)) sm_dprintf("setdefuser: DefUid=%d, DefUser=%s\n", (int) DefUid, DefUser); } /* ** SETUPQUEUES -- initialize default queues ** ** The mqueue QUEUE structure gets filled in after readcf() but ** we need something to point to now for the mailer setup, ** which use "mqueue" as default queue. */ static void setupqueues() { char buf[100]; MaxRunnersPerQueue = 1; (void) sm_strlcpy(buf, "mqueue, P=/var/spool/mqueue", sizeof(buf)); makequeue(buf, false); } /* ** SETUPMAILERS -- initialize default mailers */ static void setupmailers() { char buf[100]; (void) sm_strlcpy(buf, "prog, P=/bin/sh, F=lsouDq9, T=X-Unix/X-Unix/X-Unix, A=sh -c \201u", sizeof(buf)); makemailer(buf); (void) sm_strlcpy(buf, "*file*, P=[FILE], F=lsDFMPEouq9, T=X-Unix/X-Unix/X-Unix, A=FILE \201u", sizeof(buf)); makemailer(buf); (void) sm_strlcpy(buf, "*include*, P=/dev/null, F=su, A=INCLUDE \201u", sizeof(buf)); makemailer(buf); initerrmailers(); } /* ** SETUPMAPS -- set up map classes */ #define MAPDEF(name, ext, flags, parse, open, close, lookup, store) \ { \ extern bool parse __P((MAP *, char *)); \ extern bool open __P((MAP *, int)); \ extern void close __P((MAP *)); \ extern char *lookup __P((MAP *, char *, char **, int *)); \ extern void store __P((MAP *, char *, char *)); \ s = stab(name, ST_MAPCLASS, ST_ENTER); \ s->s_mapclass.map_cname = name; \ s->s_mapclass.map_ext = ext; \ s->s_mapclass.map_cflags = flags; \ s->s_mapclass.map_parse = parse; \ s->s_mapclass.map_open = open; \ s->s_mapclass.map_close = close; \ s->s_mapclass.map_lookup = lookup; \ s->s_mapclass.map_store = store; \ } static void setupmaps() { register STAB *s; #if NEWDB # if DB_VERSION_MAJOR > 1 int major_v, minor_v, patch_v; (void) db_version(&major_v, &minor_v, &patch_v); if (major_v != DB_VERSION_MAJOR || minor_v != DB_VERSION_MINOR) { errno = 0; syserr("Berkeley DB version mismatch: compiled against %d.%d.%d, run-time linked against %d.%d.%d", DB_VERSION_MAJOR, DB_VERSION_MINOR, DB_VERSION_PATCH, major_v, minor_v, patch_v); } # endif /* DB_VERSION_MAJOR > 1 */ MAPDEF("hash", ".db", MCF_ALIASOK|MCF_REBUILDABLE, map_parseargs, hash_map_open, db_map_close, db_map_lookup, db_map_store); MAPDEF("btree", ".db", MCF_ALIASOK|MCF_REBUILDABLE, map_parseargs, bt_map_open, db_map_close, db_map_lookup, db_map_store); #endif /* NEWDB */ #if NDBM MAPDEF("dbm", ".dir", MCF_ALIASOK|MCF_REBUILDABLE, map_parseargs, ndbm_map_open, ndbm_map_close, ndbm_map_lookup, ndbm_map_store); #endif /* NDBM */ #if NIS MAPDEF("nis", NULL, MCF_ALIASOK, map_parseargs, nis_map_open, null_map_close, nis_map_lookup, null_map_store); #endif /* NIS */ #if NISPLUS MAPDEF("nisplus", NULL, MCF_ALIASOK, map_parseargs, nisplus_map_open, null_map_close, nisplus_map_lookup, null_map_store); #endif /* NISPLUS */ #if LDAPMAP MAPDEF("ldap", NULL, MCF_ALIASOK|MCF_NOTPERSIST, ldapmap_parseargs, ldapmap_open, ldapmap_close, ldapmap_lookup, null_map_store); #endif /* LDAPMAP */ #if PH_MAP MAPDEF("ph", NULL, MCF_NOTPERSIST, ph_map_parseargs, ph_map_open, ph_map_close, ph_map_lookup, null_map_store); #endif /* PH_MAP */ #if MAP_NSD /* IRIX 6.5 nsd support */ MAPDEF("nsd", NULL, MCF_ALIASOK, map_parseargs, null_map_open, null_map_close, nsd_map_lookup, null_map_store); #endif /* MAP_NSD */ #if HESIOD MAPDEF("hesiod", NULL, MCF_ALIASOK|MCF_ALIASONLY, map_parseargs, hes_map_open, hes_map_close, hes_map_lookup, null_map_store); #endif /* HESIOD */ #if NETINFO MAPDEF("netinfo", NULL, MCF_ALIASOK, map_parseargs, ni_map_open, null_map_close, ni_map_lookup, null_map_store); #endif /* NETINFO */ #if 0 MAPDEF("dns", NULL, 0, dns_map_init, null_map_open, null_map_close, dns_map_lookup, null_map_store); #endif /* 0 */ #if NAMED_BIND # if DNSMAP # if _FFR_DNSMAP_ALIASABLE MAPDEF("dns", NULL, MCF_ALIASOK, dns_map_parseargs, dns_map_open, null_map_close, dns_map_lookup, null_map_store); # else /* _FFR_DNSMAP_ALIASABLE */ MAPDEF("dns", NULL, 0, dns_map_parseargs, dns_map_open, null_map_close, dns_map_lookup, null_map_store); # endif /* _FFR_DNSMAP_ALIASABLE */ # endif /* DNSMAP */ #endif /* NAMED_BIND */ #if NAMED_BIND /* best MX DNS lookup */ MAPDEF("bestmx", NULL, MCF_OPTFILE, map_parseargs, null_map_open, null_map_close, bestmx_map_lookup, null_map_store); #endif /* NAMED_BIND */ MAPDEF("host", NULL, 0, host_map_init, null_map_open, null_map_close, host_map_lookup, null_map_store); MAPDEF("text", NULL, MCF_ALIASOK, map_parseargs, text_map_open, null_map_close, text_map_lookup, null_map_store); MAPDEF("stab", NULL, MCF_ALIASOK|MCF_ALIASONLY, map_parseargs, stab_map_open, null_map_close, stab_map_lookup, stab_map_store); MAPDEF("implicit", NULL, MCF_ALIASOK|MCF_ALIASONLY|MCF_REBUILDABLE, map_parseargs, impl_map_open, impl_map_close, impl_map_lookup, impl_map_store); /* access to system passwd file */ MAPDEF("user", NULL, MCF_OPTFILE, map_parseargs, user_map_open, null_map_close, user_map_lookup, null_map_store); /* dequote map */ MAPDEF("dequote", NULL, 0, dequote_init, null_map_open, null_map_close, dequote_map, null_map_store); #if MAP_REGEX MAPDEF("regex", NULL, 0, regex_map_init, null_map_open, null_map_close, regex_map_lookup, null_map_store); #endif /* MAP_REGEX */ #if USERDB /* user database */ MAPDEF("userdb", ".db", 0, map_parseargs, null_map_open, null_map_close, udb_map_lookup, null_map_store); #endif /* USERDB */ /* arbitrary programs */ MAPDEF("program", NULL, MCF_ALIASOK, map_parseargs, null_map_open, null_map_close, prog_map_lookup, null_map_store); /* sequenced maps */ MAPDEF("sequence", NULL, MCF_ALIASOK, seq_map_parse, null_map_open, null_map_close, seq_map_lookup, seq_map_store); /* switched interface to sequenced maps */ MAPDEF("switch", NULL, MCF_ALIASOK, map_parseargs, switch_map_open, null_map_close, seq_map_lookup, seq_map_store); /* null map lookup -- really for internal use only */ MAPDEF("null", NULL, MCF_ALIASOK|MCF_OPTFILE, map_parseargs, null_map_open, null_map_close, null_map_lookup, null_map_store); /* syslog map -- logs information to syslog */ MAPDEF("syslog", NULL, 0, syslog_map_parseargs, null_map_open, null_map_close, syslog_map_lookup, null_map_store); /* macro storage map -- rulesets can set macros */ MAPDEF("macro", NULL, 0, dequote_init, null_map_open, null_map_close, macro_map_lookup, null_map_store); /* arithmetic map -- add/subtract/compare */ MAPDEF("arith", NULL, 0, dequote_init, null_map_open, null_map_close, arith_map_lookup, null_map_store); #if SOCKETMAP /* arbitrary daemons */ MAPDEF("socket", NULL, MCF_ALIASOK, map_parseargs, socket_map_open, socket_map_close, socket_map_lookup, null_map_store); #endif /* SOCKETMAP */ #if _FFR_DPRINTF_MAP /* dprintf map -- logs information to syslog */ MAPDEF("dprintf", NULL, 0, dprintf_map_parseargs, null_map_open, null_map_close, dprintf_map_lookup, null_map_store); #endif /* _FFR_DPRINTF_MAP */ if (tTd(38, 2)) { /* bogus map -- always return tempfail */ MAPDEF("bogus", NULL, MCF_ALIASOK|MCF_OPTFILE, map_parseargs, null_map_open, null_map_close, bogus_map_lookup, null_map_store); } } #undef MAPDEF /* ** INITHOSTMAPS -- initial host-dependent maps ** ** This should act as an interface to any local service switch ** provided by the host operating system. ** ** Parameters: ** none ** ** Returns: ** none ** ** Side Effects: ** Should define maps "host" and "users" as necessary ** for this OS. If they are not defined, they will get ** a default value later. It should check to make sure ** they are not defined first, since it's possible that ** the config file has provided an override. */ void inithostmaps() { register int i; int nmaps; char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; char buf[MAXLINE]; /* ** Make sure we have a host map. */ if (stab("host", ST_MAP, ST_FIND) == NULL) { /* user didn't initialize: set up host map */ (void) sm_strlcpy(buf, "host host", sizeof(buf)); #if NAMED_BIND if (ConfigLevel >= 2) (void) sm_strlcat(buf, " -a. -D", sizeof(buf)); #endif /* NAMED_BIND */ (void) makemapentry(buf); } /* ** Set up default aliases maps */ nmaps = switch_map_find("aliases", maptype, mapreturn); for (i = 0; i < nmaps; i++) { if (strcmp(maptype[i], "files") == 0 && stab("aliases.files", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.files null", sizeof(buf)); (void) makemapentry(buf); } #if NISPLUS else if (strcmp(maptype[i], "nisplus") == 0 && stab("aliases.nisplus", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.nisplus nisplus -kalias -vexpansion mail_aliases.org_dir", sizeof(buf)); (void) makemapentry(buf); } #endif /* NISPLUS */ #if NIS else if (strcmp(maptype[i], "nis") == 0 && stab("aliases.nis", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.nis nis mail.aliases", sizeof(buf)); (void) makemapentry(buf); } #endif /* NIS */ #if NETINFO else if (strcmp(maptype[i], "netinfo") == 0 && stab("aliases.netinfo", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.netinfo netinfo -z, /aliases", sizeof(buf)); (void) makemapentry(buf); } #endif /* NETINFO */ #if HESIOD else if (strcmp(maptype[i], "hesiod") == 0 && stab("aliases.hesiod", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.hesiod hesiod aliases", sizeof(buf)); (void) makemapentry(buf); } #endif /* HESIOD */ #if LDAPMAP && defined(SUN_EXTENSIONS) && \ defined(SUN_SIMPLIFIED_LDAP) && HASLDAPGETALIASBYNAME else if (strcmp(maptype[i], "ldap") == 0 && stab("aliases.ldap", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.ldap ldap -b . -h localhost -k mail=%0 -v mailgroup", sizeof buf); (void) makemapentry(buf); } #endif /* LDAPMAP && defined(SUN_EXTENSIONS) && ... */ } if (stab("aliases", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases switch aliases", sizeof(buf)); (void) makemapentry(buf); } } /* ** SWITCH_MAP_FIND -- find the list of types associated with a map ** ** This is the system-dependent interface to the service switch. ** ** Parameters: ** service -- the name of the service of interest. ** maptype -- an out-array of strings containing the types ** of access to use for this service. There can ** be at most MAXMAPSTACK types for a single service. ** mapreturn -- an out-array of return information bitmaps ** for the map. ** ** Returns: ** The number of map types filled in, or -1 for failure. ** ** Side effects: ** Preserves errno so nothing in the routine clobbers it. */ #if defined(SOLARIS) || (defined(sony_news) && defined(__svr4)) # define _USE_SUN_NSSWITCH_ #endif /* defined(SOLARIS) || (defined(sony_news) && defined(__svr4)) */ #if _FFR_HPUX_NSSWITCH # ifdef __hpux # define _USE_SUN_NSSWITCH_ # endif /* __hpux */ #endif /* _FFR_HPUX_NSSWITCH */ #ifdef _USE_SUN_NSSWITCH_ # include #endif /* _USE_SUN_NSSWITCH_ */ #if defined(ultrix) || (defined(__osf__) && defined(__alpha)) # define _USE_DEC_SVC_CONF_ #endif /* defined(ultrix) || (defined(__osf__) && defined(__alpha)) */ #ifdef _USE_DEC_SVC_CONF_ # include #endif /* _USE_DEC_SVC_CONF_ */ int switch_map_find(service, maptype, mapreturn) char *service; char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; { int svcno = 0; int save_errno = errno; #ifdef _USE_SUN_NSSWITCH_ struct __nsw_switchconfig *nsw_conf; enum __nsw_parse_err pserr; struct __nsw_lookup *lk; static struct __nsw_lookup lkp0 = { "files", {1, 0, 0, 0}, NULL, NULL }; static struct __nsw_switchconfig lkp_default = { 0, "sendmail", 3, &lkp0 }; for (svcno = 0; svcno < MAXMAPACTIONS; svcno++) mapreturn[svcno] = 0; if ((nsw_conf = __nsw_getconfig(service, &pserr)) == NULL) lk = lkp_default.lookups; else lk = nsw_conf->lookups; svcno = 0; while (lk != NULL && svcno < MAXMAPSTACK) { maptype[svcno] = lk->service_name; if (lk->actions[__NSW_NOTFOUND] == __NSW_RETURN) mapreturn[MA_NOTFOUND] |= 1 << svcno; if (lk->actions[__NSW_TRYAGAIN] == __NSW_RETURN) mapreturn[MA_TRYAGAIN] |= 1 << svcno; if (lk->actions[__NSW_UNAVAIL] == __NSW_RETURN) mapreturn[MA_TRYAGAIN] |= 1 << svcno; svcno++; lk = lk->next; } errno = save_errno; return svcno; #endif /* _USE_SUN_NSSWITCH_ */ #ifdef _USE_DEC_SVC_CONF_ struct svcinfo *svcinfo; int svc; for (svcno = 0; svcno < MAXMAPACTIONS; svcno++) mapreturn[svcno] = 0; svcinfo = getsvc(); if (svcinfo == NULL) goto punt; if (strcmp(service, "hosts") == 0) svc = SVC_HOSTS; else if (strcmp(service, "aliases") == 0) svc = SVC_ALIASES; else if (strcmp(service, "passwd") == 0) svc = SVC_PASSWD; else { errno = save_errno; return -1; } for (svcno = 0; svcno < SVC_PATHSIZE && svcno < MAXMAPSTACK; svcno++) { switch (svcinfo->svcpath[svc][svcno]) { case SVC_LOCAL: maptype[svcno] = "files"; break; case SVC_YP: maptype[svcno] = "nis"; break; case SVC_BIND: maptype[svcno] = "dns"; break; # ifdef SVC_HESIOD case SVC_HESIOD: maptype[svcno] = "hesiod"; break; # endif /* SVC_HESIOD */ case SVC_LAST: errno = save_errno; return svcno; } } errno = save_errno; return svcno; #endif /* _USE_DEC_SVC_CONF_ */ #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) /* ** Fall-back mechanism. */ STAB *st; static time_t servicecachetime; /* time service switch was cached */ time_t now = curtime(); for (svcno = 0; svcno < MAXMAPACTIONS; svcno++) mapreturn[svcno] = 0; if ((now - servicecachetime) > (time_t) ServiceCacheMaxAge) { /* (re)read service switch */ register SM_FILE_T *fp; long sff = SFF_REGONLY|SFF_OPENASROOT|SFF_NOLOCK; if (!bitnset(DBS_LINKEDSERVICESWITCHFILEINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; if (ConfigFileRead) servicecachetime = now; fp = safefopen(ServiceSwitchFile, O_RDONLY, 0, sff); if (fp != NULL) { char buf[MAXLINE]; while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, - sizeof(buf)) != NULL) + sizeof(buf)) >= 0) { register char *p; p = strpbrk(buf, "#\n"); if (p != NULL) *p = '\0'; #ifndef SM_NSSWITCH_DELIMS # define SM_NSSWITCH_DELIMS " \t" #endif /* SM_NSSWITCH_DELIMS */ p = strpbrk(buf, SM_NSSWITCH_DELIMS); if (p != NULL) *p++ = '\0'; if (buf[0] == '\0') continue; if (p == NULL) { sm_syslog(LOG_ERR, NOQID, "Bad line on %.100s: %.100s", ServiceSwitchFile, buf); continue; } while (isascii(*p) && isspace(*p)) p++; if (*p == '\0') continue; /* ** Find/allocate space for this service entry. ** Space for all of the service strings ** are allocated at once. This means ** that we only have to free the first ** one to free all of them. */ st = stab(buf, ST_SERVICE, ST_ENTER); if (st->s_service[0] != NULL) sm_free((void *) st->s_service[0]); /* XXX */ p = newstr(p); for (svcno = 0; svcno < MAXMAPSTACK; ) { if (*p == '\0') break; st->s_service[svcno++] = p; p = strpbrk(p, " \t"); if (p == NULL) break; *p++ = '\0'; while (isascii(*p) && isspace(*p)) p++; } if (svcno < MAXMAPSTACK) st->s_service[svcno] = NULL; } (void) sm_io_close(fp, SM_TIME_DEFAULT); } } /* look up entry in cache */ st = stab(service, ST_SERVICE, ST_FIND); if (st != NULL && st->s_service[0] != NULL) { /* extract data */ svcno = 0; while (svcno < MAXMAPSTACK) { maptype[svcno] = st->s_service[svcno]; if (maptype[svcno++] == NULL) break; } errno = save_errno; return --svcno; } #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */ #if !defined(_USE_SUN_NSSWITCH_) /* if the service file doesn't work, use an absolute fallback */ # ifdef _USE_DEC_SVC_CONF_ punt: # endif /* _USE_DEC_SVC_CONF_ */ for (svcno = 0; svcno < MAXMAPACTIONS; svcno++) mapreturn[svcno] = 0; svcno = 0; if (strcmp(service, "aliases") == 0) { maptype[svcno++] = "files"; # if defined(AUTO_NETINFO_ALIASES) && defined (NETINFO) maptype[svcno++] = "netinfo"; # endif /* defined(AUTO_NETINFO_ALIASES) && defined (NETINFO) */ # ifdef AUTO_NIS_ALIASES # if NISPLUS maptype[svcno++] = "nisplus"; # endif /* NISPLUS */ # if NIS maptype[svcno++] = "nis"; # endif /* NIS */ # endif /* AUTO_NIS_ALIASES */ errno = save_errno; return svcno; } if (strcmp(service, "hosts") == 0) { # if NAMED_BIND maptype[svcno++] = "dns"; # else /* NAMED_BIND */ # if defined(sun) && !defined(BSD) /* SunOS */ maptype[svcno++] = "nis"; # endif /* defined(sun) && !defined(BSD) */ # endif /* NAMED_BIND */ # if defined(AUTO_NETINFO_HOSTS) && defined (NETINFO) maptype[svcno++] = "netinfo"; # endif /* defined(AUTO_NETINFO_HOSTS) && defined (NETINFO) */ maptype[svcno++] = "files"; errno = save_errno; return svcno; } errno = save_errno; return -1; #endif /* !defined(_USE_SUN_NSSWITCH_) */ } /* ** USERNAME -- return the user id of the logged in user. ** ** Parameters: ** none. ** ** Returns: ** The login name of the logged in user. ** ** Side Effects: ** none. ** ** Notes: ** The return value is statically allocated. */ char * username() { static char *myname = NULL; extern char *getlogin(); register struct passwd *pw; /* cache the result */ if (myname == NULL) { myname = getlogin(); if (myname == NULL || myname[0] == '\0') { pw = sm_getpwuid(RealUid); if (pw != NULL) myname = pw->pw_name; } else { uid_t uid = RealUid; if ((pw = sm_getpwnam(myname)) == NULL || (uid != 0 && uid != pw->pw_uid)) { pw = sm_getpwuid(uid); if (pw != NULL) myname = pw->pw_name; } } if (myname == NULL || myname[0] == '\0') { syserr("554 5.3.0 Who are you?"); myname = "postmaster"; } else if (strpbrk(myname, ",;:/|\"\\") != NULL) myname = addquotes(myname, NULL); else myname = sm_pstrdup_x(myname); } return myname; } /* ** TTYPATH -- Get the path of the user's tty ** ** Returns the pathname of the user's tty. Returns NULL if ** the user is not logged in or if s/he has write permission ** denied. ** ** Parameters: ** none ** ** Returns: ** pathname of the user's tty. ** NULL if not logged in or write permission denied. ** ** Side Effects: ** none. ** ** WARNING: ** Return value is in a local buffer. ** ** Called By: ** savemail */ char * ttypath() { struct stat stbuf; register char *pathn; extern char *ttyname(); extern char *getlogin(); /* compute the pathname of the controlling tty */ if ((pathn = ttyname(2)) == NULL && (pathn = ttyname(1)) == NULL && (pathn = ttyname(0)) == NULL) { errno = 0; return NULL; } /* see if we have write permission */ if (stat(pathn, &stbuf) < 0 || !bitset(S_IWOTH, stbuf.st_mode)) { errno = 0; return NULL; } /* see if the user is logged in */ if (getlogin() == NULL) return NULL; /* looks good */ return pathn; } /* ** CHECKCOMPAT -- check for From and To person compatible. ** ** This routine can be supplied on a per-installation basis ** to determine whether a person is allowed to send a message. ** This allows restriction of certain types of internet ** forwarding or registration of users. ** ** If the hosts are found to be incompatible, an error ** message should be given using "usrerr" and an EX_ code ** should be returned. You can also set to->q_status to ** a DSN-style status code. ** ** EF_NO_BODY_RETN can be set in e->e_flags to suppress the ** body during the return-to-sender function; this should be done ** on huge messages. This bit may already be set by the ESMTP ** protocol. ** ** Parameters: ** to -- the person being sent to. ** ** Returns: ** an exit status ** ** Side Effects: ** none (unless you include the usrerr stuff) */ int checkcompat(to, e) register ADDRESS *to; register ENVELOPE *e; { if (tTd(49, 1)) sm_dprintf("checkcompat(to=%s, from=%s)\n", to->q_paddr, e->e_from.q_paddr); #ifdef EXAMPLE_CODE /* this code is intended as an example only */ register STAB *s; s = stab("arpa", ST_MAILER, ST_FIND); if (s != NULL && strcmp(e->e_from.q_mailer->m_name, "local") != 0 && to->q_mailer == s->s_mailer) { usrerr("553 No ARPA mail through this machine: see your system administration"); /* e->e_flags |= EF_NO_BODY_RETN; to suppress body on return */ to->q_status = "5.7.1"; return EX_UNAVAILABLE; } #endif /* EXAMPLE_CODE */ return EX_OK; } #ifdef SUN_EXTENSIONS static void init_md_sun() { struct stat sbuf; /* Check for large file descriptor */ if (fstat(fileno(stdin), &sbuf) < 0) { if (errno == EOVERFLOW) { perror("stdin"); exit(EX_NOINPUT); } } } #endif /* SUN_EXTENSIONS */ /* ** INIT_MD -- do machine dependent initializations ** ** Systems that have global modes that should be set should do ** them here rather than in main. */ #ifdef _AUX_SOURCE # include #endif /* _AUX_SOURCE */ #if SHARE_V1 # include #endif /* SHARE_V1 */ void init_md(argc, argv) int argc; char **argv; { #ifdef _AUX_SOURCE setcompat(getcompat() | COMPAT_BSDPROT); #endif /* _AUX_SOURCE */ #ifdef SUN_EXTENSIONS init_md_sun(); #endif /* SUN_EXTENSIONS */ #if _CONVEX_SOURCE /* keep gethostby*() from stripping the local domain name */ set_domain_trim_off(); #endif /* _CONVEX_SOURCE */ #if defined(__QNX__) && !defined(__QNXNTO__) /* ** Due to QNX's network distributed nature, you can target a tcpip ** stack on a different node in the qnx network; this patch lets ** this feature work. The __sock_locate() must be done before the ** environment is clear. */ __sock_locate(); #endif /* __QNX__ */ #if SECUREWARE || defined(_SCO_unix_) set_auth_parameters(argc, argv); # ifdef _SCO_unix_ /* ** This is required for highest security levels (the kernel ** won't let it call set*uid() or run setuid binaries without ** it). It may be necessary on other SECUREWARE systems. */ if (getluid() == -1) setluid(0); # endif /* _SCO_unix_ */ #endif /* SECUREWARE || defined(_SCO_unix_) */ #ifdef VENDOR_DEFAULT VendorCode = VENDOR_DEFAULT; #else /* VENDOR_DEFAULT */ VendorCode = VENDOR_BERKELEY; #endif /* VENDOR_DEFAULT */ } /* ** INIT_VENDOR_MACROS -- vendor-dependent macro initializations ** ** Called once, on startup. ** ** Parameters: ** e -- the global envelope. ** ** Returns: ** none. ** ** Side Effects: ** vendor-dependent. */ void init_vendor_macros(e) register ENVELOPE *e; { } /* ** GETLA -- get the current load average ** ** This code stolen from la.c. ** ** Parameters: ** none. ** ** Returns: ** The current load average as an integer. ** ** Side Effects: ** none. */ /* try to guess what style of load average we have */ #define LA_ZERO 1 /* always return load average as zero */ #define LA_INT 2 /* read kmem for avenrun; interpret as long */ #define LA_FLOAT 3 /* read kmem for avenrun; interpret as float */ #define LA_SUBR 4 /* call getloadavg */ #define LA_MACH 5 /* MACH load averages (as on NeXT boxes) */ #define LA_SHORT 6 /* read kmem for avenrun; interpret as short */ #define LA_PROCSTR 7 /* read string ("1.17") from /proc/loadavg */ #define LA_READKSYM 8 /* SVR4: use MIOC_READKSYM ioctl call */ #define LA_DGUX 9 /* special DGUX implementation */ #define LA_HPUX 10 /* special HPUX implementation */ #define LA_IRIX6 11 /* special IRIX 6.2 implementation */ #define LA_KSTAT 12 /* special Solaris kstat(3k) implementation */ #define LA_DEVSHORT 13 /* read short from a device */ #define LA_ALPHAOSF 14 /* Digital UNIX (OSF/1 on Alpha) table() call */ #define LA_PSET 15 /* Solaris per-processor-set load average */ #define LA_LONGLONG 17 /* read kmem for avenrun; interpret as long long */ /* do guesses based on general OS type */ #ifndef LA_TYPE # define LA_TYPE LA_ZERO #endif /* ! LA_TYPE */ #ifndef FSHIFT # if defined(unixpc) # define FSHIFT 5 # endif /* defined(unixpc) */ # if defined(__alpha) || defined(IRIX) # define FSHIFT 10 # endif /* defined(__alpha) || defined(IRIX) */ #endif /* ! FSHIFT */ #ifndef FSHIFT # define FSHIFT 8 #endif /* ! FSHIFT */ #ifndef FSCALE # define FSCALE (1 << FSHIFT) #endif /* ! FSCALE */ #ifndef LA_AVENRUN # ifdef SYSTEM5 # define LA_AVENRUN "avenrun" # else /* SYSTEM5 */ # define LA_AVENRUN "_avenrun" # endif /* SYSTEM5 */ #endif /* ! LA_AVENRUN */ /* _PATH_KMEM should be defined in */ #ifndef _PATH_KMEM # define _PATH_KMEM "/dev/kmem" #endif /* ! _PATH_KMEM */ #if (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) # include /* _PATH_UNIX should be defined in */ # ifndef _PATH_UNIX # if defined(SYSTEM5) # define _PATH_UNIX "/unix" # else /* defined(SYSTEM5) */ # define _PATH_UNIX "/vmunix" # endif /* defined(SYSTEM5) */ # endif /* ! _PATH_UNIX */ # ifdef _AUX_SOURCE struct nlist Nl[2]; # else /* _AUX_SOURCE */ struct nlist Nl[] = { { LA_AVENRUN }, { 0 }, }; # endif /* _AUX_SOURCE */ # define X_AVENRUN 0 int getla() { int j; static int kmem = -1; # if LA_TYPE == LA_INT long avenrun[3]; # else /* LA_TYPE == LA_INT */ # if LA_TYPE == LA_SHORT short avenrun[3]; # else # if LA_TYPE == LA_LONGLONG long long avenrun[3]; # else /* LA_TYPE == LA_LONGLONG */ double avenrun[3]; # endif /* LA_TYPE == LA_LONGLONG */ # endif /* LA_TYPE == LA_SHORT */ # endif /* LA_TYPE == LA_INT */ extern off_t lseek(); if (kmem < 0) { # ifdef _AUX_SOURCE (void) sm_strlcpy(Nl[X_AVENRUN].n_name, LA_AVENRUN, sizeof(Nl[X_AVENRUN].n_name)); Nl[1].n_name[0] = '\0'; # endif /* _AUX_SOURCE */ # if defined(_AIX3) || defined(_AIX4) if (knlist(Nl, 1, sizeof(Nl[0])) < 0) # else /* defined(_AIX3) || defined(_AIX4) */ if (nlist(_PATH_UNIX, Nl) < 0) # endif /* defined(_AIX3) || defined(_AIX4) */ { if (tTd(3, 1)) sm_dprintf("getla: nlist(%s): %s\n", _PATH_UNIX, sm_errstring(errno)); return -1; } if (Nl[X_AVENRUN].n_value == 0) { if (tTd(3, 1)) sm_dprintf("getla: nlist(%s, %s) ==> 0\n", _PATH_UNIX, LA_AVENRUN); return -1; } # ifdef NAMELISTMASK Nl[X_AVENRUN].n_value &= NAMELISTMASK; # endif /* NAMELISTMASK */ kmem = open(_PATH_KMEM, 0, 0); if (kmem < 0) { if (tTd(3, 1)) sm_dprintf("getla: open(/dev/kmem): %s\n", sm_errstring(errno)); return -1; } if ((j = fcntl(kmem, F_GETFD, 0)) < 0 || fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0) { if (tTd(3, 1)) sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n", sm_errstring(errno)); (void) close(kmem); kmem = -1; return -1; } } if (tTd(3, 20)) sm_dprintf("getla: symbol address = %#lx\n", (unsigned long) Nl[X_AVENRUN].n_value); if (lseek(kmem, (off_t) Nl[X_AVENRUN].n_value, SEEK_SET) == -1 || read(kmem, (char *) avenrun, sizeof(avenrun)) != sizeof(avenrun)) { /* thank you Ian */ if (tTd(3, 1)) sm_dprintf("getla: lseek or read: %s\n", sm_errstring(errno)); return -1; } # if (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) if (tTd(3, 5)) { # if LA_TYPE == LA_SHORT sm_dprintf("getla: avenrun = %d", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %d, %d", avenrun[1], avenrun[2]); # else /* LA_TYPE == LA_SHORT */ # if LA_TYPE == LA_LONGLONG sm_dprintf("getla: avenrun = %lld", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %lld, %lld", avenrun[1], avenrun[2]); # else /* LA_TYPE == LA_LONGLONG */ sm_dprintf("getla: avenrun = %ld", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %ld, %ld", avenrun[1], avenrun[2]); # endif /* LA_TYPE == LA_LONGLONG */ # endif /* LA_TYPE == LA_SHORT */ sm_dprintf("\n"); } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] + FSCALE/2) >> FSHIFT); return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT); # else /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */ if (tTd(3, 5)) { sm_dprintf("getla: avenrun = %g", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %g, %g", avenrun[1], avenrun[2]); sm_dprintf("\n"); } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5)); return ((int) (avenrun[0] + 0.5)); # endif /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */ } #endif /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */ #if LA_TYPE == LA_READKSYM # include int getla() { int j; static int kmem = -1; long avenrun[3]; struct mioc_rksym mirk; if (kmem < 0) { kmem = open("/dev/kmem", 0, 0); if (kmem < 0) { if (tTd(3, 1)) sm_dprintf("getla: open(/dev/kmem): %s\n", sm_errstring(errno)); return -1; } if ((j = fcntl(kmem, F_GETFD, 0)) < 0 || fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0) { if (tTd(3, 1)) sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n", sm_errstring(errno)); (void) close(kmem); kmem = -1; return -1; } } mirk.mirk_symname = LA_AVENRUN; mirk.mirk_buf = avenrun; mirk.mirk_buflen = sizeof(avenrun); if (ioctl(kmem, MIOC_READKSYM, &mirk) < 0) { if (tTd(3, 1)) sm_dprintf("getla: ioctl(MIOC_READKSYM) failed: %s\n", sm_errstring(errno)); return -1; } if (tTd(3, 5)) { sm_dprintf("getla: avenrun = %d", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %d, %d", avenrun[1], avenrun[2]); sm_dprintf("\n"); } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] + FSCALE/2) >> FSHIFT); return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT); } #endif /* LA_TYPE == LA_READKSYM */ #if LA_TYPE == LA_DGUX # include int getla() { struct dg_sys_info_load_info load_info; dg_sys_info((long *)&load_info, DG_SYS_INFO_LOAD_INFO_TYPE, DG_SYS_INFO_LOAD_VERSION_0); if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (load_info.one_minute + 0.5)); return ((int) (load_info.one_minute + 0.5)); } #endif /* LA_TYPE == LA_DGUX */ #if LA_TYPE == LA_HPUX /* forward declarations to keep gcc from complaining */ struct pst_dynamic; struct pst_status; struct pst_static; struct pst_vminfo; struct pst_diskinfo; struct pst_processor; struct pst_lv; struct pst_swapinfo; # include # include int getla() { struct pst_dynamic pstd; if (pstat_getdynamic(&pstd, sizeof(struct pst_dynamic), (size_t) 1, 0) == -1) return 0; if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (pstd.psd_avg_1_min + 0.5)); return (int) (pstd.psd_avg_1_min + 0.5); } #endif /* LA_TYPE == LA_HPUX */ #if LA_TYPE == LA_SUBR int getla() { double avenrun[3]; if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) < 0) { if (tTd(3, 1)) sm_dprintf("getla: getloadavg failed: %s", sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5)); return ((int) (avenrun[0] + 0.5)); } #endif /* LA_TYPE == LA_SUBR */ #if LA_TYPE == LA_MACH /* ** This has been tested on NEXTSTEP release 2.1/3.X. */ # if defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0 # include # else /* defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0 */ # include # endif /* defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0 */ int getla() { processor_set_t default_set; kern_return_t error; unsigned int info_count; struct processor_set_basic_info info; host_t host; error = processor_set_default(host_self(), &default_set); if (error != KERN_SUCCESS) { if (tTd(3, 1)) sm_dprintf("getla: processor_set_default failed: %s", sm_errstring(errno)); return -1; } info_count = PROCESSOR_SET_BASIC_INFO_COUNT; if (processor_set_info(default_set, PROCESSOR_SET_BASIC_INFO, &host, (processor_set_info_t)&info, &info_count) != KERN_SUCCESS) { if (tTd(3, 1)) sm_dprintf("getla: processor_set_info failed: %s", sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) ((info.load_average + (LOAD_SCALE / 2)) / LOAD_SCALE)); return (int) (info.load_average + (LOAD_SCALE / 2)) / LOAD_SCALE; } #endif /* LA_TYPE == LA_MACH */ #if LA_TYPE == LA_PROCSTR # if SM_CONF_BROKEN_STRTOD ERROR: This OS has most likely a broken strtod() implemenentation. ERROR: The function is required for getla(). ERROR: Check the compilation options _LA_PROCSTR and ERROR: _SM_CONF_BROKEN_STRTOD (without the leading _). # endif /* SM_CONF_BROKEN_STRTOD */ /* ** Read /proc/loadavg for the load average. This is assumed to be ** in a format like "0.15 0.12 0.06". ** ** Initially intended for Linux. This has been in the kernel ** since at least 0.99.15. */ # ifndef _PATH_LOADAVG # define _PATH_LOADAVG "/proc/loadavg" # endif /* ! _PATH_LOADAVG */ int getla() { double avenrun; register int result; SM_FILE_T *fp; fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, _PATH_LOADAVG, SM_IO_RDONLY, NULL); if (fp == NULL) { if (tTd(3, 1)) sm_dprintf("getla: sm_io_open(%s): %s\n", _PATH_LOADAVG, sm_errstring(errno)); return -1; } result = sm_io_fscanf(fp, SM_TIME_DEFAULT, "%lf", &avenrun); (void) sm_io_close(fp, SM_TIME_DEFAULT); if (result != 1) { if (tTd(3, 1)) sm_dprintf("getla: sm_io_fscanf() = %d: %s\n", result, sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla(): %.2f\n", avenrun); return ((int) (avenrun + 0.5)); } #endif /* LA_TYPE == LA_PROCSTR */ #if LA_TYPE == LA_IRIX6 # include # ifdef _UNICOSMP # define CAST_SYSMP(x) (x) # else /* _UNICOSMP */ # define CAST_SYSMP(x) ((x) & 0x7fffffff) # endif /* _UNICOSMP */ int getla(void) { int j; static int kmem = -1; int avenrun[3]; if (kmem < 0) { kmem = open(_PATH_KMEM, 0, 0); if (kmem < 0) { if (tTd(3, 1)) sm_dprintf("getla: open(%s): %s\n", _PATH_KMEM, sm_errstring(errno)); return -1; } if ((j = fcntl(kmem, F_GETFD, 0)) < 0 || fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0) { if (tTd(3, 1)) sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n", sm_errstring(errno)); (void) close(kmem); kmem = -1; return -1; } } if (lseek(kmem, CAST_SYSMP(sysmp(MP_KERNADDR, MPKA_AVENRUN)), SEEK_SET) == -1 || read(kmem, (char *) avenrun, sizeof(avenrun)) != sizeof(avenrun)) { if (tTd(3, 1)) sm_dprintf("getla: lseek or read: %s\n", sm_errstring(errno)); return -1; } if (tTd(3, 5)) { sm_dprintf("getla: avenrun = %ld", (long int) avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %ld, %ld", (long int) avenrun[1], (long int) avenrun[2]); sm_dprintf("\n"); } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] + FSCALE/2) >> FSHIFT); return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT); } #endif /* LA_TYPE == LA_IRIX6 */ #if LA_TYPE == LA_KSTAT # include int getla() { static kstat_ctl_t *kc = NULL; static kstat_t *ksp = NULL; kstat_named_t *ksn; int la; if (kc == NULL) /* if not initialized before */ kc = kstat_open(); if (kc == NULL) { if (tTd(3, 1)) sm_dprintf("getla: kstat_open(): %s\n", sm_errstring(errno)); return -1; } if (ksp == NULL) ksp = kstat_lookup(kc, "unix", 0, "system_misc"); if (ksp == NULL) { if (tTd(3, 1)) sm_dprintf("getla: kstat_lookup(): %s\n", sm_errstring(errno)); return -1; } if (kstat_read(kc, ksp, NULL) < 0) { if (tTd(3, 1)) sm_dprintf("getla: kstat_read(): %s\n", sm_errstring(errno)); return -1; } ksn = (kstat_named_t *) kstat_data_lookup(ksp, "avenrun_1min"); la = ((double) ksn->value.ul + FSCALE/2) / FSCALE; /* kstat_close(kc); /o do not close for fast access */ return la; } #endif /* LA_TYPE == LA_KSTAT */ #if LA_TYPE == LA_DEVSHORT /* ** Read /dev/table/avenrun for the load average. This should contain ** three shorts for the 1, 5, and 15 minute loads. We only read the ** first, since that's all we care about. ** ** Intended for SCO OpenServer 5. */ # ifndef _PATH_AVENRUN # define _PATH_AVENRUN "/dev/table/avenrun" # endif /* ! _PATH_AVENRUN */ int getla() { static int afd = -1; short avenrun; int loadav; int r; errno = EBADF; if (afd == -1 || lseek(afd, 0L, SEEK_SET) == -1) { if (errno != EBADF) return -1; afd = open(_PATH_AVENRUN, O_RDONLY|O_SYNC); if (afd < 0) { sm_syslog(LOG_ERR, NOQID, "can't open %s: %s", _PATH_AVENRUN, sm_errstring(errno)); return -1; } } r = read(afd, &avenrun, sizeof(avenrun)); if (r != sizeof(avenrun)) { sm_syslog(LOG_ERR, NOQID, "can't read %s: %s", _PATH_AVENRUN, r == -1 ? sm_errstring(errno) : "short read"); return -1; } if (tTd(3, 5)) sm_dprintf("getla: avenrun = %d\n", avenrun); loadav = (int) (avenrun + FSCALE/2) >> FSHIFT; if (tTd(3, 1)) sm_dprintf("getla: %d\n", loadav); return loadav; } #endif /* LA_TYPE == LA_DEVSHORT */ #if LA_TYPE == LA_ALPHAOSF struct rtentry; struct mbuf; # include int getla() { int ave = 0; struct tbl_loadavg tab; if (table(TBL_LOADAVG, 0, &tab, 1, sizeof(tab)) == -1) { if (tTd(3, 1)) sm_dprintf("getla: table %s\n", sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla: scale = %d\n", tab.tl_lscale); if (tab.tl_lscale) ave = ((tab.tl_avenrun.l[2] + (tab.tl_lscale/2)) / tab.tl_lscale); else ave = (int) (tab.tl_avenrun.d[2] + 0.5); if (tTd(3, 1)) sm_dprintf("getla: %d\n", ave); return ave; } #endif /* LA_TYPE == LA_ALPHAOSF */ #if LA_TYPE == LA_PSET int getla() { double avenrun[3]; if (pset_getloadavg(PS_MYID, avenrun, sizeof(avenrun) / sizeof(avenrun[0])) < 0) { if (tTd(3, 1)) sm_dprintf("getla: pset_getloadavg failed: %s", sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5)); return ((int) (avenrun[0] + 0.5)); } #endif /* LA_TYPE == LA_PSET */ #if LA_TYPE == LA_ZERO int getla() { if (tTd(3, 1)) sm_dprintf("getla: ZERO\n"); return 0; } #endif /* LA_TYPE == LA_ZERO */ /* * Copyright 1989 Massachusetts Institute of Technology * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of M.I.T. not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. M.I.T. makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL M.I.T. * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Authors: Many and varied... */ /* Non Apollo stuff removed by Don Lewis 11/15/93 */ #ifndef lint SM_UNUSED(static char rcsid[]) = "@(#)$OrigId: getloadavg.c,v 1.16 1991/06/21 12:51:15 paul Exp $"; #endif /* ! lint */ #ifdef apollo # undef volatile # include /* ARGSUSED */ int getloadavg( call_data ) caddr_t call_data; /* pointer to (double) return value */ { double *avenrun = (double *) call_data; int i; status_$t st; long loadav[3]; proc1_$get_loadav(loadav, &st); *avenrun = loadav[0] / (double) (1 << 16); return 0; } #endif /* apollo */ /* ** SM_GETLA -- get the current load average ** ** Parameters: ** none ** ** Returns: ** none ** ** Side Effects: ** Set CurrentLA to the current load average. ** Set {load_avg} in GlobalMacros to the current load average. */ void sm_getla() { char labuf[8]; CurrentLA = getla(); (void) sm_snprintf(labuf, sizeof(labuf), "%d", CurrentLA); macdefine(&GlobalMacros, A_TEMP, macid("{load_avg}"), labuf); } /* ** SHOULDQUEUE -- should this message be queued or sent? ** ** Compares the message cost to the load average to decide. ** ** Note: Do NOT change this API! It is documented in op.me ** and theoretically the user can change this function... ** ** Parameters: ** pri -- the priority of the message in question. ** ct -- the message creation time (unused, but see above). ** ** Returns: ** true -- if this message should be queued up for the ** time being. ** false -- if the load is low enough to send this message. ** ** Side Effects: ** none. */ /* ARGSUSED1 */ bool shouldqueue(pri, ct) long pri; time_t ct; { bool rval; #if _FFR_MEMSTAT long memfree; #endif /* _FFR_MEMSTAT */ if (tTd(3, 30)) sm_dprintf("shouldqueue: CurrentLA=%d, pri=%ld: ", CurrentLA, pri); #if _FFR_MEMSTAT if (QueueLowMem > 0 && sm_memstat_get(MemoryResource, &memfree) >= 0 && memfree < QueueLowMem) { if (tTd(3, 30)) sm_dprintf("true (memfree=%ld < QueueLowMem=%ld)\n", memfree, QueueLowMem); return true; } #endif /* _FFR_MEMSTAT */ if (CurrentLA < QueueLA) { if (tTd(3, 30)) sm_dprintf("false (CurrentLA < QueueLA)\n"); return false; } rval = pri > (QueueFactor / (CurrentLA - QueueLA + 1)); if (tTd(3, 30)) sm_dprintf("%s (by calculation)\n", rval ? "true" : "false"); return rval; } /* ** REFUSECONNECTIONS -- decide if connections should be refused ** ** Parameters: ** e -- the current envelope. ** dn -- number of daemon. ** active -- was this daemon actually active? ** ** Returns: ** true if incoming SMTP connections should be refused ** (for now). ** false if we should accept new work. ** ** Side Effects: ** Sets process title when it is rejecting connections. */ bool refuseconnections(e, dn, active) ENVELOPE *e; int dn; bool active; { static time_t lastconn[MAXDAEMONS]; static int conncnt[MAXDAEMONS]; static time_t firstrejtime[MAXDAEMONS]; static time_t nextlogtime[MAXDAEMONS]; int limit; #if _FFR_MEMSTAT long memfree; #endif /* _FFR_MEMSTAT */ #if XLA if (!xla_smtp_ok()) return true; #endif /* XLA */ SM_ASSERT(dn >= 0); SM_ASSERT(dn < MAXDAEMONS); if (ConnRateThrottle > 0) { time_t now; now = curtime(); if (active) { if (now != lastconn[dn]) { lastconn[dn] = now; conncnt[dn] = 1; } else if (conncnt[dn]++ > ConnRateThrottle) { #define D_MSG_CRT "deferring connections on daemon %s: %d per second" /* sleep to flatten out connection load */ sm_setproctitle(true, e, D_MSG_CRT, Daemons[dn].d_name, ConnRateThrottle); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, D_MSG_CRT, Daemons[dn].d_name, ConnRateThrottle); (void) sleep(1); } } else if (now != lastconn[dn]) conncnt[dn] = 0; } #if _FFR_MEMSTAT if (RefuseLowMem > 0 && sm_memstat_get(MemoryResource, &memfree) >= 0 && memfree < RefuseLowMem) { # define R_MSG_LM "rejecting connections on daemon %s: free memory: %ld" sm_setproctitle(true, e, R_MSG_LM, Daemons[dn].d_name, memfree); if (LogLevel > 8) sm_syslog(LOG_NOTICE, NOQID, R_MSG_LM, Daemons[dn].d_name, memfree); return true; } #endif /* _FFR_MEMSTAT */ sm_getla(); limit = (Daemons[dn].d_refuseLA != DPO_NOTSET) ? Daemons[dn].d_refuseLA : RefuseLA; if (limit > 0 && CurrentLA >= limit) { time_t now; # define R_MSG_LA "rejecting connections on daemon %s: load average: %d" # define R2_MSG_LA "have been rejecting connections on daemon %s for %s" sm_setproctitle(true, e, R_MSG_LA, Daemons[dn].d_name, CurrentLA); if (LogLevel > 8) sm_syslog(LOG_NOTICE, NOQID, R_MSG_LA, Daemons[dn].d_name, CurrentLA); now = curtime(); if (firstrejtime[dn] == 0) { firstrejtime[dn] = now; nextlogtime[dn] = now + RejectLogInterval; } else if (nextlogtime[dn] < now) { sm_syslog(LOG_ERR, NOQID, R2_MSG_LA, Daemons[dn].d_name, pintvl(now - firstrejtime[dn], true)); nextlogtime[dn] = now + RejectLogInterval; } return true; } else firstrejtime[dn] = 0; limit = (Daemons[dn].d_delayLA != DPO_NOTSET) ? Daemons[dn].d_delayLA : DelayLA; if (limit > 0 && CurrentLA >= limit) { time_t now; static time_t log_delay = (time_t) 0; # define MIN_DELAY_LOG 90 /* wait before logging this again */ # define D_MSG_LA "delaying connections on daemon %s: load average=%d >= %d" /* sleep to flatten out connection load */ sm_setproctitle(true, e, D_MSG_LA, Daemons[dn].d_name, CurrentLA, limit); if (LogLevel > 8 && (now = curtime()) > log_delay) { sm_syslog(LOG_INFO, NOQID, D_MSG_LA, Daemons[dn].d_name, CurrentLA, limit); log_delay = now + MIN_DELAY_LOG; } (void) sleep(1); } limit = (Daemons[dn].d_maxchildren != DPO_NOTSET) ? Daemons[dn].d_maxchildren : MaxChildren; if (limit > 0 && CurChildren >= limit) { proc_list_probe(); if (CurChildren >= limit) { #define R_MSG_CHILD "rejecting connections on daemon %s: %d children, max %d" sm_setproctitle(true, e, R_MSG_CHILD, Daemons[dn].d_name, CurChildren, limit); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, R_MSG_CHILD, Daemons[dn].d_name, CurChildren, limit); return true; } } return false; } /* ** SETPROCTITLE -- set process title for ps ** ** Parameters: ** fmt -- a printf style format string. ** a, b, c -- possible parameters to fmt. ** ** Returns: ** none. ** ** Side Effects: ** Clobbers argv of our main procedure so ps(1) will ** display the title. */ #define SPT_NONE 0 /* don't use it at all */ #define SPT_REUSEARGV 1 /* cover argv with title information */ #define SPT_BUILTIN 2 /* use libc builtin */ #define SPT_PSTAT 3 /* use pstat(PSTAT_SETCMD, ...) */ #define SPT_PSSTRINGS 4 /* use PS_STRINGS->... */ #define SPT_SYSMIPS 5 /* use sysmips() supported by NEWS-OS 6 */ #define SPT_SCO 6 /* write kernel u. area */ #define SPT_CHANGEARGV 7 /* write our own strings into argv[] */ #ifndef SPT_TYPE # define SPT_TYPE SPT_REUSEARGV #endif /* ! SPT_TYPE */ #if SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN # if SPT_TYPE == SPT_PSTAT # include # endif /* SPT_TYPE == SPT_PSTAT */ # if SPT_TYPE == SPT_PSSTRINGS # include # include # ifndef PS_STRINGS /* hmmmm.... apparently not available after all */ # undef SPT_TYPE # define SPT_TYPE SPT_REUSEARGV # else /* ! PS_STRINGS */ # ifndef NKPDE /* FreeBSD 2.0 */ # define NKPDE 63 typedef unsigned int *pt_entry_t; # endif /* ! NKPDE */ # endif /* ! PS_STRINGS */ # endif /* SPT_TYPE == SPT_PSSTRINGS */ # if SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV # define SETPROC_STATIC static # else /* SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV */ # define SETPROC_STATIC # endif /* SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV */ # if SPT_TYPE == SPT_SYSMIPS # include # include # endif /* SPT_TYPE == SPT_SYSMIPS */ # if SPT_TYPE == SPT_SCO # include # include # include # include # if PSARGSZ > MAXLINE # define SPT_BUFSIZE PSARGSZ # endif /* PSARGSZ > MAXLINE */ # endif /* SPT_TYPE == SPT_SCO */ # ifndef SPT_PADCHAR # define SPT_PADCHAR ' ' # endif /* ! SPT_PADCHAR */ #endif /* SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN */ #ifndef SPT_BUFSIZE # define SPT_BUFSIZE MAXLINE #endif /* ! SPT_BUFSIZE */ #if _FFR_SPT_ALIGN /* ** It looks like the Compaq Tru64 5.1A now aligns argv and envp to ** 64 bit alignment, so unless each piece of argv and envp is a multiple ** of 8 bytes (including terminating NULL), initsetproctitle() won't use ** any of the space beyond argv[0]. Be sure to set SPT_ALIGN_SIZE if ** you use this FFR. */ # ifdef SPT_ALIGN_SIZE # define SPT_ALIGN(x, align) (((((x) + SPT_ALIGN_SIZE) >> (align)) << (align)) - 1) # else /* SPT_ALIGN_SIZE */ # define SPT_ALIGN(x, align) (x) # endif /* SPT_ALIGN_SIZE */ #else /* _FFR_SPT_ALIGN */ # define SPT_ALIGN(x, align) (x) #endif /* _FFR_SPT_ALIGN */ /* ** Pointers for setproctitle. ** This allows "ps" listings to give more useful information. */ static char **Argv = NULL; /* pointer to argument vector */ static char *LastArgv = NULL; /* end of argv */ #if SPT_TYPE != SPT_BUILTIN static void setproctitle __P((const char *, ...)); #endif /* SPT_TYPE != SPT_BUILTIN */ void initsetproctitle(argc, argv, envp) int argc; char **argv; char **envp; { register int i; int align; extern char **environ; /* ** Move the environment so setproctitle can use the space at ** the top of memory. */ if (envp != NULL) { for (i = 0; envp[i] != NULL; i++) continue; environ = (char **) xalloc(sizeof(char *) * (i + 1)); for (i = 0; envp[i] != NULL; i++) environ[i] = newstr(envp[i]); environ[i] = NULL; } /* ** Save start and extent of argv for setproctitle. */ Argv = argv; /* ** Determine how much space we can use for setproctitle. ** Use all contiguous argv and envp pointers starting at argv[0] */ align = -1; # if _FFR_SPT_ALIGN # ifdef SPT_ALIGN_SIZE for (i = SPT_ALIGN_SIZE; i > 0; i >>= 1) align++; # endif /* SPT_ALIGN_SIZE */ # endif /* _FFR_SPT_ALIGN */ for (i = 0; i < argc; i++) { if (i == 0 || LastArgv + 1 == argv[i]) LastArgv = argv[i] + SPT_ALIGN(strlen(argv[i]), align); } for (i = 0; LastArgv != NULL && envp != NULL && envp[i] != NULL; i++) { if (LastArgv + 1 == envp[i]) LastArgv = envp[i] + SPT_ALIGN(strlen(envp[i]), align); } } #if SPT_TYPE != SPT_BUILTIN /*VARARGS1*/ static void # ifdef __STDC__ setproctitle(const char *fmt, ...) # else /* __STDC__ */ setproctitle(fmt, va_alist) const char *fmt; va_dcl # endif /* __STDC__ */ { # if SPT_TYPE != SPT_NONE register int i; register char *p; SETPROC_STATIC char buf[SPT_BUFSIZE]; SM_VA_LOCAL_DECL # if SPT_TYPE == SPT_PSTAT union pstun pst; # endif /* SPT_TYPE == SPT_PSTAT */ # if SPT_TYPE == SPT_SCO int j; off_t seek_off; static int kmem = -1; static pid_t kmempid = -1; struct user u; # endif /* SPT_TYPE == SPT_SCO */ p = buf; /* print sendmail: heading for grep */ (void) sm_strlcpy(p, "sendmail: ", SPACELEFT(buf, p)); p += strlen(p); /* print the argument string */ SM_VA_START(ap, fmt); (void) sm_vsnprintf(p, SPACELEFT(buf, p), fmt, ap); SM_VA_END(ap); i = (int) strlen(buf); if (i < 0) return; # if SPT_TYPE == SPT_PSTAT pst.pst_command = buf; pstat(PSTAT_SETCMD, pst, i, 0, 0); # endif /* SPT_TYPE == SPT_PSTAT */ # if SPT_TYPE == SPT_PSSTRINGS PS_STRINGS->ps_nargvstr = 1; PS_STRINGS->ps_argvstr = buf; # endif /* SPT_TYPE == SPT_PSSTRINGS */ # if SPT_TYPE == SPT_SYSMIPS sysmips(SONY_SYSNEWS, NEWS_SETPSARGS, buf); # endif /* SPT_TYPE == SPT_SYSMIPS */ # if SPT_TYPE == SPT_SCO if (kmem < 0 || kmempid != CurrentPid) { if (kmem >= 0) (void) close(kmem); kmem = open(_PATH_KMEM, O_RDWR, 0); if (kmem < 0) return; if ((j = fcntl(kmem, F_GETFD, 0)) < 0 || fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0) { (void) close(kmem); kmem = -1; return; } kmempid = CurrentPid; } buf[PSARGSZ - 1] = '\0'; seek_off = UVUBLK + (off_t) u.u_psargs - (off_t) &u; if (lseek(kmem, (off_t) seek_off, SEEK_SET) == seek_off) (void) write(kmem, buf, PSARGSZ); # endif /* SPT_TYPE == SPT_SCO */ # if SPT_TYPE == SPT_REUSEARGV if (LastArgv == NULL) return; if (i > LastArgv - Argv[0] - 2) { i = LastArgv - Argv[0] - 2; buf[i] = '\0'; } (void) sm_strlcpy(Argv[0], buf, i + 1); p = &Argv[0][i]; while (p < LastArgv) *p++ = SPT_PADCHAR; Argv[1] = NULL; # endif /* SPT_TYPE == SPT_REUSEARGV */ # if SPT_TYPE == SPT_CHANGEARGV Argv[0] = buf; Argv[1] = 0; # endif /* SPT_TYPE == SPT_CHANGEARGV */ # endif /* SPT_TYPE != SPT_NONE */ } #endif /* SPT_TYPE != SPT_BUILTIN */ /* ** SM_SETPROCTITLE -- set process task and set process title for ps ** ** Possibly set process status and call setproctitle() to ** change the ps display. ** ** Parameters: ** status -- whether or not to store as process status ** e -- the current envelope. ** fmt -- a printf style format string. ** a, b, c -- possible parameters to fmt. ** ** Returns: ** none. */ /*VARARGS3*/ void #ifdef __STDC__ sm_setproctitle(bool status, ENVELOPE *e, const char *fmt, ...) #else /* __STDC__ */ sm_setproctitle(status, e, fmt, va_alist) bool status; ENVELOPE *e; const char *fmt; va_dcl #endif /* __STDC__ */ { char buf[SPT_BUFSIZE]; SM_VA_LOCAL_DECL /* print the argument string */ SM_VA_START(ap, fmt); (void) sm_vsnprintf(buf, sizeof(buf), fmt, ap); SM_VA_END(ap); if (status) proc_list_set(CurrentPid, buf); if (ProcTitlePrefix != NULL) { char prefix[SPT_BUFSIZE]; expand(ProcTitlePrefix, prefix, sizeof(prefix), e); setproctitle("%s: %s", prefix, buf); } else setproctitle("%s", buf); } /* ** WAITFOR -- wait for a particular process id. ** ** Parameters: ** pid -- process id to wait for. ** ** Returns: ** status of pid. ** -1 if pid never shows up. ** ** Side Effects: ** none. */ int waitfor(pid) pid_t pid; { int st; pid_t i; do { errno = 0; i = sm_wait(&st); if (i > 0) proc_list_drop(i, st, NULL); } while ((i >= 0 || errno == EINTR) && i != pid); if (i < 0) return -1; return st; } /* ** SM_WAIT -- wait ** ** Parameters: ** status -- pointer to status (return value) ** ** Returns: ** pid */ pid_t sm_wait(status) int *status; { # ifdef WAITUNION union wait st; # else /* WAITUNION */ auto int st; # endif /* WAITUNION */ pid_t i; # if defined(ISC_UNIX) || defined(_SCO_unix_) int savesig; # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */ # if defined(ISC_UNIX) || defined(_SCO_unix_) savesig = sm_releasesignal(SIGCHLD); # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */ i = wait(&st); # if defined(ISC_UNIX) || defined(_SCO_unix_) if (savesig > 0) sm_blocksignal(SIGCHLD); # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */ # ifdef WAITUNION *status = st.w_status; # else /* WAITUNION */ *status = st; # endif /* WAITUNION */ return i; } /* ** REAPCHILD -- pick up the body of my child, lest it become a zombie ** ** Parameters: ** sig -- the signal that got us here (unused). ** ** Returns: ** none. ** ** Side Effects: ** Picks up extant zombies. ** Control socket exits may restart/shutdown daemon. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ /* ARGSUSED0 */ SIGFUNC_DECL reapchild(sig) int sig; { int save_errno = errno; int st; pid_t pid; # if HASWAITPID auto int status; int count; count = 0; while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { st = status; if (count++ > 1000) break; # else /* HASWAITPID */ # ifdef WNOHANG union wait status; while ((pid = wait3(&status, WNOHANG, (struct rusage *) NULL)) > 0) { st = status.w_status; # else /* WNOHANG */ auto int status; /* ** Catch one zombie -- we will be re-invoked (we hope) if there ** are more. Unreliable signals probably break this, but this ** is the "old system" situation -- waitpid or wait3 are to be ** strongly preferred. */ if ((pid = wait(&status)) > 0) { st = status; # endif /* WNOHANG */ # endif /* HASWAITPID */ /* Drop PID and check if it was a control socket child */ proc_list_drop(pid, st, NULL); } FIX_SYSV_SIGNAL(sig, reapchild); errno = save_errno; return SIGFUNC_RETURN; } /* ** GETDTABLESIZE -- return number of file descriptors ** ** Only on non-BSD systems ** ** Parameters: ** none ** ** Returns: ** size of file descriptor table ** ** Side Effects: ** none */ #ifdef SOLARIS # include #endif /* SOLARIS */ int getdtsize() { # ifdef RLIMIT_NOFILE struct rlimit rl; if (getrlimit(RLIMIT_NOFILE, &rl) >= 0) return rl.rlim_cur; # endif /* RLIMIT_NOFILE */ # if HASGETDTABLESIZE return getdtablesize(); # else /* HASGETDTABLESIZE */ # ifdef _SC_OPEN_MAX return sysconf(_SC_OPEN_MAX); # else /* _SC_OPEN_MAX */ return NOFILE; # endif /* _SC_OPEN_MAX */ # endif /* HASGETDTABLESIZE */ } /* ** UNAME -- get the UUCP name of this system. */ #if !HASUNAME int uname(name) struct utsname *name; { SM_FILE_T *file; char *n; name->nodename[0] = '\0'; /* try /etc/whoami -- one line with the node name */ if ((file = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, "/etc/whoami", SM_IO_RDONLY, NULL)) != NULL) { (void) sm_io_fgets(file, SM_TIME_DEFAULT, name->nodename, NODE_LENGTH + 1); (void) sm_io_close(file, SM_TIME_DEFAULT); n = strchr(name->nodename, '\n'); if (n != NULL) *n = '\0'; if (name->nodename[0] != '\0') return 0; } /* try /usr/include/whoami.h -- has a #define somewhere */ if ((file = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, "/usr/include/whoami.h", SM_IO_RDONLY, NULL)) != NULL) { char buf[MAXLINE]; while (sm_io_fgets(file, SM_TIME_DEFAULT, - buf, sizeof(buf)) != NULL) + buf, sizeof(buf)) >= 0) { if (sm_io_sscanf(buf, "#define sysname \"%*[^\"]\"", NODE_LENGTH, name->nodename) > 0) break; } (void) sm_io_close(file, SM_TIME_DEFAULT); if (name->nodename[0] != '\0') return 0; } return -1; } #endif /* !HASUNAME */ /* ** INITGROUPS -- initialize groups ** ** Stub implementation for System V style systems */ #if !HASINITGROUPS initgroups(name, basegid) char *name; int basegid; { return 0; } #endif /* !HASINITGROUPS */ /* ** SETGROUPS -- set group list ** ** Stub implementation for systems that don't have group lists */ #ifndef NGROUPS_MAX int setgroups(ngroups, grouplist) int ngroups; GIDSET_T grouplist[]; { return 0; } #endif /* ! NGROUPS_MAX */ /* ** SETSID -- set session id (for non-POSIX systems) */ #if !HASSETSID pid_t setsid __P ((void)) { # ifdef TIOCNOTTY int fd; fd = open("/dev/tty", O_RDWR, 0); if (fd >= 0) { (void) ioctl(fd, TIOCNOTTY, (char *) 0); (void) close(fd); } # endif /* TIOCNOTTY */ # ifdef SYS5SETPGRP return setpgrp(); # else /* SYS5SETPGRP */ return setpgid(0, CurrentPid); # endif /* SYS5SETPGRP */ } #endif /* !HASSETSID */ /* ** FSYNC -- dummy fsync */ #if NEEDFSYNC fsync(fd) int fd; { # ifdef O_SYNC return fcntl(fd, F_SETFL, O_SYNC); # else /* O_SYNC */ /* nothing we can do */ return 0; # endif /* O_SYNC */ } #endif /* NEEDFSYNC */ /* ** DGUX_INET_ADDR -- inet_addr for DG/UX ** ** Data General DG/UX version of inet_addr returns a struct in_addr ** instead of a long. This patches things. Only needed on versions ** prior to 5.4.3. */ #ifdef DGUX_5_4_2 # undef inet_addr long dgux_inet_addr(host) char *host; { struct in_addr haddr; haddr = inet_addr(host); return haddr.s_addr; } #endif /* DGUX_5_4_2 */ /* ** GETOPT -- for old systems or systems with bogus implementations */ #if !SM_CONF_GETOPT /* * Copyright (c) 1985 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ /* ** this version hacked to add `atend' flag to allow state machine ** to reset if invoked by the program to scan args for a 2nd time */ # if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)getopt.c 4.3 (Berkeley) 3/9/86"; # endif /* defined(LIBC_SCCS) && !defined(lint) */ /* ** get option letter from argument vector */ # ifdef _CONVEX_SOURCE extern int optind, opterr, optopt; extern char *optarg; # else /* _CONVEX_SOURCE */ int opterr = 1; /* if error message should be printed */ int optind = 1; /* index into parent argv vector */ int optopt = 0; /* character checked for validity */ char *optarg = NULL; /* argument associated with option */ # endif /* _CONVEX_SOURCE */ # define BADCH (int)'?' # define EMSG "" # define tell(s) if (opterr) \ {sm_io_fputs(smioerr, SM_TIME_DEFAULT, *nargv); \ (void) sm_io_fputs(smioerr, SM_TIME_DEFAULT, s); \ (void) sm_io_putc(smioerr, SM_TIME_DEFAULT, optopt); \ (void) sm_io_putc(smioerr, SM_TIME_DEFAULT, '\n'); \ return BADCH;} int getopt(nargc,nargv,ostr) int nargc; char *const *nargv; const char *ostr; { static char *place = EMSG; /* option letter processing */ static char atend = 0; register char *oli = NULL; /* option letter list index */ if (atend) { atend = 0; place = EMSG; } if(!*place) { /* update scanning pointer */ if (optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) { atend++; return -1; } if (*place == '-') { /* found "--" */ ++optind; atend++; return -1; } } /* option letter okay? */ if ((optopt = (int)*place++) == (int)':' || !(oli = strchr(ostr,optopt))) { if (!*place) ++optind; tell(": illegal option -- "); } if (oli && *++oli != ':') { /* don't need argument */ optarg = NULL; if (!*place) ++optind; } else { /* need an argument */ if (*place) optarg = place; /* no white space */ else if (nargc <= ++optind) { /* no arg */ place = EMSG; tell(": option requires an argument -- "); } else optarg = nargv[optind]; /* white space */ place = EMSG; ++optind; } return optopt; /* dump back option letter */ } #endif /* !SM_CONF_GETOPT */ /* ** USERSHELLOK -- tell if a user's shell is ok for unrestricted use ** ** Parameters: ** user -- the name of the user we are checking. ** shell -- the user's shell from /etc/passwd ** ** Returns: ** true -- if it is ok to use this for unrestricted access. ** false -- if the shell is restricted. */ #if !HASGETUSERSHELL # ifndef _PATH_SHELLS # define _PATH_SHELLS "/etc/shells" # endif /* ! _PATH_SHELLS */ # if defined(_AIX3) || defined(_AIX4) # include # if _AIX4 >= 40200 # include # endif /* _AIX4 >= 40200 */ # include # endif /* defined(_AIX3) || defined(_AIX4) */ static char *DefaultUserShells[] = { "/bin/sh", /* standard shell */ # ifdef MPE "/SYS/PUB/CI", # else /* MPE */ "/usr/bin/sh", "/bin/csh", /* C shell */ "/usr/bin/csh", # endif /* MPE */ # ifdef __hpux # ifdef V4FS "/usr/bin/rsh", /* restricted Bourne shell */ "/usr/bin/ksh", /* Korn shell */ "/usr/bin/rksh", /* restricted Korn shell */ "/usr/bin/pam", "/usr/bin/keysh", /* key shell (extended Korn shell) */ "/usr/bin/posix/sh", # else /* V4FS */ "/bin/rsh", /* restricted Bourne shell */ "/bin/ksh", /* Korn shell */ "/bin/rksh", /* restricted Korn shell */ "/bin/pam", "/usr/bin/keysh", /* key shell (extended Korn shell) */ "/bin/posix/sh", "/sbin/sh", # endif /* V4FS */ # endif /* __hpux */ # if defined(_AIX3) || defined(_AIX4) "/bin/ksh", /* Korn shell */ "/usr/bin/ksh", "/bin/tsh", /* trusted shell */ "/usr/bin/tsh", "/bin/bsh", /* Bourne shell */ "/usr/bin/bsh", # endif /* defined(_AIX3) || defined(_AIX4) */ # if defined(__svr4__) || defined(__svr5__) "/bin/ksh", /* Korn shell */ "/usr/bin/ksh", # endif /* defined(__svr4__) || defined(__svr5__) */ # ifdef sgi "/sbin/sh", /* SGI's shells really live in /sbin */ "/usr/bin/sh", "/sbin/bsh", /* classic Bourne shell */ "/bin/bsh", "/usr/bin/bsh", "/sbin/csh", /* standard csh */ "/bin/csh", "/usr/bin/csh", "/sbin/jsh", /* classic Bourne shell w/ job control*/ "/bin/jsh", "/usr/bin/jsh", "/bin/ksh", /* Korn shell */ "/sbin/ksh", "/usr/bin/ksh", "/sbin/tcsh", /* Extended csh */ "/bin/tcsh", "/usr/bin/tcsh", # endif /* sgi */ NULL }; #endif /* !HASGETUSERSHELL */ #define WILDCARD_SHELL "/SENDMAIL/ANY/SHELL/" bool usershellok(user, shell) char *user; char *shell; { # if HASGETUSERSHELL register char *p; extern char *getusershell(); if (shell == NULL || shell[0] == '\0' || wordinclass(user, 't') || ConfigLevel <= 1) return true; setusershell(); while ((p = getusershell()) != NULL) if (strcmp(p, shell) == 0 || strcmp(p, WILDCARD_SHELL) == 0) break; endusershell(); return p != NULL; # else /* HASGETUSERSHELL */ # if USEGETCONFATTR auto char *v; # endif /* USEGETCONFATTR */ register SM_FILE_T *shellf; char buf[MAXLINE]; if (shell == NULL || shell[0] == '\0' || wordinclass(user, 't') || ConfigLevel <= 1) return true; # if USEGETCONFATTR /* ** Naturally IBM has a "better" idea..... ** ** What a crock. This interface isn't documented, it is ** considered part of the security library (-ls), and it ** only works if you are running as root (since the list ** of valid shells is obviously a source of great concern). ** I recommend that you do NOT define USEGETCONFATTR, ** especially since you are going to have to set up an ** /etc/shells anyhow to handle the cases where getconfattr ** fails. */ if (getconfattr(SC_SYS_LOGIN, SC_SHELLS, &v, SEC_LIST) == 0 && v != NULL) { while (*v != '\0') { if (strcmp(v, shell) == 0 || strcmp(v, WILDCARD_SHELL) == 0) return true; v += strlen(v) + 1; } return false; } # endif /* USEGETCONFATTR */ shellf = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, _PATH_SHELLS, SM_IO_RDONLY, NULL); if (shellf == NULL) { /* no /etc/shells; see if it is one of the std shells */ char **d; if (errno != ENOENT && LogLevel > 3) sm_syslog(LOG_ERR, NOQID, "usershellok: cannot open %s: %s", _PATH_SHELLS, sm_errstring(errno)); for (d = DefaultUserShells; *d != NULL; d++) { if (strcmp(shell, *d) == 0) return true; } return false; } - while (sm_io_fgets(shellf, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(shellf, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { register char *p, *q; p = buf; while (*p != '\0' && *p != '#' && *p != '/') p++; if (*p == '#' || *p == '\0') continue; q = p; while (*p != '\0' && *p != '#' && !(isascii(*p) && isspace(*p))) p++; *p = '\0'; if (strcmp(shell, q) == 0 || strcmp(WILDCARD_SHELL, q) == 0) { (void) sm_io_close(shellf, SM_TIME_DEFAULT); return true; } } (void) sm_io_close(shellf, SM_TIME_DEFAULT); return false; # endif /* HASGETUSERSHELL */ } /* ** FREEDISKSPACE -- see how much free space is on the queue filesystem ** ** Only implemented if you have statfs. ** ** Parameters: ** dir -- the directory in question. ** bsize -- a variable into which the filesystem ** block size is stored. ** ** Returns: ** The number of blocks free on the queue filesystem. ** -1 if the statfs call fails. ** ** Side effects: ** Puts the filesystem block size into bsize. */ /* statfs types */ # define SFS_NONE 0 /* no statfs implementation */ # define SFS_USTAT 1 /* use ustat */ # define SFS_4ARGS 2 /* use four-argument statfs call */ # define SFS_VFS 3 /* use implementation */ # define SFS_MOUNT 4 /* use implementation */ # define SFS_STATFS 5 /* use implementation */ # define SFS_STATVFS 6 /* use implementation */ # ifndef SFS_TYPE # define SFS_TYPE SFS_NONE # endif /* ! SFS_TYPE */ # if SFS_TYPE == SFS_USTAT # include # endif /* SFS_TYPE == SFS_USTAT */ # if SFS_TYPE == SFS_4ARGS || SFS_TYPE == SFS_STATFS # include # endif /* SFS_TYPE == SFS_4ARGS || SFS_TYPE == SFS_STATFS */ # if SFS_TYPE == SFS_VFS # include # endif /* SFS_TYPE == SFS_VFS */ # if SFS_TYPE == SFS_MOUNT # include # endif /* SFS_TYPE == SFS_MOUNT */ # if SFS_TYPE == SFS_STATVFS # include # endif /* SFS_TYPE == SFS_STATVFS */ long freediskspace(dir, bsize) const char *dir; long *bsize; { # if SFS_TYPE == SFS_NONE if (bsize != NULL) *bsize = 4096L; /* assume free space is plentiful */ return (long) LONG_MAX; # else /* SFS_TYPE == SFS_NONE */ # if SFS_TYPE == SFS_USTAT struct ustat fs; struct stat statbuf; # define FSBLOCKSIZE DEV_BSIZE # define SFS_BAVAIL f_tfree # else /* SFS_TYPE == SFS_USTAT */ # if defined(ultrix) struct fs_data fs; # define SFS_BAVAIL fd_bfreen # define FSBLOCKSIZE 1024L # else /* defined(ultrix) */ # if SFS_TYPE == SFS_STATVFS struct statvfs fs; # define FSBLOCKSIZE fs.f_frsize # else /* SFS_TYPE == SFS_STATVFS */ struct statfs fs; # define FSBLOCKSIZE fs.f_bsize # endif /* SFS_TYPE == SFS_STATVFS */ # endif /* defined(ultrix) */ # endif /* SFS_TYPE == SFS_USTAT */ # ifndef SFS_BAVAIL # define SFS_BAVAIL f_bavail # endif /* ! SFS_BAVAIL */ # if SFS_TYPE == SFS_USTAT if (stat(dir, &statbuf) == 0 && ustat(statbuf.st_dev, &fs) == 0) # else /* SFS_TYPE == SFS_USTAT */ # if SFS_TYPE == SFS_4ARGS if (statfs(dir, &fs, sizeof(fs), 0) == 0) # else /* SFS_TYPE == SFS_4ARGS */ # if SFS_TYPE == SFS_STATVFS if (statvfs(dir, &fs) == 0) # else /* SFS_TYPE == SFS_STATVFS */ # if defined(ultrix) if (statfs(dir, &fs) > 0) # else /* defined(ultrix) */ if (statfs(dir, &fs) == 0) # endif /* defined(ultrix) */ # endif /* SFS_TYPE == SFS_STATVFS */ # endif /* SFS_TYPE == SFS_4ARGS */ # endif /* SFS_TYPE == SFS_USTAT */ { if (bsize != NULL) *bsize = FSBLOCKSIZE; if (fs.SFS_BAVAIL <= 0) return 0; else if (fs.SFS_BAVAIL > LONG_MAX) return (long) LONG_MAX; else return (long) fs.SFS_BAVAIL; } return -1; # endif /* SFS_TYPE == SFS_NONE */ } /* ** ENOUGHDISKSPACE -- is there enough free space on the queue file systems? ** ** Parameters: ** msize -- the size to check against. If zero, we don't yet ** know how big the message will be, so just check for ** a "reasonable" amount. ** e -- envelope, or NULL -- controls logging ** ** Returns: ** true if in every queue group there is at least one ** queue directory whose file system contains enough free space. ** false otherwise. ** ** Side Effects: ** If there is not enough disk space and e != NULL ** then sm_syslog is called. */ bool enoughdiskspace(msize, e) long msize; ENVELOPE *e; { int i; #if _FFR_TESTS if (tTd(4, 101)) return false; #endif /* _FFR_TESTS */ if (MinBlocksFree <= 0 && msize <= 0) { if (tTd(4, 80)) sm_dprintf("enoughdiskspace: no threshold\n"); return true; } filesys_update(); for (i = 0; i < NumQueue; ++i) { if (pickqdir(Queue[i], msize, e) < 0) return false; } return true; } /* ** TRANSIENTERROR -- tell if an error code indicates a transient failure ** ** This looks at an errno value and tells if this is likely to ** go away if retried later. ** ** Parameters: ** err -- the errno code to classify. ** ** Returns: ** true if this is probably transient. ** false otherwise. */ bool transienterror(err) int err; { switch (err) { case EIO: /* I/O error */ case ENXIO: /* Device not configured */ case EAGAIN: /* Resource temporarily unavailable */ case ENOMEM: /* Cannot allocate memory */ case ENODEV: /* Operation not supported by device */ case ENFILE: /* Too many open files in system */ case EMFILE: /* Too many open files */ case ENOSPC: /* No space left on device */ case ETIMEDOUT: /* Connection timed out */ #ifdef ESTALE case ESTALE: /* Stale NFS file handle */ #endif /* ESTALE */ #ifdef ENETDOWN case ENETDOWN: /* Network is down */ #endif /* ENETDOWN */ #ifdef ENETUNREACH case ENETUNREACH: /* Network is unreachable */ #endif /* ENETUNREACH */ #ifdef ENETRESET case ENETRESET: /* Network dropped connection on reset */ #endif /* ENETRESET */ #ifdef ECONNABORTED case ECONNABORTED: /* Software caused connection abort */ #endif /* ECONNABORTED */ #ifdef ECONNRESET case ECONNRESET: /* Connection reset by peer */ #endif /* ECONNRESET */ #ifdef ENOBUFS case ENOBUFS: /* No buffer space available */ #endif /* ENOBUFS */ #ifdef ESHUTDOWN case ESHUTDOWN: /* Can't send after socket shutdown */ #endif /* ESHUTDOWN */ #ifdef ECONNREFUSED case ECONNREFUSED: /* Connection refused */ #endif /* ECONNREFUSED */ #ifdef EHOSTDOWN case EHOSTDOWN: /* Host is down */ #endif /* EHOSTDOWN */ #ifdef EHOSTUNREACH case EHOSTUNREACH: /* No route to host */ #endif /* EHOSTUNREACH */ #ifdef EDQUOT case EDQUOT: /* Disc quota exceeded */ #endif /* EDQUOT */ #ifdef EPROCLIM case EPROCLIM: /* Too many processes */ #endif /* EPROCLIM */ #ifdef EUSERS case EUSERS: /* Too many users */ #endif /* EUSERS */ #ifdef EDEADLK case EDEADLK: /* Resource deadlock avoided */ #endif /* EDEADLK */ #ifdef EISCONN case EISCONN: /* Socket already connected */ #endif /* EISCONN */ #ifdef EINPROGRESS case EINPROGRESS: /* Operation now in progress */ #endif /* EINPROGRESS */ #ifdef EALREADY case EALREADY: /* Operation already in progress */ #endif /* EALREADY */ #ifdef EADDRINUSE case EADDRINUSE: /* Address already in use */ #endif /* EADDRINUSE */ #ifdef EADDRNOTAVAIL case EADDRNOTAVAIL: /* Can't assign requested address */ #endif /* EADDRNOTAVAIL */ #ifdef ETXTBSY case ETXTBSY: /* (Apollo) file locked */ #endif /* ETXTBSY */ #if defined(ENOSR) && (!defined(ENOBUFS) || (ENOBUFS != ENOSR)) case ENOSR: /* Out of streams resources */ #endif /* defined(ENOSR) && (!defined(ENOBUFS) || (ENOBUFS != ENOSR)) */ #ifdef ENOLCK case ENOLCK: /* No locks available */ #endif /* ENOLCK */ case E_SM_OPENTIMEOUT: /* PSEUDO: open timed out */ return true; } /* nope, must be permanent */ return false; } /* ** LOCKFILE -- lock a file using flock or (shudder) fcntl locking ** ** Parameters: ** fd -- the file descriptor of the file. ** filename -- the file name (for error messages). ** ext -- the filename extension. ** type -- type of the lock. Bits can be: ** LOCK_EX -- exclusive lock. ** LOCK_NB -- non-blocking. ** LOCK_UN -- unlock. ** ** Returns: ** true if the lock was acquired. ** false otherwise. */ bool lockfile(fd, filename, ext, type) int fd; char *filename; char *ext; int type; { int i; int save_errno; # if !HASFLOCK int action; struct flock lfd; if (ext == NULL) ext = ""; memset(&lfd, '\0', sizeof(lfd)); if (bitset(LOCK_UN, type)) lfd.l_type = F_UNLCK; else if (bitset(LOCK_EX, type)) lfd.l_type = F_WRLCK; else lfd.l_type = F_RDLCK; if (bitset(LOCK_NB, type)) action = F_SETLK; else action = F_SETLKW; if (tTd(55, 60)) sm_dprintf("lockfile(%s%s, action=%d, type=%d): ", filename, ext, action, lfd.l_type); while ((i = fcntl(fd, action, &lfd)) < 0 && errno == EINTR) continue; if (i >= 0) { if (tTd(55, 60)) sm_dprintf("SUCCESS\n"); return true; } save_errno = errno; if (tTd(55, 60)) sm_dprintf("(%s) ", sm_errstring(save_errno)); /* ** On SunOS, if you are testing using -oQ/tmp/mqueue or ** -oA/tmp/aliases or anything like that, and /tmp is mounted ** as type "tmp" (that is, served from swap space), the ** previous fcntl will fail with "Invalid argument" errors. ** Since this is fairly common during testing, we will assume ** that this indicates that the lock is successfully grabbed. */ if (save_errno == EINVAL) { if (tTd(55, 60)) sm_dprintf("SUCCESS\n"); return true; } if (!bitset(LOCK_NB, type) || (save_errno != EACCES && save_errno != EAGAIN)) { int omode = fcntl(fd, F_GETFL, 0); uid_t euid = geteuid(); errno = save_errno; syserr("cannot lockf(%s%s, fd=%d, type=%o, omode=%o, euid=%d)", filename, ext, fd, type, omode, euid); dumpfd(fd, true, true); } # else /* !HASFLOCK */ if (ext == NULL) ext = ""; if (tTd(55, 60)) sm_dprintf("lockfile(%s%s, type=%o): ", filename, ext, type); while ((i = flock(fd, type)) < 0 && errno == EINTR) continue; if (i >= 0) { if (tTd(55, 60)) sm_dprintf("SUCCESS\n"); return true; } save_errno = errno; if (tTd(55, 60)) sm_dprintf("(%s) ", sm_errstring(save_errno)); if (!bitset(LOCK_NB, type) || save_errno != EWOULDBLOCK) { int omode = fcntl(fd, F_GETFL, 0); uid_t euid = geteuid(); errno = save_errno; syserr("cannot flock(%s%s, fd=%d, type=%o, omode=%o, euid=%d)", filename, ext, fd, type, omode, euid); dumpfd(fd, true, true); } # endif /* !HASFLOCK */ if (tTd(55, 60)) sm_dprintf("FAIL\n"); errno = save_errno; return false; } /* ** CHOWNSAFE -- tell if chown is "safe" (executable only by root) ** ** Unfortunately, given that we can't predict other systems on which ** a remote mounted (NFS) filesystem will be mounted, the answer is ** almost always that this is unsafe. ** ** Note also that many operating systems have non-compliant ** implementations of the _POSIX_CHOWN_RESTRICTED variable and the ** fpathconf() routine. According to IEEE 1003.1-1990, if ** _POSIX_CHOWN_RESTRICTED is defined and not equal to -1, then ** no non-root process can give away the file. However, vendors ** don't take NFS into account, so a comfortable value of ** _POSIX_CHOWN_RESTRICTED tells us nothing. ** ** Also, some systems (e.g., IRIX 6.2) return 1 from fpathconf() ** even on files where chown is not restricted. Many systems get ** this wrong on NFS-based filesystems (that is, they say that chown ** is restricted [safe] on NFS filesystems where it may not be, since ** other systems can access the same filesystem and do file giveaway; ** only the NFS server knows for sure!) Hence, it is important to ** get the value of SAFENFSPATHCONF correct -- it should be defined ** _only_ after testing (see test/t_pathconf.c) a system on an unsafe ** NFS-based filesystem to ensure that you can get meaningful results. ** If in doubt, assume unsafe! ** ** You may also need to tweak IS_SAFE_CHOWN -- it should be a ** condition indicating whether the return from pathconf indicates ** that chown is safe (typically either > 0 or >= 0 -- there isn't ** even any agreement about whether a zero return means that a file ** is or is not safe). It defaults to "> 0". ** ** If the parent directory is safe (writable only by owner back ** to the root) then we can relax slightly and trust fpathconf ** in more circumstances. This is really a crock -- if this is an ** NFS mounted filesystem then we really know nothing about the ** underlying implementation. However, most systems pessimize and ** return an error (EINVAL or EOPNOTSUPP) on NFS filesystems, which ** we interpret as unsafe, as we should. Thus, this heuristic gets ** us into a possible problem only on systems that have a broken ** pathconf implementation and which are also poorly configured ** (have :include: files in group- or world-writable directories). ** ** Parameters: ** fd -- the file descriptor to check. ** safedir -- set if the parent directory is safe. ** ** Returns: ** true -- if the chown(2) operation is "safe" -- that is, ** only root can chown the file to an arbitrary user. ** false -- if an arbitrary user can give away a file. */ #ifndef IS_SAFE_CHOWN # define IS_SAFE_CHOWN > 0 #endif /* ! IS_SAFE_CHOWN */ bool chownsafe(fd, safedir) int fd; bool safedir; { # if (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && \ (defined(_PC_CHOWN_RESTRICTED) || defined(_GNU_TYPES_H)) int rval; /* give the system administrator a chance to override */ if (bitnset(DBS_ASSUMESAFECHOWN, DontBlameSendmail)) return true; /* ** Some systems (e.g., SunOS) seem to have the call and the ** #define _PC_CHOWN_RESTRICTED, but don't actually implement ** the call. This heuristic checks for that. */ errno = 0; rval = fpathconf(fd, _PC_CHOWN_RESTRICTED); # if SAFENFSPATHCONF return errno == 0 && rval IS_SAFE_CHOWN; # else /* SAFENFSPATHCONF */ return safedir && errno == 0 && rval IS_SAFE_CHOWN; # endif /* SAFENFSPATHCONF */ # else /* (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && ... */ return bitnset(DBS_ASSUMESAFECHOWN, DontBlameSendmail); # endif /* (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && ... */ } /* ** RESETLIMITS -- reset system controlled resource limits ** ** This is to avoid denial-of-service attacks ** ** Parameters: ** none ** ** Returns: ** none */ #if HASSETRLIMIT # ifdef RLIMIT_NEEDS_SYS_TIME_H # include # endif /* RLIMIT_NEEDS_SYS_TIME_H */ # include #endif /* HASSETRLIMIT */ void resetlimits() { #if HASSETRLIMIT struct rlimit lim; lim.rlim_cur = lim.rlim_max = RLIM_INFINITY; (void) setrlimit(RLIMIT_CPU, &lim); (void) setrlimit(RLIMIT_FSIZE, &lim); # ifdef RLIMIT_NOFILE lim.rlim_cur = lim.rlim_max = FD_SETSIZE; (void) setrlimit(RLIMIT_NOFILE, &lim); # endif /* RLIMIT_NOFILE */ #else /* HASSETRLIMIT */ # if HASULIMIT (void) ulimit(2, 0x3fffff); (void) ulimit(4, FD_SETSIZE); # endif /* HASULIMIT */ #endif /* HASSETRLIMIT */ errno = 0; } /* ** SETVENDOR -- process vendor code from V configuration line ** ** Parameters: ** vendor -- string representation of vendor. ** ** Returns: ** true -- if ok. ** false -- if vendor code could not be processed. ** ** Side Effects: ** It is reasonable to set mode flags here to tweak ** processing in other parts of the code if necessary. ** For example, if you are a vendor that uses $%y to ** indicate YP lookups, you could enable that here. */ bool setvendor(vendor) char *vendor; { if (sm_strcasecmp(vendor, "Berkeley") == 0) { VendorCode = VENDOR_BERKELEY; return true; } /* add vendor extensions here */ #ifdef SUN_EXTENSIONS if (sm_strcasecmp(vendor, "Sun") == 0) { VendorCode = VENDOR_SUN; return true; } #endif /* SUN_EXTENSIONS */ #ifdef DEC if (sm_strcasecmp(vendor, "Digital") == 0) { VendorCode = VENDOR_DEC; return true; } #endif /* DEC */ #if defined(VENDOR_NAME) && defined(VENDOR_CODE) if (sm_strcasecmp(vendor, VENDOR_NAME) == 0) { VendorCode = VENDOR_CODE; return true; } #endif /* defined(VENDOR_NAME) && defined(VENDOR_CODE) */ return false; } /* ** GETVENDOR -- return vendor name based on vendor code ** ** Parameters: ** vendorcode -- numeric representation of vendor. ** ** Returns: ** string containing vendor name. */ char * getvendor(vendorcode) int vendorcode; { #if defined(VENDOR_NAME) && defined(VENDOR_CODE) /* ** Can't have the same switch case twice so need to ** handle VENDOR_CODE outside of switch. It might ** match one of the existing VENDOR_* codes. */ if (vendorcode == VENDOR_CODE) return VENDOR_NAME; #endif /* defined(VENDOR_NAME) && defined(VENDOR_CODE) */ switch (vendorcode) { case VENDOR_BERKELEY: return "Berkeley"; case VENDOR_SUN: return "Sun"; case VENDOR_HP: return "HP"; case VENDOR_IBM: return "IBM"; case VENDOR_SENDMAIL: return "Sendmail"; default: return "Unknown"; } } /* ** VENDOR_PRE_DEFAULTS, VENDOR_POST_DEFAULTS -- set vendor-specific defaults ** ** Vendor_pre_defaults is called before reading the configuration ** file; vendor_post_defaults is called immediately after. ** ** Parameters: ** e -- the global environment to initialize. ** ** Returns: ** none. */ #if SHARE_V1 int DefShareUid; /* default share uid to run as -- unused??? */ #endif /* SHARE_V1 */ void vendor_pre_defaults(e) ENVELOPE *e; { #if SHARE_V1 /* OTHERUID is defined in shares.h, do not be alarmed */ DefShareUid = OTHERUID; #endif /* SHARE_V1 */ #if defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) sun_pre_defaults(e); #endif /* defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) */ #ifdef apollo /* ** stupid domain/os can't even open ** /etc/mail/sendmail.cf without this */ sm_setuserenv("ISP", NULL); sm_setuserenv("SYSTYPE", NULL); #endif /* apollo */ } void vendor_post_defaults(e) ENVELOPE *e; { #ifdef __QNX__ /* Makes sure the SOCK environment variable remains */ sm_setuserenv("SOCK", NULL); #endif /* __QNX__ */ #if defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) sun_post_defaults(e); #endif /* defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) */ } /* ** VENDOR_DAEMON_SETUP -- special vendor setup needed for daemon mode */ void vendor_daemon_setup(e) ENVELOPE *e; { #if HASSETLOGIN (void) setlogin(RunAsUserName); #endif /* HASSETLOGIN */ #if SECUREWARE if (getluid() != -1) { usrerr("Daemon cannot have LUID"); finis(false, true, EX_USAGE); } #endif /* SECUREWARE */ } /* ** VENDOR_SET_UID -- do setup for setting a user id ** ** This is called when we are still root. ** ** Parameters: ** uid -- the uid we are about to become. ** ** Returns: ** none. */ void vendor_set_uid(uid) UID_T uid; { /* ** We need to setup the share groups (lnodes) ** and add auditing information (luid's) ** before we loose our ``root''ness. */ #if SHARE_V1 if (setupshares(uid, syserr) != 0) syserr("Unable to set up shares"); #endif /* SHARE_V1 */ #if SECUREWARE (void) setup_secure(uid); #endif /* SECUREWARE */ } /* ** VALIDATE_CONNECTION -- check connection for rationality ** ** If the connection is rejected, this routine should log an ** appropriate message -- but should never issue any SMTP protocol. ** ** Parameters: ** sap -- a pointer to a SOCKADDR naming the peer. ** hostname -- the name corresponding to sap. ** e -- the current envelope. ** ** Returns: ** error message from rejection. ** NULL if not rejected. */ #if TCPWRAPPERS # include /* tcpwrappers does no logging, but you still have to declare these -- ugh */ int allow_severity = LOG_INFO; int deny_severity = LOG_NOTICE; #endif /* TCPWRAPPERS */ char * validate_connection(sap, hostname, e) SOCKADDR *sap; char *hostname; ENVELOPE *e; { #if TCPWRAPPERS char *host; char *addr; extern int hosts_ctl(); #endif /* TCPWRAPPERS */ if (tTd(48, 3)) sm_dprintf("validate_connection(%s, %s)\n", hostname, anynet_ntoa(sap)); connection_rate_check(sap, e); if (rscheck("check_relay", hostname, anynet_ntoa(sap), e, RSF_RMCOMM|RSF_COUNT, 3, NULL, NOQID, NULL) != EX_OK) { static char reject[BUFSIZ*2]; extern char MsgBuf[]; if (tTd(48, 4)) sm_dprintf(" ... validate_connection: BAD (rscheck)\n"); if (strlen(MsgBuf) >= 3) (void) sm_strlcpy(reject, MsgBuf, sizeof(reject)); else (void) sm_strlcpy(reject, "Access denied", sizeof(reject)); return reject; } #if TCPWRAPPERS if (hostname[0] == '[' && hostname[strlen(hostname) - 1] == ']') host = "unknown"; else host = hostname; addr = anynet_ntoa(sap); # if NETINET6 /* TCP/Wrappers don't want the IPv6: protocol label */ if (addr != NULL && sm_strncasecmp(addr, "IPv6:", 5) == 0) addr += 5; # endif /* NETINET6 */ if (!hosts_ctl("sendmail", host, addr, STRING_UNKNOWN)) { if (tTd(48, 4)) sm_dprintf(" ... validate_connection: BAD (tcpwrappers)\n"); if (LogLevel > 3) sm_syslog(LOG_NOTICE, e->e_id, "tcpwrappers (%s, %s) rejection", host, addr); return "Access denied"; } #endif /* TCPWRAPPERS */ if (tTd(48, 4)) sm_dprintf(" ... validate_connection: OK\n"); return NULL; } /* ** STRTOL -- convert string to long integer ** ** For systems that don't have it in the C library. ** ** This is taken verbatim from the 4.4-Lite C library. */ #if NEEDSTRTOL # if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)strtol.c 8.1 (Berkeley) 6/4/93"; # endif /* defined(LIBC_SCCS) && !defined(lint) */ /* ** Convert a string to a long integer. ** ** Ignores `locale' stuff. Assumes that the upper and lower case ** alphabets and digits are each contiguous. */ long strtol(nptr, endptr, base) const char *nptr; char **endptr; register int base; { register const char *s = nptr; register unsigned long acc; register int c; register unsigned long cutoff; register int neg = 0, any, cutlim; /* ** Skip white space and pick up leading +/- sign if any. ** If base is 0, allow 0x for hex and 0 for octal, else ** assume decimal; if base is already 16, allow 0x. */ do { c = *s++; } while (isascii(c) && isspace(c)); if (c == '-') { neg = 1; c = *s++; } else if (c == '+') c = *s++; if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) base = c == '0' ? 8 : 10; /* ** Compute the cutoff value between legal numbers and illegal ** numbers. That is the largest legal value, divided by the ** base. An input number that is greater than this value, if ** followed by a legal input character, is too big. One that ** is equal to this value may be valid or not; the limit ** between valid and invalid numbers is then based on the last ** digit. For instance, if the range for longs is ** [-2147483648..2147483647] and the input base is 10, ** cutoff will be set to 214748364 and cutlim to either ** 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated ** a value > 214748364, or equal but the next digit is > 7 (or 8), ** the number is too big, and we will return a range error. ** ** Set any if any `digits' consumed; make it negative to indicate ** overflow. */ cutoff = neg ? -(unsigned long) LONG_MIN : LONG_MAX; cutlim = cutoff % (unsigned long) base; cutoff /= (unsigned long) base; for (acc = 0, any = 0;; c = *s++) { if (isascii(c) && isdigit(c)) c -= '0'; else if (isascii(c) && isalpha(c)) c -= isupper(c) ? 'A' - 10 : 'a' - 10; else break; if (c >= base) break; if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim) any = -1; else { any = 1; acc *= base; acc += c; } } if (any < 0) { acc = neg ? LONG_MIN : LONG_MAX; errno = ERANGE; } else if (neg) acc = -acc; if (endptr != 0) *endptr = (char *)(any ? s - 1 : nptr); return acc; } #endif /* NEEDSTRTOL */ /* ** STRSTR -- find first substring in string ** ** Parameters: ** big -- the big (full) string. ** little -- the little (sub) string. ** ** Returns: ** A pointer to the first instance of little in big. ** big if little is the null string. ** NULL if little is not contained in big. */ #if NEEDSTRSTR char * strstr(big, little) char *big; char *little; { register char *p = big; int l; if (*little == '\0') return big; l = strlen(little); while ((p = strchr(p, *little)) != NULL) { if (strncmp(p, little, l) == 0) return p; p++; } return NULL; } #endif /* NEEDSTRSTR */ /* ** SM_GETHOSTBY{NAME,ADDR} -- compatibility routines for gethostbyXXX ** ** Some operating systems have weird problems with the gethostbyXXX ** routines. For example, Solaris versions at least through 2.3 ** don't properly deliver a canonical h_name field. This tries to ** work around these problems. ** ** Support IPv6 as well as IPv4. */ #if NETINET6 && NEEDSGETIPNODE # ifndef AI_DEFAULT # define AI_DEFAULT 0 /* dummy */ # endif /* ! AI_DEFAULT */ # ifndef AI_ADDRCONFIG # define AI_ADDRCONFIG 0 /* dummy */ # endif /* ! AI_ADDRCONFIG */ # ifndef AI_V4MAPPED # define AI_V4MAPPED 0 /* dummy */ # endif /* ! AI_V4MAPPED */ # ifndef AI_ALL # define AI_ALL 0 /* dummy */ # endif /* ! AI_ALL */ static struct hostent * sm_getipnodebyname(name, family, flags, err) const char *name; int family; int flags; int *err; { bool resv6 = true; struct hostent *h; if (family == AF_INET6) { /* From RFC2133, section 6.1 */ resv6 = bitset(RES_USE_INET6, _res.options); _res.options |= RES_USE_INET6; } SM_SET_H_ERRNO(0); h = gethostbyname(name); if (!resv6) _res.options &= ~RES_USE_INET6; *err = h_errno; return h; } static struct hostent * sm_getipnodebyaddr(addr, len, family, err) const void *addr; size_t len; int family; int *err; { struct hostent *h; SM_SET_H_ERRNO(0); h = gethostbyaddr(addr, len, family); *err = h_errno; return h; } void freehostent(h) struct hostent *h; { /* ** Stub routine -- if they don't have getipnodeby*(), ** they probably don't have the free routine either. */ return; } #endif /* NETINET6 && NEEDSGETIPNODE */ struct hostent * sm_gethostbyname(name, family) char *name; int family; { int save_errno; struct hostent *h = NULL; #if (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) # if SOLARIS == 20300 || SOLARIS == 203 static struct hostent hp; static char buf[1000]; extern struct hostent *_switch_gethostbyname_r(); if (tTd(61, 10)) sm_dprintf("_switch_gethostbyname_r(%s)... ", name); h = _switch_gethostbyname_r(name, &hp, buf, sizeof(buf), &h_errno); save_errno = errno; # else /* SOLARIS == 20300 || SOLARIS == 203 */ extern struct hostent *__switch_gethostbyname(); if (tTd(61, 10)) sm_dprintf("__switch_gethostbyname(%s)... ", name); h = __switch_gethostbyname(name); save_errno = errno; # endif /* SOLARIS == 20300 || SOLARIS == 203 */ #else /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) */ int nmaps; # if NETINET6 - int flags = AI_DEFAULT|AI_ALL; +# ifndef SM_IPNODEBYNAME_FLAGS + /* For IPv4-mapped addresses, use: AI_DEFAULT|AI_ALL */ +# define SM_IPNODEBYNAME_FLAGS AI_ADDRCONFIG +# endif /* SM_IPNODEBYNAME_FLAGS */ + + int flags = SM_IPNODEBYNAME_FLAGS; int err; # endif /* NETINET6 */ char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; char hbuf[MAXNAME]; if (tTd(61, 10)) sm_dprintf("sm_gethostbyname(%s, %d)... ", name, family); # if NETINET6 # if ADDRCONFIG_IS_BROKEN flags &= ~AI_ADDRCONFIG; # endif /* ADDRCONFIG_IS_BROKEN */ h = sm_getipnodebyname(name, family, flags, &err); SM_SET_H_ERRNO(err); # else /* NETINET6 */ h = gethostbyname(name); # endif /* NETINET6 */ save_errno = errno; if (h == NULL) { if (tTd(61, 10)) sm_dprintf("failure\n"); nmaps = switch_map_find("hosts", maptype, mapreturn); while (--nmaps >= 0) { if (strcmp(maptype[nmaps], "nis") == 0 || strcmp(maptype[nmaps], "files") == 0) break; } if (nmaps >= 0) { /* try short name */ if (strlen(name) > sizeof(hbuf) - 1) { errno = save_errno; return NULL; } (void) sm_strlcpy(hbuf, name, sizeof(hbuf)); (void) shorten_hostname(hbuf); /* if it hasn't been shortened, there's no point */ if (strcmp(hbuf, name) != 0) { if (tTd(61, 10)) sm_dprintf("sm_gethostbyname(%s, %d)... ", hbuf, family); # if NETINET6 h = sm_getipnodebyname(hbuf, family, flags, &err); SM_SET_H_ERRNO(err); save_errno = errno; # else /* NETINET6 */ h = gethostbyname(hbuf); save_errno = errno; # endif /* NETINET6 */ } } } #endif /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) */ if (tTd(61, 10)) { if (h == NULL) sm_dprintf("failure\n"); else { sm_dprintf("%s\n", h->h_name); if (tTd(61, 11)) { #if NETINET6 struct in6_addr ia6; char buf6[INET6_ADDRSTRLEN]; #else /* NETINET6 */ struct in_addr ia; #endif /* NETINET6 */ size_t i; if (h->h_aliases != NULL) for (i = 0; h->h_aliases[i] != NULL; i++) sm_dprintf("\talias: %s\n", h->h_aliases[i]); for (i = 0; h->h_addr_list[i] != NULL; i++) { char *addr; #if NETINET6 memmove(&ia6, h->h_addr_list[i], IN6ADDRSZ); addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); #else /* NETINET6 */ memmove(&ia, h->h_addr_list[i], INADDRSZ); addr = (char *) inet_ntoa(ia); #endif /* NETINET6 */ if (addr != NULL) sm_dprintf("\taddr: %s\n", addr); } } } } errno = save_errno; return h; } struct hostent * sm_gethostbyaddr(addr, len, type) char *addr; int len; int type; { struct hostent *hp; #if NETINET6 if (type == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED((struct in6_addr *) addr)) { /* Avoid reverse lookup for IPv6 unspecified address */ SM_SET_H_ERRNO(HOST_NOT_FOUND); return NULL; } #endif /* NETINET6 */ #if (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) # if SOLARIS == 20300 || SOLARIS == 203 { static struct hostent he; static char buf[1000]; extern struct hostent *_switch_gethostbyaddr_r(); hp = _switch_gethostbyaddr_r(addr, len, type, &he, buf, sizeof(buf), &h_errno); } # else /* SOLARIS == 20300 || SOLARIS == 203 */ { extern struct hostent *__switch_gethostbyaddr(); hp = __switch_gethostbyaddr(addr, len, type); } # endif /* SOLARIS == 20300 || SOLARIS == 203 */ #else /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) */ # if NETINET6 { int err; hp = sm_getipnodebyaddr(addr, len, type, &err); SM_SET_H_ERRNO(err); } # else /* NETINET6 */ hp = gethostbyaddr(addr, len, type); # endif /* NETINET6 */ #endif /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) */ return hp; } /* ** SM_GETPW{NAM,UID} -- wrapper for getpwnam and getpwuid */ struct passwd * sm_getpwnam(user) char *user; { #ifdef _AIX4 extern struct passwd *_getpwnam_shadow(const char *, const int); return _getpwnam_shadow(user, 0); #else /* _AIX4 */ return getpwnam(user); #endif /* _AIX4 */ } struct passwd * sm_getpwuid(uid) UID_T uid; { #if defined(_AIX4) && 0 extern struct passwd *_getpwuid_shadow(const int, const int); return _getpwuid_shadow(uid,0); #else /* defined(_AIX4) && 0 */ return getpwuid(uid); #endif /* defined(_AIX4) && 0 */ } /* ** SECUREWARE_SETUP_SECURE -- Convex SecureWare setup ** ** Set up the trusted computing environment for C2 level security ** under SecureWare. ** ** Parameters: ** uid -- uid of the user to initialize in the TCB ** ** Returns: ** none ** ** Side Effects: ** Initialized the user in the trusted computing base */ #if SECUREWARE # include # include void secureware_setup_secure(uid) UID_T uid; { int rc; if (getluid() != -1) return; if ((rc = set_secure_info(uid)) != SSI_GOOD_RETURN) { switch (rc) { case SSI_NO_PRPW_ENTRY: syserr("No protected passwd entry, uid = %d", (int) uid); break; case SSI_LOCKED: syserr("Account has been disabled, uid = %d", (int) uid); break; case SSI_RETIRED: syserr("Account has been retired, uid = %d", (int) uid); break; case SSI_BAD_SET_LUID: syserr("Could not set LUID, uid = %d", (int) uid); break; case SSI_BAD_SET_PRIVS: syserr("Could not set kernel privs, uid = %d", (int) uid); default: syserr("Unknown return code (%d) from set_secure_info(%d)", rc, (int) uid); break; } finis(false, true, EX_NOPERM); } } #endif /* SECUREWARE */ /* ** ADD_HOSTNAMES -- Add a hostname to class 'w' based on IP address ** ** Add hostnames to class 'w' based on the IP address read from ** the network interface. ** ** Parameters: ** sa -- a pointer to a SOCKADDR containing the address ** ** Returns: ** 0 if successful, -1 if host lookup fails. */ static int add_hostnames(sa) SOCKADDR *sa; { struct hostent *hp; char **ha; char hnb[MAXHOSTNAMELEN]; /* lookup name with IP address */ switch (sa->sa.sa_family) { #if NETINET case AF_INET: hp = sm_gethostbyaddr((char *) &sa->sin.sin_addr, sizeof(sa->sin.sin_addr), sa->sa.sa_family); break; #endif /* NETINET */ #if NETINET6 case AF_INET6: hp = sm_gethostbyaddr((char *) &sa->sin6.sin6_addr, sizeof(sa->sin6.sin6_addr), sa->sa.sa_family); break; #endif /* NETINET6 */ default: /* Give warning about unsupported family */ if (LogLevel > 3) sm_syslog(LOG_WARNING, NOQID, "Unsupported address family %d: %.100s", sa->sa.sa_family, anynet_ntoa(sa)); return -1; } if (hp == NULL) { int save_errno = errno; if (LogLevel > 3 && #if NETINET && defined(IN_LINKLOCAL) !(sa->sa.sa_family == AF_INET && IN_LINKLOCAL(ntohl(sa->sin.sin_addr.s_addr))) && #endif /* NETINET && defined(IN_LINKLOCAL) */ #if NETINET6 !(sa->sa.sa_family == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr)) && #endif /* NETINET6 */ true) sm_syslog(LOG_WARNING, NOQID, "gethostbyaddr(%.100s) failed: %d", anynet_ntoa(sa), #if NAMED_BIND h_errno #else /* NAMED_BIND */ -1 #endif /* NAMED_BIND */ ); errno = save_errno; return -1; } /* save its cname */ if (!wordinclass((char *) hp->h_name, 'w')) { setclass('w', (char *) hp->h_name); if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", hp->h_name); if (sm_snprintf(hnb, sizeof(hnb), "[%s]", hp->h_name) < sizeof(hnb) && !wordinclass((char *) hnb, 'w')) setclass('w', hnb); } else { if (tTd(0, 43)) sm_dprintf("\ta.k.a.: %s (already in $=w)\n", hp->h_name); } /* save all it aliases name */ for (ha = hp->h_aliases; ha != NULL && *ha != NULL; ha++) { if (!wordinclass(*ha, 'w')) { setclass('w', *ha); if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", *ha); if (sm_snprintf(hnb, sizeof(hnb), "[%s]", *ha) < sizeof(hnb) && !wordinclass((char *) hnb, 'w')) setclass('w', hnb); } else { if (tTd(0, 43)) sm_dprintf("\ta.k.a.: %s (already in $=w)\n", *ha); } } #if NETINET6 freehostent(hp); #endif /* NETINET6 */ return 0; } /* ** LOAD_IF_NAMES -- load interface-specific names into $=w ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** Loads $=w with the names of all the interfaces. */ #if !NETINET # define SIOCGIFCONF_IS_BROKEN 1 /* XXX */ #endif /* !NETINET */ #if defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN struct rtentry; struct mbuf; # ifndef SUNOS403 # include # endif /* ! SUNOS403 */ # if (_AIX4 >= 40300) && !defined(_NET_IF_H) # undef __P # endif /* (_AIX4 >= 40300) && !defined(_NET_IF_H) */ # include #endif /* defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN */ void load_if_names() { # if NETINET6 && defined(SIOCGLIFCONF) # ifdef __hpux /* ** Unfortunately, HP has changed all of the structures, ** making life difficult for implementors. */ # define lifconf if_laddrconf # define lifc_len iflc_len # define lifc_buf iflc_buf # define lifreq if_laddrreq # define lifr_addr iflr_addr # define lifr_name iflr_name # define lifr_flags iflr_flags # define ss_family sa_family # undef SIOCGLIFNUM # endif /* __hpux */ int s; int i; size_t len; int numifs; char *buf; struct lifconf lifc; # ifdef SIOCGLIFNUM struct lifnum lifn; # endif /* SIOCGLIFNUM */ s = socket(InetMode, SOCK_DGRAM, 0); if (s == -1) return; /* get the list of known IP address from the kernel */ # ifdef __hpux i = ioctl(s, SIOCGIFNUM, (char *) &numifs); # endif /* __hpux */ # ifdef SIOCGLIFNUM lifn.lifn_family = AF_UNSPEC; lifn.lifn_flags = 0; i = ioctl(s, SIOCGLIFNUM, (char *)&lifn); numifs = lifn.lifn_count; # endif /* SIOCGLIFNUM */ # if defined(__hpux) || defined(SIOCGLIFNUM) if (i < 0) { /* can't get number of interfaces -- fall back */ if (tTd(0, 4)) sm_dprintf("SIOCGLIFNUM failed: %s\n", sm_errstring(errno)); numifs = -1; } else if (tTd(0, 42)) sm_dprintf("system has %d interfaces\n", numifs); if (numifs < 0) # endif /* defined(__hpux) || defined(SIOCGLIFNUM) */ numifs = MAXINTERFACES; if (numifs <= 0) { (void) close(s); return; } len = lifc.lifc_len = numifs * sizeof(struct lifreq); buf = lifc.lifc_buf = xalloc(lifc.lifc_len); # ifndef __hpux lifc.lifc_family = AF_UNSPEC; lifc.lifc_flags = 0; # endif /* ! __hpux */ if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) { if (tTd(0, 4)) sm_dprintf("SIOCGLIFCONF failed: %s\n", sm_errstring(errno)); (void) close(s); sm_free(buf); return; } /* scan the list of IP address */ if (tTd(0, 40)) sm_dprintf("scanning for interface specific names, lifc_len=%ld\n", (long) len); for (i = 0; i < len && i >= 0; ) { int flags; struct lifreq *ifr = (struct lifreq *)&buf[i]; SOCKADDR *sa = (SOCKADDR *) &ifr->lifr_addr; int af = ifr->lifr_addr.ss_family; char *addr; char *name; struct in6_addr ia6; struct in_addr ia; # ifdef SIOCGLIFFLAGS struct lifreq ifrf; # endif /* SIOCGLIFFLAGS */ char ip_addr[256]; char buf6[INET6_ADDRSTRLEN]; /* ** We must close and recreate the socket each time ** since we don't know what type of socket it is now ** (each status function may change it). */ (void) close(s); s = socket(af, SOCK_DGRAM, 0); if (s == -1) { sm_free(buf); /* XXX */ return; } /* ** If we don't have a complete ifr structure, ** don't try to use it. */ if ((len - i) < sizeof(*ifr)) break; # ifdef BSD4_4_SOCKADDR if (sa->sa.sa_len > sizeof(ifr->lifr_addr)) i += sizeof(ifr->lifr_name) + sa->sa.sa_len; else # endif /* BSD4_4_SOCKADDR */ # ifdef DEC /* fix for IPv6 size differences */ i += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len); # else /* DEC */ i += sizeof(*ifr); # endif /* DEC */ if (tTd(0, 20)) sm_dprintf("%s\n", anynet_ntoa(sa)); if (af != AF_INET && af != AF_INET6) continue; # ifdef SIOCGLIFFLAGS memset(&ifrf, '\0', sizeof(struct lifreq)); (void) sm_strlcpy(ifrf.lifr_name, ifr->lifr_name, sizeof(ifrf.lifr_name)); if (ioctl(s, SIOCGLIFFLAGS, (char *) &ifrf) < 0) { if (tTd(0, 4)) sm_dprintf("SIOCGLIFFLAGS failed: %s\n", sm_errstring(errno)); continue; } name = ifr->lifr_name; flags = ifrf.lifr_flags; if (tTd(0, 41)) sm_dprintf("\tflags: %lx\n", (unsigned long) flags); if (!bitset(IFF_UP, flags)) continue; # endif /* SIOCGLIFFLAGS */ ip_addr[0] = '\0'; /* extract IP address from the list*/ switch (af) { case AF_INET6: SETV6LOOPBACKADDRFOUND(*sa); # ifdef __KAME__ /* convert into proper scoped address */ if ((IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr) || IN6_IS_ADDR_SITELOCAL(&sa->sin6.sin6_addr)) && sa->sin6.sin6_scope_id == 0) { struct in6_addr *ia6p; ia6p = &sa->sin6.sin6_addr; sa->sin6.sin6_scope_id = ntohs(ia6p->s6_addr[3] | ((unsigned int)ia6p->s6_addr[2] << 8)); ia6p->s6_addr[2] = ia6p->s6_addr[3] = 0; } # endif /* __KAME__ */ ia6 = sa->sin6.sin6_addr; if (IN6_IS_ADDR_UNSPECIFIED(&ia6)) { addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); message("WARNING: interface %s is UP with %s address", name, addr == NULL ? "(NULL)" : addr); continue; } /* save IP address in text from */ addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); if (addr != NULL) (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]", (int) sizeof(ip_addr) - 3, addr); break; case AF_INET: ia = sa->sin.sin_addr; if (ia.s_addr == INADDR_ANY || ia.s_addr == INADDR_NONE) { message("WARNING: interface %s is UP with %s address", name, inet_ntoa(ia)); continue; } /* save IP address in text from */ (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]", (int) sizeof(ip_addr) - 3, inet_ntoa(ia)); break; } if (*ip_addr == '\0') continue; if (!wordinclass(ip_addr, 'w')) { setclass('w', ip_addr); if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", ip_addr); } # ifdef SIOCGLIFFLAGS /* skip "loopback" interface "lo" */ if (DontProbeInterfaces == DPI_SKIPLOOPBACK && bitset(IFF_LOOPBACK, flags)) continue; # endif /* SIOCGLIFFLAGS */ (void) add_hostnames(sa); } sm_free(buf); /* XXX */ (void) close(s); # else /* NETINET6 && defined(SIOCGLIFCONF) */ # if defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN int s; int i; struct ifconf ifc; int numifs; s = socket(AF_INET, SOCK_DGRAM, 0); if (s == -1) return; /* get the list of known IP address from the kernel */ # if defined(SIOCGIFNUM) && !SIOCGIFNUM_IS_BROKEN if (ioctl(s, SIOCGIFNUM, (char *) &numifs) < 0) { /* can't get number of interfaces -- fall back */ if (tTd(0, 4)) sm_dprintf("SIOCGIFNUM failed: %s\n", sm_errstring(errno)); numifs = -1; } else if (tTd(0, 42)) sm_dprintf("system has %d interfaces\n", numifs); if (numifs < 0) # endif /* defined(SIOCGIFNUM) && !SIOCGIFNUM_IS_BROKEN */ numifs = MAXINTERFACES; if (numifs <= 0) { (void) close(s); return; } ifc.ifc_len = numifs * sizeof(struct ifreq); ifc.ifc_buf = xalloc(ifc.ifc_len); if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) { if (tTd(0, 4)) sm_dprintf("SIOCGIFCONF failed: %s\n", sm_errstring(errno)); (void) close(s); return; } /* scan the list of IP address */ if (tTd(0, 40)) sm_dprintf("scanning for interface specific names, ifc_len=%d\n", ifc.ifc_len); for (i = 0; i < ifc.ifc_len && i >= 0; ) { int af; struct ifreq *ifr = (struct ifreq *) &ifc.ifc_buf[i]; SOCKADDR *sa = (SOCKADDR *) &ifr->ifr_addr; # if NETINET6 char *addr; struct in6_addr ia6; # endif /* NETINET6 */ struct in_addr ia; # ifdef SIOCGIFFLAGS struct ifreq ifrf; # endif /* SIOCGIFFLAGS */ char ip_addr[256]; # if NETINET6 char buf6[INET6_ADDRSTRLEN]; # endif /* NETINET6 */ /* ** If we don't have a complete ifr structure, ** don't try to use it. */ if ((ifc.ifc_len - i) < sizeof(*ifr)) break; # ifdef BSD4_4_SOCKADDR if (sa->sa.sa_len > sizeof(ifr->ifr_addr)) i += sizeof(ifr->ifr_name) + sa->sa.sa_len; else # endif /* BSD4_4_SOCKADDR */ i += sizeof(*ifr); if (tTd(0, 20)) sm_dprintf("%s\n", anynet_ntoa(sa)); af = ifr->ifr_addr.sa_family; if (af != AF_INET # if NETINET6 && af != AF_INET6 # endif /* NETINET6 */ ) continue; # ifdef SIOCGIFFLAGS memset(&ifrf, '\0', sizeof(struct ifreq)); (void) sm_strlcpy(ifrf.ifr_name, ifr->ifr_name, sizeof(ifrf.ifr_name)); (void) ioctl(s, SIOCGIFFLAGS, (char *) &ifrf); if (tTd(0, 41)) sm_dprintf("\tflags: %lx\n", (unsigned long) ifrf.ifr_flags); # define IFRFREF ifrf # else /* SIOCGIFFLAGS */ # define IFRFREF (*ifr) # endif /* SIOCGIFFLAGS */ if (!bitset(IFF_UP, IFRFREF.ifr_flags)) continue; ip_addr[0] = '\0'; /* extract IP address from the list*/ switch (af) { case AF_INET: ia = sa->sin.sin_addr; if (ia.s_addr == INADDR_ANY || ia.s_addr == INADDR_NONE) { message("WARNING: interface %s is UP with %s address", ifr->ifr_name, inet_ntoa(ia)); continue; } /* save IP address in text from */ (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]", (int) sizeof(ip_addr) - 3, inet_ntoa(ia)); break; # if NETINET6 case AF_INET6: SETV6LOOPBACKADDRFOUND(*sa); # ifdef __KAME__ /* convert into proper scoped address */ if ((IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr) || IN6_IS_ADDR_SITELOCAL(&sa->sin6.sin6_addr)) && sa->sin6.sin6_scope_id == 0) { struct in6_addr *ia6p; ia6p = &sa->sin6.sin6_addr; sa->sin6.sin6_scope_id = ntohs(ia6p->s6_addr[3] | ((unsigned int)ia6p->s6_addr[2] << 8)); ia6p->s6_addr[2] = ia6p->s6_addr[3] = 0; } # endif /* __KAME__ */ ia6 = sa->sin6.sin6_addr; if (IN6_IS_ADDR_UNSPECIFIED(&ia6)) { addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); message("WARNING: interface %s is UP with %s address", ifr->ifr_name, addr == NULL ? "(NULL)" : addr); continue; } /* save IP address in text from */ addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); if (addr != NULL) (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]", (int) sizeof(ip_addr) - 3, addr); break; # endif /* NETINET6 */ } if (ip_addr[0] == '\0') continue; if (!wordinclass(ip_addr, 'w')) { setclass('w', ip_addr); if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", ip_addr); } /* skip "loopback" interface "lo" */ if (DontProbeInterfaces == DPI_SKIPLOOPBACK && bitset(IFF_LOOPBACK, IFRFREF.ifr_flags)) continue; (void) add_hostnames(sa); } sm_free(ifc.ifc_buf); /* XXX */ (void) close(s); # undef IFRFREF # endif /* defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN */ # endif /* NETINET6 && defined(SIOCGLIFCONF) */ } /* ** ISLOOPBACK -- is socket address in the loopback net? ** ** Parameters: ** sa -- socket address. ** ** Returns: ** true -- is socket address in the loopback net? ** false -- otherwise ** */ bool isloopback(sa) SOCKADDR sa; { #if NETINET6 if (IN6_IS_ADDR_LOOPBACK(&sa.sin6.sin6_addr)) return true; #else /* NETINET6 */ /* XXX how to correctly extract IN_LOOPBACKNET part? */ if (((ntohl(sa.sin.sin_addr.s_addr) & IN_CLASSA_NET) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) return true; #endif /* NETINET6 */ return false; } /* ** GET_NUM_PROCS_ONLINE -- return the number of processors currently online ** ** Parameters: ** none. ** ** Returns: ** The number of processors online. */ static int get_num_procs_online() { int nproc = 0; #ifdef USESYSCTL # if defined(CTL_HW) && defined(HW_NCPU) size_t sz; int mib[2]; mib[0] = CTL_HW; mib[1] = HW_NCPU; sz = (size_t) sizeof(nproc); (void) sysctl(mib, 2, &nproc, &sz, NULL, 0); # endif /* defined(CTL_HW) && defined(HW_NCPU) */ #else /* USESYSCTL */ # ifdef _SC_NPROCESSORS_ONLN nproc = (int) sysconf(_SC_NPROCESSORS_ONLN); # else /* _SC_NPROCESSORS_ONLN */ # ifdef __hpux # include struct pst_dynamic psd; if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) != -1) nproc = psd.psd_proc_cnt; # endif /* __hpux */ # endif /* _SC_NPROCESSORS_ONLN */ #endif /* USESYSCTL */ if (nproc <= 0) nproc = 1; return nproc; } /* ** SM_CLOSEFROM -- close file descriptors ** ** Parameters: ** lowest -- first fd to close ** highest -- last fd + 1 to close ** ** Returns: ** none */ void sm_closefrom(lowest, highest) int lowest, highest; { #if HASCLOSEFROM closefrom(lowest); #else /* HASCLOSEFROM */ int i; for (i = lowest; i < highest; i++) (void) close(i); #endif /* HASCLOSEFROM */ } #if HASFDWALK /* ** CLOSEFD_WALK -- walk fd's arranging to close them ** Callback for fdwalk() ** ** Parameters: ** lowest -- first fd to arrange to be closed ** fd -- fd to arrange to be closed ** ** Returns: ** zero */ static int closefd_walk(lowest, fd) void *lowest; int fd; { if (fd >= *(int *)lowest) (void) fcntl(fd, F_SETFD, FD_CLOEXEC); return 0; } #endif /* HASFDWALK */ /* ** SM_CLOSE_ON_EXEC -- arrange for file descriptors to be closed ** ** Parameters: ** lowest -- first fd to arrange to be closed ** highest -- last fd + 1 to arrange to be closed ** ** Returns: ** none */ void sm_close_on_exec(highest, lowest) int highest, lowest; { #if HASFDWALK (void) fdwalk(closefd_walk, &lowest); #else /* HASFDWALK */ int i, j; for (i = lowest; i < highest; i++) { if ((j = fcntl(i, F_GETFD, 0)) != -1) (void) fcntl(i, F_SETFD, j | FD_CLOEXEC); } #endif /* HASFDWALK */ } /* ** SEED_RANDOM -- seed the random number generator ** ** Parameters: ** none ** ** Returns: ** none */ void seed_random() { #if HASSRANDOMDEV srandomdev(); #else /* HASSRANDOMDEV */ long seed; struct timeval t; seed = (long) CurrentPid; if (gettimeofday(&t, NULL) >= 0) seed += t.tv_sec + t.tv_usec; # if HASRANDOM (void) srandom(seed); # else /* HASRANDOM */ (void) srand((unsigned int) seed); # endif /* HASRANDOM */ #endif /* HASSRANDOMDEV */ } /* ** SM_SYSLOG -- syslog wrapper to keep messages under SYSLOG_BUFSIZE ** ** Parameters: ** level -- syslog level ** id -- envelope ID or NULL (NOQUEUE) ** fmt -- format string ** arg... -- arguments as implied by fmt. ** ** Returns: ** none */ /* VARARGS3 */ void #ifdef __STDC__ sm_syslog(int level, const char *id, const char *fmt, ...) #else /* __STDC__ */ sm_syslog(level, id, fmt, va_alist) int level; const char *id; const char *fmt; va_dcl #endif /* __STDC__ */ { char *buf; size_t bufsize; char *begin, *end; int save_errno; int seq = 1; int idlen; char buf0[MAXLINE]; char *newstring; extern int SyslogPrefixLen; SM_VA_LOCAL_DECL save_errno = errno; if (id == NULL) id = "NOQUEUE"; idlen = strlen(id) + SyslogPrefixLen; buf = buf0; bufsize = sizeof(buf0); for (;;) { int n; /* print log message into buf */ SM_VA_START(ap, fmt); n = sm_vsnprintf(buf, bufsize, fmt, ap); SM_VA_END(ap); SM_ASSERT(n > 0); if (n < bufsize) break; /* String too small, redo with correct size */ bufsize = n + 1; if (buf != buf0) { sm_free(buf); buf = NULL; } buf = sm_malloc_x(bufsize); } /* clean up buf after it has been expanded with args */ newstring = str2prt(buf); if ((strlen(newstring) + idlen + 1) < SYSLOG_BUFSIZE) { #if LOG if (*id == '\0') { if (tTd(89, 10)) { struct timeval tv; gettimeofday(&tv, NULL); sm_dprintf("%ld.%06ld %s\n", (long) tv.tv_sec, (long) tv.tv_usec, newstring); } else if (tTd(89, 8)) sm_dprintf("%s\n", newstring); else syslog(level, "%s", newstring); } else { if (tTd(89, 10)) { struct timeval tv; gettimeofday(&tv, NULL); sm_dprintf("%ld.%06ld %s: %s\n", (long) tv.tv_sec, (long) tv.tv_usec, id, newstring); } else if (tTd(89, 8)) sm_dprintf("%s: %s\n", id, newstring); else syslog(level, "%s: %s", id, newstring); } #else /* LOG */ /*XXX should do something more sensible */ if (*id == '\0') (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s\n", newstring); else (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: %s\n", id, newstring); #endif /* LOG */ if (buf != buf0) sm_free(buf); errno = save_errno; return; } /* ** additional length for splitting: " ..." + 3, where 3 is magic to ** have some data for the next entry. */ #define SL_SPLIT 7 begin = newstring; idlen += 5; /* strlen("[999]"), see below */ while (*begin != '\0' && (strlen(begin) + idlen) > SYSLOG_BUFSIZE) { char save; if (seq >= 999) { /* Too many messages */ break; } end = begin + SYSLOG_BUFSIZE - idlen - SL_SPLIT; while (end > begin) { /* Break on comma or space */ if (*end == ',' || *end == ' ') { end++; /* Include separator */ break; } end--; } /* No separator, break midstring... */ if (end == begin) end = begin + SYSLOG_BUFSIZE - idlen - SL_SPLIT; save = *end; *end = 0; #if LOG if (tTd(89, 8)) sm_dprintf("%s[%d]: %s ...\n", id, seq++, begin); else syslog(level, "%s[%d]: %s ...", id, seq++, begin); #else /* LOG */ (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s[%d]: %s ...\n", id, seq++, begin); #endif /* LOG */ *end = save; begin = end; } if (seq >= 999) { #if LOG if (tTd(89, 8)) sm_dprintf("%s[%d]: log terminated, too many parts\n", id, seq); else syslog(level, "%s[%d]: log terminated, too many parts", id, seq); #else /* LOG */ (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s[%d]: log terminated, too many parts\n", id, seq); #endif /* LOG */ } else if (*begin != '\0') { #if LOG if (tTd(89, 8)) sm_dprintf("%s[%d]: %s\n", id, seq, begin); else syslog(level, "%s[%d]: %s", id, seq, begin); #else /* LOG */ (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s[%d]: %s\n", id, seq, begin); #endif /* LOG */ } if (buf != buf0) sm_free(buf); errno = save_errno; } /* ** HARD_SYSLOG -- call syslog repeatedly until it works ** ** Needed on HP-UX, which apparently doesn't guarantee that ** syslog succeeds during interrupt handlers. */ #if defined(__hpux) && !defined(HPUX11) # define MAXSYSLOGTRIES 100 # undef syslog # ifdef V4FS # define XCNST const # define CAST (const char *) # else /* V4FS */ # define XCNST # define CAST # endif /* V4FS */ void # ifdef __STDC__ hard_syslog(int pri, XCNST char *msg, ...) # else /* __STDC__ */ hard_syslog(pri, msg, va_alist) int pri; XCNST char *msg; va_dcl # endif /* __STDC__ */ { int i; char buf[SYSLOG_BUFSIZE]; SM_VA_LOCAL_DECL SM_VA_START(ap, msg); (void) sm_vsnprintf(buf, sizeof(buf), msg, ap); SM_VA_END(ap); for (i = MAXSYSLOGTRIES; --i >= 0 && syslog(pri, CAST "%s", buf) < 0; ) continue; } # undef CAST #endif /* defined(__hpux) && !defined(HPUX11) */ #if NEEDLOCAL_HOSTNAME_LENGTH /* ** LOCAL_HOSTNAME_LENGTH ** ** This is required to get sendmail to compile against BIND 4.9.x ** on Ultrix. ** ** Unfortunately, a Compaq Y2K patch kit provides it without ** bumping __RES in /usr/include/resolv.h so we can't automatically ** figure out whether it is needed. */ int local_hostname_length(hostname) char *hostname; { size_t len_host, len_domain; if (!*_res.defdname) res_init(); len_host = strlen(hostname); len_domain = strlen(_res.defdname); if (len_host > len_domain && (sm_strcasecmp(hostname + len_host - len_domain, _res.defdname) == 0) && hostname[len_host - len_domain - 1] == '.') return len_host - len_domain - 1; else return 0; } #endif /* NEEDLOCAL_HOSTNAME_LENGTH */ #if NEEDLINK /* ** LINK -- clone a file ** ** Some OS's lacks link() and hard links. Since sendmail is using ** link() as an efficient way to clone files, this implementation ** will simply do a file copy. ** ** NOTE: This link() replacement is not a generic replacement as it ** does not handle all of the semantics of the real link(2). ** ** Parameters: ** source -- pathname of existing file. ** target -- pathname of link (clone) to be created. ** ** Returns: ** 0 -- success. ** -1 -- failure, see errno for details. */ int link(source, target) const char *source; const char *target; { int save_errno; int sff; int src = -1, dst = -1; ssize_t readlen; ssize_t writelen; char buf[BUFSIZ]; struct stat st; sff = SFF_REGONLY|SFF_OPENASROOT; if (DontLockReadFiles) sff |= SFF_NOLOCK; /* Open the original file */ src = safeopen((char *)source, O_RDONLY, 0, sff); if (src < 0) goto fail; /* Obtain the size and the mode */ if (fstat(src, &st) < 0) goto fail; /* Create the duplicate copy */ sff &= ~SFF_NOLOCK; sff |= SFF_CREAT; dst = safeopen((char *)target, O_CREAT|O_EXCL|O_WRONLY, st.st_mode, sff); if (dst < 0) goto fail; /* Copy all of the bytes one buffer at a time */ while ((readlen = read(src, &buf, sizeof(buf))) > 0) { ssize_t left = readlen; char *p = buf; while (left > 0 && (writelen = write(dst, p, (size_t) left)) >= 0) { left -= writelen; p += writelen; } if (writelen < 0) break; } /* Any trouble reading? */ if (readlen < 0 || writelen < 0) goto fail; /* Close the input file */ if (close(src) < 0) { src = -1; goto fail; } src = -1; /* Close the output file */ if (close(dst) < 0) { /* don't set dst = -1 here so we unlink the file */ goto fail; } /* Success */ return 0; fail: save_errno = errno; if (src >= 0) (void) close(src); if (dst >= 0) { (void) unlink(target); (void) close(dst); } errno = save_errno; return -1; } #endif /* NEEDLINK */ /* ** Compile-Time options */ char *CompileOptions[] = { #if ALLOW_255 "ALLOW_255", #endif /* ALLOW_255 */ #if NAMED_BIND # if DNSMAP "DNSMAP", # endif /* DNSMAP */ #endif /* NAMED_BIND */ #if EGD "EGD", #endif /* EGD */ #if HESIOD "HESIOD", #endif /* HESIOD */ #if HES_GETMAILHOST "HES_GETMAILHOST", #endif /* HES_GETMAILHOST */ #if LDAPMAP "LDAPMAP", #endif /* LDAPMAP */ #if LDAP_REFERRALS "LDAP_REFERRALS", #endif /* LDAP_REFERRALS */ #if LOG "LOG", #endif /* LOG */ #if MAP_NSD "MAP_NSD", #endif /* MAP_NSD */ #if MAP_REGEX "MAP_REGEX", #endif /* MAP_REGEX */ #if MATCHGECOS "MATCHGECOS", #endif /* MATCHGECOS */ #if MILTER "MILTER", #endif /* MILTER */ #if MIME7TO8 "MIME7TO8", #endif /* MIME7TO8 */ #if MIME7TO8_OLD "MIME7TO8_OLD", #endif /* MIME7TO8_OLD */ #if MIME8TO7 "MIME8TO7", #endif /* MIME8TO7 */ #if NAMED_BIND "NAMED_BIND", #endif /* NAMED_BIND */ #if NDBM "NDBM", #endif /* NDBM */ #if NETINET "NETINET", #endif /* NETINET */ #if NETINET6 "NETINET6", #endif /* NETINET6 */ #if NETINFO "NETINFO", #endif /* NETINFO */ #if NETISO "NETISO", #endif /* NETISO */ #if NETNS "NETNS", #endif /* NETNS */ #if NETUNIX "NETUNIX", #endif /* NETUNIX */ #if NETX25 "NETX25", #endif /* NETX25 */ #if NEWDB "NEWDB", #endif /* NEWDB */ #if NIS "NIS", #endif /* NIS */ #if NISPLUS "NISPLUS", #endif /* NISPLUS */ #if NO_DH "NO_DH", #endif /* NO_DH */ #if PH_MAP "PH_MAP", #endif /* PH_MAP */ #ifdef PICKY_HELO_CHECK "PICKY_HELO_CHECK", #endif /* PICKY_HELO_CHECK */ #if PIPELINING "PIPELINING", #endif /* PIPELINING */ #if SASL # if SASL >= 20000 "SASLv2", # else /* SASL >= 20000 */ "SASL", # endif /* SASL >= 20000 */ #endif /* SASL */ #if SCANF "SCANF", #endif /* SCANF */ #if SM_LDAP_ERROR_ON_MISSING_ARGS "SM_LDAP_ERROR_ON_MISSING_ARGS", #endif /* SM_LDAP_ERROR_ON_MISSING_ARGS */ #if SMTPDEBUG "SMTPDEBUG", #endif /* SMTPDEBUG */ #if SOCKETMAP "SOCKETMAP", #endif /* SOCKETMAP */ #if STARTTLS "STARTTLS", #endif /* STARTTLS */ #if SUID_ROOT_FILES_OK "SUID_ROOT_FILES_OK", #endif /* SUID_ROOT_FILES_OK */ #if TCPWRAPPERS "TCPWRAPPERS", #endif /* TCPWRAPPERS */ #if TLS_NO_RSA "TLS_NO_RSA", #endif /* TLS_NO_RSA */ #if TLS_VRFY_PER_CTX "TLS_VRFY_PER_CTX", #endif /* TLS_VRFY_PER_CTX */ #if USERDB "USERDB", #endif /* USERDB */ #if USE_LDAP_INIT "USE_LDAP_INIT", #endif /* USE_LDAP_INIT */ #if USE_TTYPATH "USE_TTYPATH", #endif /* USE_TTYPATH */ #if XDEBUG "XDEBUG", #endif /* XDEBUG */ #if XLA "XLA", #endif /* XLA */ NULL }; /* ** OS compile options. */ char *OsCompileOptions[] = { #if ADDRCONFIG_IS_BROKEN "ADDRCONFIG_IS_BROKEN", #endif /* ADDRCONFIG_IS_BROKEN */ #ifdef AUTO_NETINFO_HOSTS "AUTO_NETINFO_HOSTS", #endif /* AUTO_NETINFO_HOSTS */ #ifdef AUTO_NIS_ALIASES "AUTO_NIS_ALIASES", #endif /* AUTO_NIS_ALIASES */ #if BROKEN_RES_SEARCH "BROKEN_RES_SEARCH", #endif /* BROKEN_RES_SEARCH */ #ifdef BSD4_4_SOCKADDR "BSD4_4_SOCKADDR", #endif /* BSD4_4_SOCKADDR */ #if BOGUS_O_EXCL "BOGUS_O_EXCL", #endif /* BOGUS_O_EXCL */ #if DEC_OSF_BROKEN_GETPWENT "DEC_OSF_BROKEN_GETPWENT", #endif /* DEC_OSF_BROKEN_GETPWENT */ #if FAST_PID_RECYCLE "FAST_PID_RECYCLE", #endif /* FAST_PID_RECYCLE */ #if HASCLOSEFROM "HASCLOSEFROM", #endif /* HASCLOSEFROM */ #if HASFCHOWN "HASFCHOWN", #endif /* HASFCHOWN */ #if HASFCHMOD "HASFCHMOD", #endif /* HASFCHMOD */ #if HASFDWALK "HASFDWALK", #endif /* HASFDWALK */ #if HASFLOCK "HASFLOCK", #endif /* HASFLOCK */ #if HASGETDTABLESIZE "HASGETDTABLESIZE", #endif /* HASGETDTABLESIZE */ #if HASGETUSERSHELL "HASGETUSERSHELL", #endif /* HASGETUSERSHELL */ #if HASINITGROUPS "HASINITGROUPS", #endif /* HASINITGROUPS */ #if HASLDAPGETALIASBYNAME "HASLDAPGETALIASBYNAME", #endif /* HASLDAPGETALIASBYNAME */ #if HASLSTAT "HASLSTAT", #endif /* HASLSTAT */ #if HASNICE "HASNICE", #endif /* HASNICE */ #if HASRANDOM "HASRANDOM", #endif /* HASRANDOM */ #if HASRRESVPORT "HASRRESVPORT", #endif /* HASRRESVPORT */ #if HASSETEGID "HASSETEGID", #endif /* HASSETEGID */ #if HASSETLOGIN "HASSETLOGIN", #endif /* HASSETLOGIN */ #if HASSETREGID "HASSETREGID", #endif /* HASSETREGID */ #if HASSETRESGID "HASSETRESGID", #endif /* HASSETRESGID */ #if HASSETREUID "HASSETREUID", #endif /* HASSETREUID */ #if HASSETRLIMIT "HASSETRLIMIT", #endif /* HASSETRLIMIT */ #if HASSETSID "HASSETSID", #endif /* HASSETSID */ #if HASSETUSERCONTEXT "HASSETUSERCONTEXT", #endif /* HASSETUSERCONTEXT */ #if HASSETVBUF "HASSETVBUF", #endif /* HASSETVBUF */ #if HAS_ST_GEN "HAS_ST_GEN", #endif /* HAS_ST_GEN */ #if HASSRANDOMDEV "HASSRANDOMDEV", #endif /* HASSRANDOMDEV */ #if HASURANDOMDEV "HASURANDOMDEV", #endif /* HASURANDOMDEV */ #if HASSTRERROR "HASSTRERROR", #endif /* HASSTRERROR */ #if HASULIMIT "HASULIMIT", #endif /* HASULIMIT */ #if HASUNAME "HASUNAME", #endif /* HASUNAME */ #if HASUNSETENV "HASUNSETENV", #endif /* HASUNSETENV */ #if HASWAITPID "HASWAITPID", #endif /* HASWAITPID */ #if HAVE_NANOSLEEP "HAVE_NANOSLEEP", #endif /* HAVE_NANOSLEEP */ #if IDENTPROTO "IDENTPROTO", #endif /* IDENTPROTO */ #if IP_SRCROUTE "IP_SRCROUTE", #endif /* IP_SRCROUTE */ #if O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL "LOCK_ON_OPEN", #endif /* O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL */ #if MILTER_NO_NAGLE "MILTER_NO_NAGLE ", #endif /* MILTER_NO_NAGLE */ #if NEEDFSYNC "NEEDFSYNC", #endif /* NEEDFSYNC */ #if NEEDLINK "NEEDLINK", #endif /* NEEDLINK */ #if NEEDLOCAL_HOSTNAME_LENGTH "NEEDLOCAL_HOSTNAME_LENGTH", #endif /* NEEDLOCAL_HOSTNAME_LENGTH */ #if NEEDSGETIPNODE "NEEDSGETIPNODE", #endif /* NEEDSGETIPNODE */ #if NEEDSTRSTR "NEEDSTRSTR", #endif /* NEEDSTRSTR */ #if NEEDSTRTOL "NEEDSTRTOL", #endif /* NEEDSTRTOL */ #ifdef NO_GETSERVBYNAME "NO_GETSERVBYNAME", #endif /* NO_GETSERVBYNAME */ #if NOFTRUNCATE "NOFTRUNCATE", #endif /* NOFTRUNCATE */ #if REQUIRES_DIR_FSYNC "REQUIRES_DIR_FSYNC", #endif /* REQUIRES_DIR_FSYNC */ #if RLIMIT_NEEDS_SYS_TIME_H "RLIMIT_NEEDS_SYS_TIME_H", #endif /* RLIMIT_NEEDS_SYS_TIME_H */ #if SAFENFSPATHCONF "SAFENFSPATHCONF", #endif /* SAFENFSPATHCONF */ #if SECUREWARE "SECUREWARE", #endif /* SECUREWARE */ +#if SFS_TYPE == SFS_4ARGS + "SFS_4ARGS", +#elif SFS_TYPE == SFS_MOUNT + "SFS_MOUNT", +#elif SFS_TYPE == SFS_NONE + "SFS_NONE", +#elif SFS_TYPE == SFS_NT + "SFS_NT", +#elif SFS_TYPE == SFS_STATFS + "SFS_STATFS", +#elif SFS_TYPE == SFS_STATVFS + "SFS_STATVFS", +#elif SFS_TYPE == SFS_USTAT + "SFS_USTAT", +#elif SFS_TYPE == SFS_VFS + "SFS_VFS", +#endif #if SHARE_V1 "SHARE_V1", #endif /* SHARE_V1 */ #if SIOCGIFCONF_IS_BROKEN "SIOCGIFCONF_IS_BROKEN", #endif /* SIOCGIFCONF_IS_BROKEN */ #if SIOCGIFNUM_IS_BROKEN "SIOCGIFNUM_IS_BROKEN", #endif /* SIOCGIFNUM_IS_BROKEN */ #if SNPRINTF_IS_BROKEN "SNPRINTF_IS_BROKEN", #endif /* SNPRINTF_IS_BROKEN */ #if SO_REUSEADDR_IS_BROKEN "SO_REUSEADDR_IS_BROKEN", #endif /* SO_REUSEADDR_IS_BROKEN */ #if SYS5SETPGRP "SYS5SETPGRP", #endif /* SYS5SETPGRP */ #if SYSTEM5 "SYSTEM5", #endif /* SYSTEM5 */ #if USE_DOUBLE_FORK "USE_DOUBLE_FORK", #endif /* USE_DOUBLE_FORK */ #if USE_ENVIRON "USE_ENVIRON", #endif /* USE_ENVIRON */ #if USE_SA_SIGACTION "USE_SA_SIGACTION", #endif /* USE_SA_SIGACTION */ #if USE_SIGLONGJMP "USE_SIGLONGJMP", #endif /* USE_SIGLONGJMP */ #if USEGETCONFATTR "USEGETCONFATTR", #endif /* USEGETCONFATTR */ #if USESETEUID "USESETEUID", #endif /* USESETEUID */ #ifdef USESYSCTL "USESYSCTL", #endif /* USESYSCTL */ #if USE_OPENSSL_ENGINE "USE_OPENSSL_ENGINE", #endif /* USE_OPENSSL_ENGINE */ #if USING_NETSCAPE_LDAP "USING_NETSCAPE_LDAP", #endif /* USING_NETSCAPE_LDAP */ #ifdef WAITUNION "WAITUNION", #endif /* WAITUNION */ NULL }; /* ** FFR compile options. */ char *FFRCompileOptions[] = { #if _FFR_ADDR_TYPE_MODES /* more info in {addr_type}, requires m4 changes! */ "_FFR_ADDR_TYPE_MODES", #endif /* _FFR_ADDR_TYPE_MODES */ #if _FFR_ALLOW_SASLINFO /* DefaultAuthInfo can be specified by user. */ /* DefaultAuthInfo doesn't really work in 8.13 anymore. */ "_FFR_ALLOW_SASLINFO", #endif /* _FFR_ALLOW_SASLINFO */ #if _FFR_BADRCPT_SHUTDOWN /* shut down connection (421) if there are too many bad RCPTs */ "_FFR_BADRCPT_SHUTDOWN", #endif /* _FFR_BADRCPT_SHUTDOWN */ #if _FFR_BESTMX_BETTER_TRUNCATION /* Better truncation of list of MX records for dns map. */ "_FFR_BESTMX_BETTER_TRUNCATION", #endif /* _FFR_BESTMX_BETTER_TRUNCATION */ #if _FFR_CATCH_BROKEN_MTAS /* Deal with MTAs that send a reply during the DATA phase. */ "_FFR_CATCH_BROKEN_MTAS", #endif /* _FFR_CATCH_BROKEN_MTAS */ #if _FFR_CHECKCONFIG /* New OpMode to check the configuration file */ "_FFR_CHECKCONFIG", #endif /* _FFR_CHECKCONFIG */ #if _FFR_CHK_QUEUE /* Stricter checks about queue directory permissions. */ "_FFR_CHK_QUEUE", #endif /* _FFR_CHK_QUEUE */ #if _FFR_CLIENT_SIZE /* Don't try to send mail if its size exceeds SIZE= of server. */ "_FFR_CLIENT_SIZE", #endif /* _FFR_CLIENT_SIZE */ #if _FFR_CRLPATH /* CRLPath; needs documentation; Al Smith */ "_FFR_CRLPATH", #endif /* _FFR_CRLPATH */ #if _FFR_DAEMON_NETUNIX /* Allow local (not just TCP) socket connection to server. */ "_FFR_DAEMON_NETUNIX", #endif /* _FFR_DAEMON_NETUNIX */ #if _FFR_DEPRECATE_MAILER_FLAG_I /* What it says :-) */ "_FFR_DEPRECATE_MAILER_FLAG_I", #endif /* _FFR_DEPRECATE_MAILER_FLAG_I */ #if _FFR_DM_ONE /* deliver first TA in background, then queue */ "_FFR_DM_ONE", #endif /* _FFR_DM_ONE */ #if _FFR_DIGUNIX_SAFECHOWN /* Properly set SAFECHOWN (include/sm/conf.h) for Digital UNIX */ /* Problem noted by Anne Bennett of Concordia University */ "_FFR_DIGUNIX_SAFECHOWN", #endif /* _FFR_DIGUNIX_SAFECHOWN */ #if _FFR_DNSMAP_ALIASABLE /* Allow dns map type to be used for aliases. */ /* Don Lewis of TDK */ "_FFR_DNSMAP_ALIASABLE", #endif /* _FFR_DNSMAP_ALIASABLE */ #if _FFR_DONTLOCKFILESFORREAD_OPTION /* Enable DontLockFilesForRead option. */ "_FFR_DONTLOCKFILESFORREAD_OPTION", #endif /* _FFR_DONTLOCKFILESFORREAD_OPTION */ #if _FFR_DOTTED_USERNAMES /* Allow usernames with '.' */ "_FFR_DOTTED_USERNAMES", #endif /* _FFR_DOTTED_USERNAMES */ #if _FFR_DPO_CS /* ** Make DaemonPortOptions case sensitive. ** For some unknown reasons the code converted every option ** to uppercase (first letter only, as that's the only one that ** is actually checked). This prevented all new lower case options ** from working... ** The documentation doesn't say anything about case (in)sensitivity, ** which means it should be case sensitive by default, ** but it's not a good idea to change this within a patch release, ** so let's delay this to 8.15. */ "_FFR_DPO_CS", #endif /* _FFR_DPO_CS */ #if _FFR_DPRINTF_MAP /* dprintf map for logging */ "_FFR_DPRINTF_MAP", #endif /* _FFR_DPRINTF_MAP */ #if _FFR_DROP_TRUSTUSER_WARNING /* ** Don't issue this warning: ** "readcf: option TrustedUser may cause problems on systems ** which do not support fchown() if UseMSP is not set. */ "_FFR_DROP_TRUSTUSER_WARNING", #endif /* _FFR_DROP_TRUSTUSER_WARNING */ #if _FFR_EIGHT_BIT_ADDR_OK /* EightBitAddrOK: allow 8-bit e-mail addresses */ "_FFR_EIGHT_BIT_ADDR_OK", #endif /* _FFR_EIGHT_BIT_ADDR_OK */ #if _FFR_EXPDELAY /* exponential queue delay */ "_FFR_EXPDELAY", #endif /* _FFR_EXPDELAY */ #if _FFR_EXTRA_MAP_CHECK /* perform extra checks on $( $) in R lines */ "_FFR_EXTRA_MAP_CHECK", #endif /* _FFR_EXTRA_MAP_CHECK */ #if _FFR_GETHBN_ExFILE /* ** According to Motonori Nakamura some gethostbyname() ** implementations (TurboLinux?) may (temporarily) fail ** due to a lack of file discriptors. Enabling this FFR ** will check errno for EMFILE and ENFILE and in case of a match ** cause a temporary error instead of a permanent error. ** The right solution is of course to file a bug against those ** systems such that they actually set h_errno = TRY_AGAIN. */ "_FFR_GETHBN_ExFILE", #endif /* _FFR_GETHBN_ExFILE */ +#if _FFR_FIPSMODE + /* FIPSMode (if supported by OpenSSL library) */ + "_FFR_FIPSMODE", +#endif /* _FFR_FIPSMODE */ #if _FFR_FIX_DASHT /* ** If using -t, force not sending to argv recipients, even ** if they are mentioned in the headers. */ "_FFR_FIX_DASHT", #endif /* _FFR_FIX_DASHT */ #if _FFR_FORWARD_SYSERR /* Cause a "syserr" if forward file isn't "safe". */ "_FFR_FORWARD_SYSERR", #endif /* _FFR_FORWARD_SYSERR */ #if _FFR_GEN_ORCPT /* Generate a ORCPT DSN arg if not already provided */ "_FFR_GEN_ORCPT", #endif /* _FFR_GEN_ORCPT */ #if _FFR_GROUPREADABLEAUTHINFOFILE /* Allow group readable DefaultAuthInfo file. */ "_FFR_GROUPREADABLEAUTHINFOFILE", #endif /* _FFR_GROUPREADABLEAUTHINFOFILE */ #if _FFR_HANDLE_ISO8859_GECOS /* ** Allow ISO 8859 characters in GECOS field: replace them ** ith ASCII "equivalent". */ /* Peter Eriksson of Linkopings universitet */ "_FFR_HANDLE_ISO8859_GECOS", #endif /* _FFR_HANDLE_ISO8859_GECOS */ #if _FFR_HPUX_NSSWITCH /* Use nsswitch on HP-UX */ "_FFR_HPUX_NSSWITCH", #endif /* _FFR_HPUX_NSSWITCH */ #if _FFR_IGNORE_BOGUS_ADDR /* Ignore addresses for which prescan() failed */ "_FFR_IGNORE_BOGUS_ADDR", #endif /* _FFR_IGNORE_BOGUS_ADDR */ #if _FFR_IGNORE_EXT_ON_HELO /* Ignore extensions offered in response to HELO */ "_FFR_IGNORE_EXT_ON_HELO", #endif /* _FFR_IGNORE_EXT_ON_HELO */ #if _FFR_LINUX_MHNL /* Set MAXHOSTNAMELEN to 256 (Linux) */ "_FFR_LINUX_MHNL", #endif /* _FFR_LINUX_MHNL */ #if _FFR_LOCAL_DAEMON /* Local daemon mode (-bl) which only accepts loopback connections */ "_FFR_LOCAL_DAEMON", #endif /* _FFR_LOCAL_DAEMON */ #if _FFR_MAIL_MACRO "_FFR_MAIL_MACRO", #endif /* _FFR_MAIL_MACRO */ #if _FFR_MAXDATASIZE /* ** It is possible that a header is larger than MILTER_CHUNK_SIZE, ** hence this shouldn't be used as limit for milter communication. ** see also libmilter/comm.c ** Gurusamy Sarathy of ActiveState */ "_FFR_MAXDATASIZE", #endif /* _FFR_MAXDATASIZE */ #if _FFR_MAX_FORWARD_ENTRIES /* Try to limit number of .forward entries */ /* (doesn't work) */ /* Randall S. Winchester of the University of Maryland */ "_FFR_MAX_FORWARD_ENTRIES", #endif /* _FFR_MAX_FORWARD_ENTRIES */ #if _FFR_MAX_SLEEP_TIME /* Limit sleep(2) time in libsm/clock.c */ "_FFR_MAX_SLEEP_TIME", #endif /* _FFR_MAX_SLEEP_TIME */ #if _FFR_MDS_NEGOTIATE /* MaxDataSize negotation with libmilter */ "_FFR_MDS_NEGOTIATE", #endif /* _FFR_MDS_NEGOTIATE */ #if _FFR_MEMSTAT /* Check free memory */ "_FFR_MEMSTAT", #endif /* _FFR_MEMSTAT */ #if _FFR_MILTER_CHECK "_FFR_MILTER_CHECK", #endif /* _FFR_MILTER_CHECK */ #if _FFR_MILTER_CONVERT_ALL_LF_TO_CRLF /* ** milter_body() uses the same conversion algorithm as putbody() ** to translate the "local" df format (\n) to SMTP format (\r\n). ** However, putbody() and mime8to7() use different conversion ** algorithms. ** If the input date does not follow the SMTP standard ** (e.g., if it has "naked \r"s), then the output from putbody() ** and mime8to7() will most likely be different. ** By turning on this FFR milter_body() will try to "imitate" ** mime8to7(). ** Note: there is no (simple) way to deal with both conversions ** in a consistent manner. Moreover, as the "GiGo" principle applies, ** it's not really worth to fix it. */ "_FFR_MILTER_CONVERT_ALL_LF_TO_CRLF", #endif /* _FFR_MILTER_CONVERT_ALL_LF_TO_CRLF */ #if _FFR_MILTER_CHECK_REJECTIONS_TOO /* ** Also send RCPTs that are rejected by check_rcpt to a milter ** (if requested during option negotiation). */ "_FFR_MILTER_CHECK_REJECTIONS_TOO", #endif /* _FFR_MILTER_CHECK_REJECTIONS_TOO */ #if _FFR_MILTER_ENHSC /* extract enhanced status code from milter replies for dsn= logging */ "_FFR_MILTER_ENHSC", #endif /* _FFR_MILTER_ENHSC */ #if _FFR_MIME7TO8_OLD /* Old mime7to8 code, the new is broken for at least one example. */ "_FFR_MIME7TO8_OLD", #endif /* _FFR_MAX_SLEEP_TIME */ #if _FFR_MORE_MACROS /* allow more long macro names ("unprintable" characters). */ "_FFR_MORE_MACROS", #endif /* _FFR_MORE_MACROS */ #if _FFR_MSG_ACCEPT /* allow to override "Message accepted for delivery" */ "_FFR_MSG_ACCEPT", #endif /* _FFR_MSG_ACCEPT */ #if _FFR_NODELAYDSN_ON_HOLD /* Do not issue a DELAY DSN for mailers that use the hold flag. */ /* Steven Pitzl */ "_FFR_NODELAYDSN_ON_HOLD", #endif /* _FFR_NODELAYDSN_ON_HOLD */ #if _FFR_NO_PIPE /* Disable PIPELINING, delay client if used. */ "_FFR_NO_PIPE", #endif /* _FFR_NO_PIPE */ #if _FFR_LDAP_NETWORK_TIMEOUT /* set LDAP_OPT_NETWORK_TIMEOUT if available (-c) */ "_FFR_LDAP_NETWORK_TIMEOUT", #endif /* _FFR_LDAP_NETWORK_TIMEOUT */ #if _FFR_LOG_NTRIES /* log ntries=, from Nik Clayton of FreeBSD */ "_FFR_LOG_NTRIES", #endif /* _FFR_LOG_NTRIES */ #if _FFR_QF_PARANOIA "_FFR_QF_PARANOIA", #endif /* _FFR_QF_PARANOIA */ #if _FFR_QUEUEDELAY /* Exponential queue delay; disabled in 8.13 since it isn't used. */ "_FFR_QUEUEDELAY", #endif /* _FFR_QUEUEDELAY */ #if _FFR_QUEUE_GROUP_SORTORDER /* Allow QueueSortOrder per queue group. */ /* XXX: Still need to actually use qgrp->qg_sortorder */ "_FFR_QUEUE_GROUP_SORTORDER", #endif /* _FFR_QUEUE_GROUP_SORTORDER */ #if _FFR_QUEUE_MACRO /* Define {queue} macro. */ "_FFR_QUEUE_MACRO", #endif /* _FFR_QUEUE_MACRO */ #if _FFR_QUEUE_RUN_PARANOIA /* Additional checks when doing queue runs; interval of checks */ "_FFR_QUEUE_RUN_PARANOIA", #endif /* _FFR_QUEUE_RUN_PARANOIA */ #if _FFR_QUEUE_SCHED_DBG /* Debug output for the queue scheduler. */ "_FFR_QUEUE_SCHED_DBG", #endif /* _FFR_QUEUE_SCHED_DBG */ #if _FFR_RCPTTHROTDELAY /* configurable delay for BadRcptThrottle */ "_FFR_RCPTTHROTDELAY", #endif /* _FFR_RCPTTHROTDELAY */ #if _FFR_REDIRECTEMPTY /* ** envelope <> can't be sent to mailing lists, only owner- ** send spam of this type to owner- of the list ** ---- to stop spam from going to mailing lists. */ "_FFR_REDIRECTEMPTY", #endif /* _FFR_REDIRECTEMPTY */ +#if _FFR_REJECT_NUL_BYTE + /* reject NUL bytes in body */ + "_FFR_REJECT_NUL_BYTE", +#endif /* _FFR_REJECT_NUL_BYTE */ #if _FFR_RESET_MACRO_GLOBALS /* Allow macro 'j' to be set dynamically via rulesets. */ "_FFR_RESET_MACRO_GLOBALS", #endif /* _FFR_RESET_MACRO_GLOBALS */ #if _FFR_RHS /* Random shuffle for queue sorting. */ "_FFR_RHS", #endif /* _FFR_RHS */ #if _FFR_RUNPQG /* ** allow -qGqueue_group -qp to work, i.e., ** restrict a persistent queue runner to a queue group. */ "_FFR_RUNPQG", #endif /* _FFR_RUNPQG */ #if _FFR_SESSID /* session id (for logging) */ "_FFR_SESSID", #endif /* _FFR_SESSID */ #if _FFR_SHM_STATUS /* Donated code (unused). */ "_FFR_SHM_STATUS", #endif /* _FFR_SHM_STATUS */ #if _FFR_LDAP_SINGLEDN /* ** The LDAP database map code in Sendmail 8.12.10, when ** given the -1 switch, would match only a single DN, ** but was able to return multiple attributes for that ** DN. In Sendmail 8.13 this "bug" was corrected to ** only return if exactly one attribute matched. ** ** Unfortunately, our configuration uses the former ** behaviour. Attached is a relatively simple patch ** to 8.13.4 which adds a -2 switch (for lack of a ** better option) which returns the single dn/multiple ** attributes. ** ** Jeffrey T. Eaton, Carnegie-Mellon University */ "_FFR_LDAP_SINGLEDN", #endif /* _FFR_LDAP_SINGLEDN */ #if _FFR_SKIP_DOMAINS /* process every N'th domain instead of every N'th message */ "_FFR_SKIP_DOMAINS", #endif /* _FFR_SKIP_DOMAINS */ #if _FFR_SLEEP_USE_SELECT /* Use select(2) in libsm/clock.c to emulate sleep(2) */ "_FFR_SLEEP_USE_SELECT ", #endif /* _FFR_SLEEP_USE_SELECT */ #if _FFR_SPT_ALIGN /* ** It looks like the Compaq Tru64 5.1A now aligns argv and envp to 64 ** bit alignment, so unless each piece of argv and envp is a multiple ** of 8 bytes (including terminating NULL), initsetproctitle() won't ** use any of the space beyond argv[0]. Be sure to set SPT_ALIGN_SIZE ** if you use this FFR. */ /* Chris Adams of HiWAAY Informations Services */ "_FFR_SPT_ALIGN", #endif /* _FFR_SPT_ALIGN */ #if _FFR_SS_PER_DAEMON /* SuperSafe per DaemonPortOptions: 'T' (better letter?) */ "_FFR_SS_PER_DAEMON", #endif /* _FFR_SS_PER_DAEMON */ #if _FFR_TESTS /* enable some test code */ "_FFR_TESTS", #endif /* _FFR_TESTS */ #if _FFR_TIMERS /* Donated code (unused). */ "_FFR_TIMERS", #endif /* _FFR_TIMERS */ #if _FFR_TLS_1 /* More STARTTLS options, e.g., secondary certs. */ "_FFR_TLS_1", #endif /* _FFR_TLS_1 */ #if _FFR_TRUSTED_QF /* ** If we don't own the file mark it as unsafe. ** However, allow TrustedUser to own it as well ** in case TrustedUser manipulates the queue. */ "_FFR_TRUSTED_QF", #endif /* _FFR_TRUSTED_QF */ #if _FFR_USE_SEM_LOCKING "_FFR_USE_SEM_LOCKING", #endif /* _FFR_USE_SEM_LOCKING */ #if _FFR_USE_SETLOGIN /* Use setlogin() */ /* Peter Philipp */ "_FFR_USE_SETLOGIN", #endif /* _FFR_USE_SETLOGIN */ NULL }; Index: head/contrib/sendmail/src/control.c =================================================================== --- head/contrib/sendmail/src/control.c (revision 249728) +++ head/contrib/sendmail/src/control.c (revision 249729) @@ -1,431 +1,431 @@ /* * Copyright (c) 1998-2004, 2006 Sendmail, Inc. and its suppliers. * All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: control.c,v 8.128 2006/08/15 23:24:56 ca Exp $") +SM_RCSID("@(#)$Id: control.c,v 8.129 2013/03/12 15:24:52 ca Exp $") #include /* values for cmd_code */ #define CMDERROR 0 /* bad command */ #define CMDRESTART 1 /* restart daemon */ #define CMDSHUTDOWN 2 /* end daemon */ #define CMDHELP 3 /* help */ #define CMDSTATUS 4 /* daemon status */ #define CMDMEMDUMP 5 /* dump memory, to find memory leaks */ #define CMDMSTAT 6 /* daemon status, more info, tagged data */ struct cmd { char *cmd_name; /* command name */ int cmd_code; /* internal code, see below */ }; static struct cmd CmdTab[] = { { "help", CMDHELP }, { "restart", CMDRESTART }, { "shutdown", CMDSHUTDOWN }, { "status", CMDSTATUS }, { "memdump", CMDMEMDUMP }, { "mstat", CMDMSTAT }, { NULL, CMDERROR } }; static void controltimeout __P((int)); int ControlSocket = -1; /* ** OPENCONTROLSOCKET -- create/open the daemon control named socket ** ** Creates and opens a named socket for external control over ** the sendmail daemon. ** ** Parameters: ** none. ** ** Returns: ** 0 if successful, -1 otherwise */ int opencontrolsocket() { # if NETUNIX int save_errno; int rval; long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_CREAT|SFF_MUSTOWN; struct sockaddr_un controladdr; if (ControlSocketName == NULL || *ControlSocketName == '\0') return 0; if (strlen(ControlSocketName) >= sizeof(controladdr.sun_path)) { errno = ENAMETOOLONG; return -1; } rval = safefile(ControlSocketName, RunAsUid, RunAsGid, RunAsUserName, sff, S_IRUSR|S_IWUSR, NULL); /* if not safe, don't create */ if (rval != 0) { errno = rval; return -1; } ControlSocket = socket(AF_UNIX, SOCK_STREAM, 0); if (ControlSocket < 0) return -1; if (SM_FD_SETSIZE > 0 && ControlSocket >= SM_FD_SETSIZE) { clrcontrol(); errno = EINVAL; return -1; } (void) unlink(ControlSocketName); memset(&controladdr, '\0', sizeof(controladdr)); controladdr.sun_family = AF_UNIX; (void) sm_strlcpy(controladdr.sun_path, ControlSocketName, sizeof(controladdr.sun_path)); if (bind(ControlSocket, (struct sockaddr *) &controladdr, sizeof(controladdr)) < 0) { save_errno = errno; clrcontrol(); errno = save_errno; return -1; } if (geteuid() == 0) { uid_t u = 0; if (RunAsUid != 0) u = RunAsUid; else if (TrustedUid != 0) u = TrustedUid; if (u != 0 && chown(ControlSocketName, u, -1) < 0) { save_errno = errno; sm_syslog(LOG_ALERT, NOQID, "ownership change on %s to uid %d failed: %s", ControlSocketName, (int) u, sm_errstring(save_errno)); message("050 ownership change on %s to uid %d failed: %s", ControlSocketName, (int) u, sm_errstring(save_errno)); closecontrolsocket(true); errno = save_errno; return -1; } } if (chmod(ControlSocketName, S_IRUSR|S_IWUSR) < 0) { save_errno = errno; closecontrolsocket(true); errno = save_errno; return -1; } if (listen(ControlSocket, 8) < 0) { save_errno = errno; closecontrolsocket(true); errno = save_errno; return -1; } # endif /* NETUNIX */ return 0; } /* ** CLOSECONTROLSOCKET -- close the daemon control named socket ** ** Close a named socket. ** ** Parameters: ** fullclose -- if set, close the socket and remove it; ** otherwise, just remove it ** ** Returns: ** none. */ void closecontrolsocket(fullclose) bool fullclose; { # if NETUNIX long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_CREAT|SFF_MUSTOWN; if (ControlSocket >= 0) { int rval; if (fullclose) { (void) close(ControlSocket); ControlSocket = -1; } rval = safefile(ControlSocketName, RunAsUid, RunAsGid, RunAsUserName, sff, S_IRUSR|S_IWUSR, NULL); /* if not safe, don't unlink */ if (rval != 0) return; if (unlink(ControlSocketName) < 0) { sm_syslog(LOG_WARNING, NOQID, "Could not remove control socket: %s", sm_errstring(errno)); return; } } # endif /* NETUNIX */ return; } /* ** CLRCONTROL -- reset the control connection ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** releases any resources used by the control interface. */ void clrcontrol() { # if NETUNIX if (ControlSocket >= 0) (void) close(ControlSocket); ControlSocket = -1; # endif /* NETUNIX */ } /* ** CONTROL_COMMAND -- read and process command from named socket ** ** Read and process the command from the opened socket. ** Exits when done since it is running in a forked child. ** ** Parameters: ** sock -- the opened socket from getrequests() ** e -- the current envelope ** ** Returns: ** none. */ static jmp_buf CtxControlTimeout; /* ARGSUSED0 */ static void controltimeout(timeout) int timeout; { /* ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ errno = ETIMEDOUT; longjmp(CtxControlTimeout, 1); } void control_command(sock, e) int sock; ENVELOPE *e; { volatile int exitstat = EX_OK; SM_FILE_T *s = NULL; SM_EVENT *ev = NULL; SM_FILE_T *traffic; SM_FILE_T *oldout; char *cmd; char *p; struct cmd *c; char cmdbuf[MAXLINE]; char inp[MAXLINE]; sm_setproctitle(false, e, "control cmd read"); if (TimeOuts.to_control > 0) { /* handle possible input timeout */ if (setjmp(CtxControlTimeout) != 0) { if (LogLevel > 2) sm_syslog(LOG_NOTICE, e->e_id, "timeout waiting for input during control command"); exit(EX_IOERR); } ev = sm_setevent(TimeOuts.to_control, controltimeout, TimeOuts.to_control); } s = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &sock, SM_IO_RDWR, NULL); if (s == NULL) { int save_errno = errno; (void) close(sock); errno = save_errno; exit(EX_IOERR); } (void) sm_io_setvbuf(s, SM_TIME_DEFAULT, NULL, SM_IO_NBF, SM_IO_BUFSIZ); - if (sm_io_fgets(s, SM_TIME_DEFAULT, inp, sizeof(inp)) == NULL) + if (sm_io_fgets(s, SM_TIME_DEFAULT, inp, sizeof(inp)) < 0) { (void) sm_io_close(s, SM_TIME_DEFAULT); exit(EX_IOERR); } (void) sm_io_flush(s, SM_TIME_DEFAULT); /* clean up end of line */ fixcrlf(inp, true); sm_setproctitle(false, e, "control: %s", inp); /* break off command */ for (p = inp; isascii(*p) && isspace(*p); p++) continue; cmd = cmdbuf; while (*p != '\0' && !(isascii(*p) && isspace(*p)) && cmd < &cmdbuf[sizeof(cmdbuf) - 2]) *cmd++ = *p++; *cmd = '\0'; /* throw away leading whitespace */ while (isascii(*p) && isspace(*p)) p++; /* decode command */ for (c = CmdTab; c->cmd_name != NULL; c++) { if (sm_strcasecmp(c->cmd_name, cmdbuf) == 0) break; } switch (c->cmd_code) { case CMDHELP: /* get help */ traffic = TrafficLogFile; TrafficLogFile = NULL; oldout = OutChannel; OutChannel = s; help("control", e); TrafficLogFile = traffic; OutChannel = oldout; break; case CMDRESTART: /* restart the daemon */ (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "OK\r\n"); exitstat = EX_RESTART; break; case CMDSHUTDOWN: /* kill the daemon */ (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "OK\r\n"); exitstat = EX_SHUTDOWN; break; case CMDSTATUS: /* daemon status */ proc_list_probe(); { int qgrp; long bsize; long free; /* XXX need to deal with different partitions */ qgrp = e->e_qgrp; if (!ISVALIDQGRP(qgrp)) qgrp = 0; free = freediskspace(Queue[qgrp]->qg_qdir, &bsize); /* ** Prevent overflow and don't lose ** precision (if bsize == 512) */ if (free > 0) free = (long)((double) free * ((double) bsize / 1024)); (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "%d/%d/%ld/%d\r\n", CurChildren, MaxChildren, free, getla()); } proc_list_display(s, ""); break; case CMDMSTAT: /* daemon status, extended, tagged format */ proc_list_probe(); (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "C:%d\r\nM:%d\r\nL:%d\r\n", CurChildren, MaxChildren, getla()); printnqe(s, "Q:"); disk_status(s, "D:"); proc_list_display(s, "P:"); break; case CMDMEMDUMP: /* daemon memory dump, to find memory leaks */ # if SM_HEAP_CHECK /* dump the heap, if we are checking for memory leaks */ if (sm_debug_active(&SmHeapCheck, 2)) { sm_heap_report(s, sm_debug_level(&SmHeapCheck) - 1); } else { (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "Memory dump unavailable.\r\n"); (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "To fix, run sendmail with -dsm_check_heap.4\r\n"); } # else /* SM_HEAP_CHECK */ (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "Memory dump unavailable.\r\n"); (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "To fix, rebuild with -DSM_HEAP_CHECK\r\n"); # endif /* SM_HEAP_CHECK */ break; case CMDERROR: /* unknown command */ (void) sm_io_fprintf(s, SM_TIME_DEFAULT, "Bad command (%s)\r\n", cmdbuf); break; } (void) sm_io_close(s, SM_TIME_DEFAULT); if (ev != NULL) sm_clrevent(ev); exit(exitstat); } Index: head/contrib/sendmail/src/deliver.c =================================================================== --- head/contrib/sendmail/src/deliver.c (revision 249728) +++ head/contrib/sendmail/src/deliver.c (revision 249729) @@ -1,6284 +1,6284 @@ /* * Copyright (c) 1998-2010, 2012 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include #include -SM_RCSID("@(#)$Id: deliver.c,v 8.1027 2012/12/19 02:49:21 ca Exp $") +SM_RCSID("@(#)$Id: deliver.c,v 8.1028 2013/01/02 18:57:42 ca Exp $") #if HASSETUSERCONTEXT # include #endif /* HASSETUSERCONTEXT */ #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ #if STARTTLS || SASL # include "sfsasl.h" #endif /* STARTTLS || SASL */ static int deliver __P((ENVELOPE *, ADDRESS *)); static void dup_queue_file __P((ENVELOPE *, ENVELOPE *, int)); static void mailfiletimeout __P((int)); static void endwaittimeout __P((int)); static int parse_hostsignature __P((char *, char **, MAILER *)); static void sendenvelope __P((ENVELOPE *, int)); static int coloncmp __P((const char *, const char *)); #if STARTTLS # include static int starttls __P((MAILER *, MCI *, ENVELOPE *)); static int endtlsclt __P((MCI *)); #endif /* STARTTLS */ # if STARTTLS || SASL static bool iscltflgset __P((ENVELOPE *, int)); # endif /* STARTTLS || SASL */ /* ** SENDALL -- actually send all the messages. ** ** Parameters: ** e -- the envelope to send. ** mode -- the delivery mode to use. If SM_DEFAULT, use ** the current e->e_sendmode. ** ** Returns: ** none. ** ** Side Effects: ** Scans the send lists and sends everything it finds. ** Delivers any appropriate error messages. ** If we are running in a non-interactive mode, takes the ** appropriate action. */ void sendall(e, mode) ENVELOPE *e; int mode; { register ADDRESS *q; char *owner; int otherowners; int save_errno; register ENVELOPE *ee; ENVELOPE *splitenv = NULL; int oldverbose = Verbose; bool somedeliveries = false, expensive = false; pid_t pid; /* ** If this message is to be discarded, don't bother sending ** the message at all. */ if (bitset(EF_DISCARD, e->e_flags)) { if (tTd(13, 1)) sm_dprintf("sendall: discarding id %s\n", e->e_id); e->e_flags |= EF_CLRQUEUE; if (LogLevel > 9) logundelrcpts(e, "discarded", 9, true); else if (LogLevel > 4) sm_syslog(LOG_INFO, e->e_id, "discarded"); markstats(e, NULL, STATS_REJECT); return; } /* ** If we have had global, fatal errors, don't bother sending ** the message at all if we are in SMTP mode. Local errors ** (e.g., a single address failing) will still cause the other ** addresses to be sent. */ if (bitset(EF_FATALERRS, e->e_flags) && (OpMode == MD_SMTP || OpMode == MD_DAEMON)) { e->e_flags |= EF_CLRQUEUE; return; } /* determine actual delivery mode */ if (mode == SM_DEFAULT) { mode = e->e_sendmode; if (mode != SM_VERIFY && mode != SM_DEFER && shouldqueue(e->e_msgpriority, e->e_ctime)) mode = SM_QUEUE; } if (tTd(13, 1)) { sm_dprintf("\n===== SENDALL: mode %c, id %s, e_from ", mode, e->e_id); printaddr(sm_debug_file(), &e->e_from, false); sm_dprintf("\te_flags = "); printenvflags(e); sm_dprintf("sendqueue:\n"); printaddr(sm_debug_file(), e->e_sendqueue, true); } /* ** Do any preprocessing necessary for the mode we are running. ** Check to make sure the hop count is reasonable. ** Delete sends to the sender in mailing lists. */ CurEnv = e; if (tTd(62, 1)) checkfds(NULL); if (e->e_hopcount > MaxHopCount) { char *recip; if (e->e_sendqueue != NULL && e->e_sendqueue->q_paddr != NULL) recip = e->e_sendqueue->q_paddr; else recip = "(nobody)"; errno = 0; queueup(e, WILL_BE_QUEUED(mode), false); e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE; ExitStat = EX_UNAVAILABLE; syserr("554 5.4.6 Too many hops %d (%d max): from %s via %s, to %s", e->e_hopcount, MaxHopCount, e->e_from.q_paddr, RealHostName == NULL ? "localhost" : RealHostName, recip); for (q = e->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_DEAD(q->q_state)) continue; q->q_state = QS_BADADDR; q->q_status = "5.4.6"; q->q_rstatus = "554 5.4.6 Too many hops"; } return; } /* ** Do sender deletion. ** ** If the sender should be queued up, skip this. ** This can happen if the name server is hosed when you ** are trying to send mail. The result is that the sender ** is instantiated in the queue as a recipient. */ if (!bitset(EF_METOO, e->e_flags) && !QS_IS_QUEUEUP(e->e_from.q_state)) { if (tTd(13, 5)) { sm_dprintf("sendall: QS_SENDER "); printaddr(sm_debug_file(), &e->e_from, false); } e->e_from.q_state = QS_SENDER; (void) recipient(&e->e_from, &e->e_sendqueue, 0, e); } /* ** Handle alias owners. ** ** We scan up the q_alias chain looking for owners. ** We discard owners that are the same as the return path. */ for (q = e->e_sendqueue; q != NULL; q = q->q_next) { register struct address *a; for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias) continue; if (a != NULL) q->q_owner = a->q_owner; if (q->q_owner != NULL && !QS_IS_DEAD(q->q_state) && strcmp(q->q_owner, e->e_from.q_paddr) == 0) q->q_owner = NULL; } if (tTd(13, 25)) { sm_dprintf("\nAfter first owner pass, sendq =\n"); printaddr(sm_debug_file(), e->e_sendqueue, true); } owner = ""; otherowners = 1; while (owner != NULL && otherowners > 0) { if (tTd(13, 28)) sm_dprintf("owner = \"%s\", otherowners = %d\n", owner, otherowners); owner = NULL; otherowners = bitset(EF_SENDRECEIPT, e->e_flags) ? 1 : 0; for (q = e->e_sendqueue; q != NULL; q = q->q_next) { if (tTd(13, 30)) { sm_dprintf("Checking "); printaddr(sm_debug_file(), q, false); } if (QS_IS_DEAD(q->q_state)) { if (tTd(13, 30)) sm_dprintf(" ... QS_IS_DEAD\n"); continue; } if (tTd(13, 29) && !tTd(13, 30)) { sm_dprintf("Checking "); printaddr(sm_debug_file(), q, false); } if (q->q_owner != NULL) { if (owner == NULL) { if (tTd(13, 40)) sm_dprintf(" ... First owner = \"%s\"\n", q->q_owner); owner = q->q_owner; } else if (owner != q->q_owner) { if (strcmp(owner, q->q_owner) == 0) { if (tTd(13, 40)) sm_dprintf(" ... Same owner = \"%s\"\n", owner); /* make future comparisons cheap */ q->q_owner = owner; } else { if (tTd(13, 40)) sm_dprintf(" ... Another owner \"%s\"\n", q->q_owner); otherowners++; } owner = q->q_owner; } else if (tTd(13, 40)) sm_dprintf(" ... Same owner = \"%s\"\n", owner); } else { if (tTd(13, 40)) sm_dprintf(" ... Null owner\n"); otherowners++; } if (QS_IS_BADADDR(q->q_state)) { if (tTd(13, 30)) sm_dprintf(" ... QS_IS_BADADDR\n"); continue; } if (QS_IS_QUEUEUP(q->q_state)) { MAILER *m = q->q_mailer; /* ** If we have temporary address failures ** (e.g., dns failure) and a fallback MX is ** set, send directly to the fallback MX host. */ if (FallbackMX != NULL && !wordinclass(FallbackMX, 'w') && mode != SM_VERIFY && !bitnset(M_NOMX, m->m_flags) && strcmp(m->m_mailer, "[IPC]") == 0 && m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0) { int len; char *p; if (tTd(13, 30)) sm_dprintf(" ... FallbackMX\n"); len = strlen(FallbackMX) + 1; p = sm_rpool_malloc_x(e->e_rpool, len); (void) sm_strlcpy(p, FallbackMX, len); q->q_state = QS_OK; q->q_host = p; } else { if (tTd(13, 30)) sm_dprintf(" ... QS_IS_QUEUEUP\n"); continue; } } /* ** If this mailer is expensive, and if we don't ** want to make connections now, just mark these ** addresses and return. This is useful if we ** want to batch connections to reduce load. This ** will cause the messages to be queued up, and a ** daemon will come along to send the messages later. */ if (NoConnect && !Verbose && bitnset(M_EXPENSIVE, q->q_mailer->m_flags)) { if (tTd(13, 30)) sm_dprintf(" ... expensive\n"); q->q_state = QS_QUEUEUP; expensive = true; } else if (bitnset(M_HOLD, q->q_mailer->m_flags) && QueueLimitId == NULL && QueueLimitSender == NULL && QueueLimitRecipient == NULL) { if (tTd(13, 30)) sm_dprintf(" ... hold\n"); q->q_state = QS_QUEUEUP; expensive = true; } else if (QueueMode != QM_QUARANTINE && e->e_quarmsg != NULL) { if (tTd(13, 30)) sm_dprintf(" ... quarantine: %s\n", e->e_quarmsg); q->q_state = QS_QUEUEUP; expensive = true; } else { if (tTd(13, 30)) sm_dprintf(" ... deliverable\n"); somedeliveries = true; } } if (owner != NULL && otherowners > 0) { /* ** Split this envelope into two. */ ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool, sizeof(*ee)); STRUCTCOPY(*e, *ee); ee->e_message = NULL; ee->e_id = NULL; assign_queueid(ee); if (tTd(13, 1)) sm_dprintf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n", e->e_id, ee->e_id, owner, otherowners); ee->e_header = copyheader(e->e_header, ee->e_rpool); ee->e_sendqueue = copyqueue(e->e_sendqueue, ee->e_rpool); ee->e_errorqueue = copyqueue(e->e_errorqueue, ee->e_rpool); ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM); ee->e_flags |= EF_NORECEIPT; setsender(owner, ee, NULL, '\0', true); if (tTd(13, 5)) { sm_dprintf("sendall(split): QS_SENDER "); printaddr(sm_debug_file(), &ee->e_from, false); } ee->e_from.q_state = QS_SENDER; ee->e_dfp = NULL; ee->e_lockfp = NULL; ee->e_xfp = NULL; ee->e_qgrp = e->e_qgrp; ee->e_qdir = e->e_qdir; ee->e_errormode = EM_MAIL; ee->e_sibling = splitenv; ee->e_statmsg = NULL; if (e->e_quarmsg != NULL) ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool, e->e_quarmsg); splitenv = ee; for (q = e->e_sendqueue; q != NULL; q = q->q_next) { if (q->q_owner == owner) { q->q_state = QS_CLONED; if (tTd(13, 6)) sm_dprintf("\t... stripping %s from original envelope\n", q->q_paddr); } } for (q = ee->e_sendqueue; q != NULL; q = q->q_next) { if (q->q_owner != owner) { q->q_state = QS_CLONED; if (tTd(13, 6)) sm_dprintf("\t... dropping %s from cloned envelope\n", q->q_paddr); } else { /* clear DSN parameters */ q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS); q->q_flags |= DefaultNotify & ~QPINGONSUCCESS; if (tTd(13, 6)) sm_dprintf("\t... moving %s to cloned envelope\n", q->q_paddr); } } if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags)) dup_queue_file(e, ee, DATAFL_LETTER); /* ** Give the split envelope access to the parent ** transcript file for errors obtained while ** processing the recipients (done before the ** envelope splitting). */ if (e->e_xfp != NULL) ee->e_xfp = sm_io_dup(e->e_xfp); /* failed to dup e->e_xfp, start a new transcript */ if (ee->e_xfp == NULL) openxscript(ee); if (mode != SM_VERIFY && LogLevel > 4) sm_syslog(LOG_INFO, e->e_id, "%s: clone: owner=%s", ee->e_id, owner); } } if (owner != NULL) { setsender(owner, e, NULL, '\0', true); if (tTd(13, 5)) { sm_dprintf("sendall(owner): QS_SENDER "); printaddr(sm_debug_file(), &e->e_from, false); } e->e_from.q_state = QS_SENDER; e->e_errormode = EM_MAIL; e->e_flags |= EF_NORECEIPT; e->e_flags &= ~EF_FATALERRS; } /* if nothing to be delivered, just queue up everything */ if (!somedeliveries && !WILL_BE_QUEUED(mode) && mode != SM_VERIFY) { time_t now; if (tTd(13, 29)) sm_dprintf("No deliveries: auto-queueing\n"); mode = SM_QUEUE; now = curtime(); /* treat this as a delivery in terms of counting tries */ e->e_dtime = now; if (!expensive) e->e_ntries++; for (ee = splitenv; ee != NULL; ee = ee->e_sibling) { ee->e_dtime = now; if (!expensive) ee->e_ntries++; } } if ((WILL_BE_QUEUED(mode) || mode == SM_FORK || (mode != SM_VERIFY && (SuperSafe == SAFE_REALLY || SuperSafe == SAFE_REALLY_POSTMILTER))) && (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL)) { bool msync; /* ** Be sure everything is instantiated in the queue. ** Split envelopes first in case the machine crashes. ** If the original were done first, we may lose ** recipients. */ #if !HASFLOCK msync = false; #else /* !HASFLOCK */ msync = mode == SM_FORK; #endif /* !HASFLOCK */ for (ee = splitenv; ee != NULL; ee = ee->e_sibling) queueup(ee, WILL_BE_QUEUED(mode), msync); queueup(e, WILL_BE_QUEUED(mode), msync); } if (tTd(62, 10)) checkfds("after envelope splitting"); /* ** If we belong in background, fork now. */ if (tTd(13, 20)) { sm_dprintf("sendall: final mode = %c\n", mode); if (tTd(13, 21)) { sm_dprintf("\n================ Final Send Queue(s) =====================\n"); sm_dprintf("\n *** Envelope %s, e_from=%s ***\n", e->e_id, e->e_from.q_paddr); printaddr(sm_debug_file(), e->e_sendqueue, true); for (ee = splitenv; ee != NULL; ee = ee->e_sibling) { sm_dprintf("\n *** Envelope %s, e_from=%s ***\n", ee->e_id, ee->e_from.q_paddr); printaddr(sm_debug_file(), ee->e_sendqueue, true); } sm_dprintf("==========================================================\n\n"); } } switch (mode) { case SM_VERIFY: Verbose = 2; break; case SM_QUEUE: case SM_DEFER: #if HASFLOCK queueonly: #endif /* HASFLOCK */ if (e->e_nrcpts > 0) e->e_flags |= EF_INQUEUE; (void) dropenvelope(e, splitenv != NULL, true); for (ee = splitenv; ee != NULL; ee = ee->e_sibling) { if (ee->e_nrcpts > 0) ee->e_flags |= EF_INQUEUE; (void) dropenvelope(ee, false, true); } return; case SM_FORK: if (e->e_xfp != NULL) (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT); #if !HASFLOCK /* ** Since fcntl locking has the interesting semantic that ** the lock is owned by a process, not by an open file ** descriptor, we have to flush this to the queue, and ** then restart from scratch in the child. */ { /* save id for future use */ char *qid = e->e_id; /* now drop the envelope in the parent */ e->e_flags |= EF_INQUEUE; (void) dropenvelope(e, splitenv != NULL, false); /* arrange to reacquire lock after fork */ e->e_id = qid; } for (ee = splitenv; ee != NULL; ee = ee->e_sibling) { /* save id for future use */ char *qid = ee->e_id; /* drop envelope in parent */ ee->e_flags |= EF_INQUEUE; (void) dropenvelope(ee, false, false); /* and save qid for reacquisition */ ee->e_id = qid; } #endif /* !HASFLOCK */ /* ** Since the delivery may happen in a child and the parent ** does not wait, the parent may close the maps thereby ** removing any shared memory used by the map. Therefore, ** close the maps now so the child will dynamically open ** them if necessary. */ closemaps(false); pid = fork(); if (pid < 0) { syserr("deliver: fork 1"); #if HASFLOCK goto queueonly; #else /* HASFLOCK */ e->e_id = NULL; for (ee = splitenv; ee != NULL; ee = ee->e_sibling) ee->e_id = NULL; return; #endif /* HASFLOCK */ } else if (pid > 0) { #if HASFLOCK /* be sure we leave the temp files to our child */ /* close any random open files in the envelope */ closexscript(e); if (e->e_dfp != NULL) (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT); e->e_dfp = NULL; e->e_flags &= ~EF_HAS_DF; /* can't call unlockqueue to avoid unlink of xfp */ if (e->e_lockfp != NULL) (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT); else syserr("%s: sendall: null lockfp", e->e_id); e->e_lockfp = NULL; #endif /* HASFLOCK */ /* make sure the parent doesn't own the envelope */ e->e_id = NULL; #if USE_DOUBLE_FORK /* catch intermediate zombie */ (void) waitfor(pid); #endif /* USE_DOUBLE_FORK */ return; } /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; /* ** Initialize exception stack and default exception ** handler for child process. */ sm_exc_newthread(fatal_error); /* ** Since we have accepted responsbility for the message, ** change the SIGTERM handler. intsig() (the old handler) ** would remove the envelope if this was a command line ** message submission. */ (void) sm_signal(SIGTERM, SIG_DFL); #if USE_DOUBLE_FORK /* double fork to avoid zombies */ pid = fork(); if (pid > 0) exit(EX_OK); save_errno = errno; #endif /* USE_DOUBLE_FORK */ CurrentPid = getpid(); /* be sure we are immune from the terminal */ disconnect(2, e); clearstats(); /* prevent parent from waiting if there was an error */ if (pid < 0) { errno = save_errno; syserr("deliver: fork 2"); #if HASFLOCK e->e_flags |= EF_INQUEUE; #else /* HASFLOCK */ e->e_id = NULL; #endif /* HASFLOCK */ finis(true, true, ExitStat); } /* be sure to give error messages in child */ QuickAbort = false; /* ** Close any cached connections. ** ** We don't send the QUIT protocol because the parent ** still knows about the connection. ** ** This should only happen when delivering an error ** message. */ mci_flush(false, NULL); #if HASFLOCK break; #else /* HASFLOCK */ /* ** Now reacquire and run the various queue files. */ for (ee = splitenv; ee != NULL; ee = ee->e_sibling) { ENVELOPE *sibling = ee->e_sibling; (void) dowork(ee->e_qgrp, ee->e_qdir, ee->e_id, false, false, ee); ee->e_sibling = sibling; } (void) dowork(e->e_qgrp, e->e_qdir, e->e_id, false, false, e); finis(true, true, ExitStat); #endif /* HASFLOCK */ } sendenvelope(e, mode); (void) dropenvelope(e, true, true); for (ee = splitenv; ee != NULL; ee = ee->e_sibling) { CurEnv = ee; if (mode != SM_VERIFY) openxscript(ee); sendenvelope(ee, mode); (void) dropenvelope(ee, true, true); } CurEnv = e; Verbose = oldverbose; if (mode == SM_FORK) finis(true, true, ExitStat); } static void sendenvelope(e, mode) register ENVELOPE *e; int mode; { register ADDRESS *q; bool didany; if (tTd(13, 10)) sm_dprintf("sendenvelope(%s) e_flags=0x%lx\n", e->e_id == NULL ? "[NOQUEUE]" : e->e_id, e->e_flags); if (LogLevel > 80) sm_syslog(LOG_DEBUG, e->e_id, "sendenvelope, flags=0x%lx", e->e_flags); /* ** If we have had global, fatal errors, don't bother sending ** the message at all if we are in SMTP mode. Local errors ** (e.g., a single address failing) will still cause the other ** addresses to be sent. */ if (bitset(EF_FATALERRS, e->e_flags) && (OpMode == MD_SMTP || OpMode == MD_DAEMON)) { e->e_flags |= EF_CLRQUEUE; return; } /* ** Don't attempt deliveries if we want to bounce now ** or if deliver-by time is exceeded. */ if (!bitset(EF_RESPONSE, e->e_flags) && (TimeOuts.to_q_return[e->e_timeoutclass] == NOW || (IS_DLVR_RETURN(e) && e->e_deliver_by > 0 && curtime() > e->e_ctime + e->e_deliver_by))) return; /* ** Run through the list and send everything. ** ** Set EF_GLOBALERRS so that error messages during delivery ** result in returned mail. */ e->e_nsent = 0; e->e_flags |= EF_GLOBALERRS; macdefine(&e->e_macro, A_PERM, macid("{envid}"), e->e_envid); macdefine(&e->e_macro, A_PERM, macid("{bodytype}"), e->e_bodytype); didany = false; if (!bitset(EF_SPLIT, e->e_flags)) { ENVELOPE *oldsib; ENVELOPE *ee; /* ** Save old sibling and set it to NULL to avoid ** queueing up the same envelopes again. ** This requires that envelopes in that list have ** been take care of before (or at some other place). */ oldsib = e->e_sibling; e->e_sibling = NULL; if (!split_by_recipient(e) && bitset(EF_FATALERRS, e->e_flags)) { if (OpMode == MD_SMTP || OpMode == MD_DAEMON) e->e_flags |= EF_CLRQUEUE; return; } for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling) queueup(ee, false, true); /* clean up */ for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling) { /* now unlock the job */ closexscript(ee); unlockqueue(ee); /* this envelope is marked unused */ if (ee->e_dfp != NULL) { (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT); ee->e_dfp = NULL; } ee->e_id = NULL; ee->e_flags &= ~EF_HAS_DF; } e->e_sibling = oldsib; } /* now run through the queue */ for (q = e->e_sendqueue; q != NULL; q = q->q_next) { #if XDEBUG char wbuf[MAXNAME + 20]; (void) sm_snprintf(wbuf, sizeof(wbuf), "sendall(%.*s)", MAXNAME, q->q_paddr); checkfd012(wbuf); #endif /* XDEBUG */ if (mode == SM_VERIFY) { e->e_to = q->q_paddr; if (QS_IS_SENDABLE(q->q_state)) { if (q->q_host != NULL && q->q_host[0] != '\0') message("deliverable: mailer %s, host %s, user %s", q->q_mailer->m_name, q->q_host, q->q_user); else message("deliverable: mailer %s, user %s", q->q_mailer->m_name, q->q_user); } } else if (QS_IS_OK(q->q_state)) { /* ** Checkpoint the send list every few addresses */ if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval) { queueup(e, false, false); e->e_nsent = 0; } (void) deliver(e, q); didany = true; } } if (didany) { e->e_dtime = curtime(); e->e_ntries++; } #if XDEBUG checkfd012("end of sendenvelope"); #endif /* XDEBUG */ } #if REQUIRES_DIR_FSYNC /* ** SYNC_DIR -- fsync a directory based on a filename ** ** Parameters: ** filename -- path of file ** panic -- panic? ** ** Returns: ** none */ void sync_dir(filename, panic) char *filename; bool panic; { int dirfd; char *dirp; char dir[MAXPATHLEN]; if (!RequiresDirfsync) return; /* filesystems which require the directory be synced */ dirp = strrchr(filename, '/'); if (dirp != NULL) { if (sm_strlcpy(dir, filename, sizeof(dir)) >= sizeof(dir)) return; dir[dirp - filename] = '\0'; dirp = dir; } else dirp = "."; dirfd = open(dirp, O_RDONLY, 0700); if (tTd(40,32)) sm_syslog(LOG_INFO, NOQID, "sync_dir: %s: fsync(%d)", dirp, dirfd); if (dirfd >= 0) { if (fsync(dirfd) < 0) { if (panic) syserr("!sync_dir: cannot fsync directory %s", dirp); else if (LogLevel > 1) sm_syslog(LOG_ERR, NOQID, "sync_dir: cannot fsync directory %s: %s", dirp, sm_errstring(errno)); } (void) close(dirfd); } } #endif /* REQUIRES_DIR_FSYNC */ /* ** DUP_QUEUE_FILE -- duplicate a queue file into a split queue ** ** Parameters: ** e -- the existing envelope ** ee -- the new envelope ** type -- the queue file type (e.g., DATAFL_LETTER) ** ** Returns: ** none */ static void dup_queue_file(e, ee, type) ENVELOPE *e, *ee; int type; { char f1buf[MAXPATHLEN], f2buf[MAXPATHLEN]; ee->e_dfp = NULL; ee->e_xfp = NULL; /* ** Make sure both are in the same directory. */ (void) sm_strlcpy(f1buf, queuename(e, type), sizeof(f1buf)); (void) sm_strlcpy(f2buf, queuename(ee, type), sizeof(f2buf)); /* Force the df to disk if it's not there yet */ if (type == DATAFL_LETTER && e->e_dfp != NULL && sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 && errno != EINVAL) { syserr("!dup_queue_file: can't commit %s", f1buf); /* NOTREACHED */ } if (link(f1buf, f2buf) < 0) { int save_errno = errno; syserr("sendall: link(%s, %s)", f1buf, f2buf); if (save_errno == EEXIST) { if (unlink(f2buf) < 0) { syserr("!sendall: unlink(%s): permanent", f2buf); /* NOTREACHED */ } if (link(f1buf, f2buf) < 0) { syserr("!sendall: link(%s, %s): permanent", f1buf, f2buf); /* NOTREACHED */ } } } SYNC_DIR(f2buf, true); } /* ** DOFORK -- do a fork, retrying a couple of times on failure. ** ** This MUST be a macro, since after a vfork we are running ** two processes on the same stack!!! ** ** Parameters: ** none. ** ** Returns: ** From a macro??? You've got to be kidding! ** ** Side Effects: ** Modifies the ==> LOCAL <== variable 'pid', leaving: ** pid of child in parent, zero in child. ** -1 on unrecoverable error. ** ** Notes: ** I'm awfully sorry this looks so awful. That's ** vfork for you..... */ #define NFORKTRIES 5 #ifndef FORK # define FORK fork #endif /* ! FORK */ #define DOFORK(fORKfN) \ {\ register int i;\ \ for (i = NFORKTRIES; --i >= 0; )\ {\ pid = fORKfN();\ if (pid >= 0)\ break;\ if (i > 0)\ (void) sleep((unsigned) NFORKTRIES - i);\ }\ } /* ** DOFORK -- simple fork interface to DOFORK. ** ** Parameters: ** none. ** ** Returns: ** pid of child in parent. ** zero in child. ** -1 on error. ** ** Side Effects: ** returns twice, once in parent and once in child. */ pid_t dofork() { register pid_t pid = -1; DOFORK(fork); return pid; } /* ** COLONCMP -- compare host-signatures up to first ':' or EOS ** ** This takes two strings which happen to be host-signatures and ** compares them. If the lowest preference portions of the MX-RR's ** match (up to ':' or EOS, whichever is first), then we have ** match. This is used for coattail-piggybacking messages during ** message delivery. ** If the signatures are the same up to the first ':' the remainder of ** the signatures are then compared with a normal strcmp(). This saves ** re-examining the first part of the signatures. ** ** Parameters: ** a - first host-signature ** b - second host-signature ** ** Returns: ** HS_MATCH_NO -- no "match". ** HS_MATCH_FIRST -- "match" for the first MX preference ** (up to the first colon (':')). ** HS_MATCH_FULL -- match for the entire MX record. ** ** Side Effects: ** none. */ #define HS_MATCH_NO 0 #define HS_MATCH_FIRST 1 #define HS_MATCH_FULL 2 static int coloncmp(a, b) register const char *a; register const char *b; { int ret = HS_MATCH_NO; int braclev = 0; while (*a == *b++) { /* Need to account for IPv6 bracketed addresses */ if (*a == '[') braclev++; else if (*a == ']' && braclev > 0) braclev--; else if (*a == ':' && braclev <= 0) { ret = HS_MATCH_FIRST; a++; break; } else if (*a == '\0') return HS_MATCH_FULL; /* a full match */ a++; } if (ret == HS_MATCH_NO && braclev <= 0 && ((*a == '\0' && *(b - 1) == ':') || (*a == ':' && *(b - 1) == '\0'))) return HS_MATCH_FIRST; if (ret == HS_MATCH_FIRST && strcmp(a, b) == 0) return HS_MATCH_FULL; return ret; } /* ** SHOULD_TRY_FBSH -- Should try FallbackSmartHost? ** ** Parameters: ** e -- envelope ** tried_fallbacksmarthost -- has been tried already? (in/out) ** hostbuf -- buffer for hostname (expand FallbackSmartHost) (out) ** hbsz -- size of hostbuf ** status -- current delivery status ** ** Returns: ** true iff FallbackSmartHost should be tried. */ static bool should_try_fbsh __P((ENVELOPE *, bool *, char *, size_t, int)); static bool should_try_fbsh(e, tried_fallbacksmarthost, hostbuf, hbsz, status) ENVELOPE *e; bool *tried_fallbacksmarthost; char *hostbuf; size_t hbsz; int status; { /* ** If the host was not found or a temporary failure occurred ** and a FallbackSmartHost is defined (and we have not yet ** tried it), then make one last try with it as the host. */ if ((status == EX_NOHOST || status == EX_TEMPFAIL) && FallbackSmartHost != NULL && !*tried_fallbacksmarthost) { *tried_fallbacksmarthost = true; expand(FallbackSmartHost, hostbuf, hbsz, e); if (!wordinclass(hostbuf, 'w')) { if (tTd(11, 1)) sm_dprintf("one last try with FallbackSmartHost %s\n", hostbuf); return true; } } return false; } /* ** DELIVER -- Deliver a message to a list of addresses. ** ** This routine delivers to everyone on the same host as the ** user on the head of the list. It is clever about mailers ** that don't handle multiple users. It is NOT guaranteed ** that it will deliver to all these addresses however -- so ** deliver should be called once for each address on the ** list. ** Deliver tries to be as opportunistic as possible about piggybacking ** messages. Some definitions to make understanding easier follow below. ** Piggybacking occurs when an existing connection to a mail host can ** be used to send the same message to more than one recipient at the ** same time. So "no piggybacking" means one message for one recipient ** per connection. "Intentional piggybacking" happens when the ** recipients' host address (not the mail host address) is used to ** attempt piggybacking. Recipients with the same host address ** have the same mail host. "Coincidental piggybacking" relies on ** piggybacking based on all the mail host addresses in the MX-RR. This ** is "coincidental" in the fact it could not be predicted until the ** MX Resource Records for the hosts were obtained and examined. For ** example (preference order and equivalence is important, not values): ** domain1 IN MX 10 mxhost-A ** IN MX 20 mxhost-B ** domain2 IN MX 4 mxhost-A ** IN MX 8 mxhost-B ** Domain1 and domain2 can piggyback the same message to mxhost-A or ** mxhost-B (if mxhost-A cannot be reached). ** "Coattail piggybacking" relaxes the strictness of "coincidental ** piggybacking" in the hope that most significant (lowest value) ** MX preference host(s) can create more piggybacking. For example ** (again, preference order and equivalence is important, not values): ** domain3 IN MX 100 mxhost-C ** IN MX 100 mxhost-D ** IN MX 200 mxhost-E ** domain4 IN MX 50 mxhost-C ** IN MX 50 mxhost-D ** IN MX 80 mxhost-F ** A message for domain3 and domain4 can piggyback to mxhost-C if mxhost-C ** is available. Same with mxhost-D because in both RR's the preference ** value is the same as mxhost-C, respectively. ** So deliver attempts coattail piggybacking when possible. If the ** first MX preference level hosts cannot be used then the piggybacking ** reverts to coincidental piggybacking. Using the above example you ** cannot deliver to mxhost-F for domain3 regardless of preference value. ** ("Coattail" from "riding on the coattails of your predecessor" meaning ** gaining benefit from a predecessor effort with no or little addition ** effort. The predecessor here being the preceding MX RR). ** ** Parameters: ** e -- the envelope to deliver. ** firstto -- head of the address list to deliver to. ** ** Returns: ** zero -- successfully delivered. ** else -- some failure, see ExitStat for more info. ** ** Side Effects: ** The standard input is passed off to someone. */ static int deliver(e, firstto) register ENVELOPE *e; ADDRESS *firstto; { char *host; /* host being sent to */ char *user; /* user being sent to */ char **pvp; register char **mvp; register char *p; register MAILER *m; /* mailer for this recipient */ ADDRESS *volatile ctladdr; #if HASSETUSERCONTEXT ADDRESS *volatile contextaddr = NULL; #endif /* HASSETUSERCONTEXT */ register MCI *volatile mci; register ADDRESS *SM_NONVOLATILE to = firstto; volatile bool clever = false; /* running user smtp to this mailer */ ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */ int rcode; /* response code */ SM_NONVOLATILE int lmtp_rcode = EX_OK; SM_NONVOLATILE int nummxhosts = 0; /* number of MX hosts available */ SM_NONVOLATILE int hostnum = 0; /* current MX host index */ char *firstsig; /* signature of firstto */ volatile pid_t pid = -1; char *volatile curhost; SM_NONVOLATILE unsigned short port = 0; SM_NONVOLATILE time_t enough = 0; #if NETUNIX char *SM_NONVOLATILE mux_path = NULL; /* path to UNIX domain socket */ #endif /* NETUNIX */ time_t xstart; bool suidwarn; bool anyok; /* at least one address was OK */ SM_NONVOLATILE bool goodmxfound = false; /* at least one MX was OK */ bool ovr; bool quarantine; int strsize; int rcptcount; int ret; static int tobufsize = 0; static char *tobuf = NULL; char *rpath; /* translated return path */ int mpvect[2]; int rpvect[2]; char *mxhosts[MAXMXHOSTS + 1]; char *pv[MAXPV + 1]; char buf[MAXNAME + 1]; char cbuf[MAXPATHLEN]; errno = 0; SM_REQUIRE(firstto != NULL); /* same as to */ if (!QS_IS_OK(to->q_state)) return 0; suidwarn = geteuid() == 0; SM_REQUIRE(e != NULL); m = to->q_mailer; host = to->q_host; CurEnv = e; /* just in case */ e->e_statmsg = NULL; SmtpError[0] = '\0'; xstart = curtime(); if (tTd(10, 1)) sm_dprintf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n", e->e_id, m->m_name, host, to->q_user); if (tTd(10, 100)) printopenfds(false); /* ** Clear {client_*} macros if this is a bounce message to ** prevent rejection by check_compat ruleset. */ if (bitset(EF_RESPONSE, e->e_flags)) { macdefine(&e->e_macro, A_PERM, macid("{client_name}"), ""); macdefine(&e->e_macro, A_PERM, macid("{client_ptr}"), ""); macdefine(&e->e_macro, A_PERM, macid("{client_addr}"), ""); macdefine(&e->e_macro, A_PERM, macid("{client_port}"), ""); macdefine(&e->e_macro, A_PERM, macid("{client_resolve}"), ""); } SM_TRY { ADDRESS *skip_back = NULL; /* ** Do initial argv setup. ** Insert the mailer name. Notice that $x expansion is ** NOT done on the mailer name. Then, if the mailer has ** a picky -f flag, we insert it as appropriate. This ** code does not check for 'pv' overflow; this places a ** manifest lower limit of 4 for MAXPV. ** The from address rewrite is expected to make ** the address relative to the other end. */ /* rewrite from address, using rewriting rules */ rcode = EX_OK; SM_ASSERT(e->e_from.q_mailer != NULL); if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags)) p = e->e_sender; else p = e->e_from.q_paddr; rpath = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e); if (strlen(rpath) > MAXNAME) { rpath = shortenstring(rpath, MAXSHORTSTR); /* avoid bogus errno */ errno = 0; syserr("remotename: huge return path %s", rpath); } rpath = sm_rpool_strdup_x(e->e_rpool, rpath); macdefine(&e->e_macro, A_PERM, 'g', rpath); macdefine(&e->e_macro, A_PERM, 'h', host); Errors = 0; pvp = pv; *pvp++ = m->m_argv[0]; /* ignore long term host status information if mailer flag W is set */ if (bitnset(M_NOHOSTSTAT, m->m_flags)) IgnoreHostStatus = true; /* insert -f or -r flag as appropriate */ if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags))) { if (bitnset(M_FOPT, m->m_flags)) *pvp++ = "-f"; else *pvp++ = "-r"; *pvp++ = rpath; } /* ** Append the other fixed parts of the argv. These run ** up to the first entry containing "$u". There can only ** be one of these, and there are only a few more slots ** in the pv after it. */ for (mvp = m->m_argv; (p = *++mvp) != NULL; ) { /* can't use strchr here because of sign extension problems */ while (*p != '\0') { if ((*p++ & 0377) == MACROEXPAND) { if (*p == 'u') break; } } if (*p != '\0') break; /* this entry is safe -- go ahead and process it */ expand(*mvp, buf, sizeof(buf), e); *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf); if (pvp >= &pv[MAXPV - 3]) { syserr("554 5.3.5 Too many parameters to %s before $u", pv[0]); rcode = -1; goto cleanup; } } /* ** If we have no substitution for the user name in the argument ** list, we know that we must supply the names otherwise -- and ** SMTP is the answer!! */ if (*mvp == NULL) { /* running LMTP or SMTP */ clever = true; *pvp = NULL; } else if (bitnset(M_LMTP, m->m_flags)) { /* not running LMTP */ sm_syslog(LOG_ERR, NULL, "Warning: mailer %s: LMTP flag (F=z) turned off", m->m_name); clrbitn(M_LMTP, m->m_flags); } /* ** At this point *mvp points to the argument with $u. We ** run through our address list and append all the addresses ** we can. If we run out of space, do not fret! We can ** always send another copy later. */ e->e_to = NULL; strsize = 2; rcptcount = 0; ctladdr = NULL; if (firstto->q_signature == NULL) firstto->q_signature = hostsignature(firstto->q_mailer, firstto->q_host); firstsig = firstto->q_signature; for (; to != NULL; to = to->q_next) { /* avoid sending multiple recipients to dumb mailers */ if (tochain != NULL && !bitnset(M_MUSER, m->m_flags)) break; /* if already sent or not for this host, don't send */ if (!QS_IS_OK(to->q_state)) /* already sent; look at next */ continue; /* ** Must be same mailer to keep grouping rcpts. ** If mailers don't match: continue; sendqueue is not ** sorted by mailers, so don't break; */ if (to->q_mailer != firstto->q_mailer) continue; if (to->q_signature == NULL) /* for safety */ to->q_signature = hostsignature(to->q_mailer, to->q_host); /* ** This is for coincidental and tailcoat piggybacking messages ** to the same mail host. While the signatures are identical ** (that's the MX-RR's are identical) we can do coincidental ** piggybacking. We try hard for coattail piggybacking ** with the same mail host when the next recipient has the ** same host at lowest preference. It may be that this ** won't work out, so 'skip_back' is maintained if a backup ** to coincidental piggybacking or full signature must happen. */ ret = firstto == to ? HS_MATCH_FULL : coloncmp(to->q_signature, firstsig); if (ret == HS_MATCH_FULL) skip_back = to; else if (ret == HS_MATCH_NO) break; if (!clever) { /* avoid overflowing tobuf */ strsize += strlen(to->q_paddr) + 1; if (strsize > TOBUFSIZE) break; } if (++rcptcount > to->q_mailer->m_maxrcpt) break; if (tTd(10, 1)) { sm_dprintf("\nsend to "); printaddr(sm_debug_file(), to, false); } /* compute effective uid/gid when sending */ if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags)) # if HASSETUSERCONTEXT contextaddr = ctladdr = getctladdr(to); # else /* HASSETUSERCONTEXT */ ctladdr = getctladdr(to); # endif /* HASSETUSERCONTEXT */ if (tTd(10, 2)) { sm_dprintf("ctladdr="); printaddr(sm_debug_file(), ctladdr, false); } user = to->q_user; e->e_to = to->q_paddr; /* ** Check to see that these people are allowed to ** talk to each other. ** Check also for overflow of e_msgsize. */ if (m->m_maxsize != 0 && (e->e_msgsize > m->m_maxsize || e->e_msgsize < 0)) { e->e_flags |= EF_NO_BODY_RETN; if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags)) to->q_status = "5.2.3"; else to->q_status = "5.3.4"; /* set to->q_rstatus = NULL; or to the following? */ usrerrenh(to->q_status, "552 Message is too large; %ld bytes max", m->m_maxsize); markfailure(e, to, NULL, EX_UNAVAILABLE, false); giveresponse(EX_UNAVAILABLE, to->q_status, m, NULL, ctladdr, xstart, e, to); continue; } SM_SET_H_ERRNO(0); ovr = true; /* do config file checking of compatibility */ quarantine = (e->e_quarmsg != NULL); rcode = rscheck("check_compat", e->e_from.q_paddr, to->q_paddr, e, RSF_RMCOMM|RSF_COUNT, 3, NULL, e->e_id, NULL); if (rcode == EX_OK) { /* do in-code checking if not discarding */ if (!bitset(EF_DISCARD, e->e_flags)) { rcode = checkcompat(to, e); ovr = false; } } if (rcode != EX_OK) { markfailure(e, to, NULL, rcode, ovr); giveresponse(rcode, to->q_status, m, NULL, ctladdr, xstart, e, to); continue; } if (!quarantine && e->e_quarmsg != NULL) { /* ** check_compat or checkcompat() has tried ** to quarantine but that isn't supported. ** Revert the attempt. */ e->e_quarmsg = NULL; macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), ""); } if (bitset(EF_DISCARD, e->e_flags)) { if (tTd(10, 5)) { sm_dprintf("deliver: discarding recipient "); printaddr(sm_debug_file(), to, false); } /* pretend the message was sent */ /* XXX should we log something here? */ to->q_state = QS_DISCARDED; /* ** Remove discard bit to prevent discard of ** future recipients. This is safe because the ** true "global discard" has been handled before ** we get here. */ e->e_flags &= ~EF_DISCARD; continue; } /* ** Strip quote bits from names if the mailer is dumb ** about them. */ if (bitnset(M_STRIPQ, m->m_flags)) { stripquotes(user); stripquotes(host); } /* ** Strip all leading backslashes if requested and the ** next character is alphanumerical (the latter can ** probably relaxed a bit, see RFC2821). */ if (bitnset(M_STRIPBACKSL, m->m_flags) && user[0] == '\\') stripbackslash(user); /* hack attack -- delivermail compatibility */ if (m == ProgMailer && *user == '|') user++; /* ** If an error message has already been given, don't ** bother to send to this address. ** ** >>>>>>>>>> This clause assumes that the local mailer ** >> NOTE >> cannot do any further aliasing; that ** >>>>>>>>>> function is subsumed by sendmail. */ if (!QS_IS_OK(to->q_state)) continue; /* ** See if this user name is "special". ** If the user name has a slash in it, assume that this ** is a file -- send it off without further ado. Note ** that this type of addresses is not processed along ** with the others, so we fudge on the To person. */ if (strcmp(m->m_mailer, "[FILE]") == 0) { macdefine(&e->e_macro, A_PERM, 'u', user); p = to->q_home; if (p == NULL && ctladdr != NULL) p = ctladdr->q_home; macdefine(&e->e_macro, A_PERM, 'z', p); expand(m->m_argv[1], buf, sizeof(buf), e); if (strlen(buf) > 0) rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e); else { syserr("empty filename specification for mailer %s", m->m_name); rcode = EX_CONFIG; } giveresponse(rcode, to->q_status, m, NULL, ctladdr, xstart, e, to); markfailure(e, to, NULL, rcode, true); e->e_nsent++; if (rcode == EX_OK) { to->q_state = QS_SENT; if (bitnset(M_LOCALMAILER, m->m_flags) && bitset(QPINGONSUCCESS, to->q_flags)) { to->q_flags |= QDELIVERED; to->q_status = "2.1.5"; (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s... Successfully delivered\n", to->q_paddr); } } to->q_statdate = curtime(); markstats(e, to, STATS_NORMAL); continue; } /* ** Address is verified -- add this user to mailer ** argv, and add it to the print list of recipients. */ /* link together the chain of recipients */ to->q_tchain = tochain; tochain = to; e->e_to = "[CHAIN]"; macdefine(&e->e_macro, A_PERM, 'u', user); /* to user */ p = to->q_home; if (p == NULL && ctladdr != NULL) p = ctladdr->q_home; macdefine(&e->e_macro, A_PERM, 'z', p); /* user's home */ /* set the ${dsn_notify} macro if applicable */ if (bitset(QHASNOTIFY, to->q_flags)) { char notify[MAXLINE]; notify[0] = '\0'; if (bitset(QPINGONSUCCESS, to->q_flags)) (void) sm_strlcat(notify, "SUCCESS,", sizeof(notify)); if (bitset(QPINGONFAILURE, to->q_flags)) (void) sm_strlcat(notify, "FAILURE,", sizeof(notify)); if (bitset(QPINGONDELAY, to->q_flags)) (void) sm_strlcat(notify, "DELAY,", sizeof(notify)); /* Set to NEVER or drop trailing comma */ if (notify[0] == '\0') (void) sm_strlcat(notify, "NEVER", sizeof(notify)); else notify[strlen(notify) - 1] = '\0'; macdefine(&e->e_macro, A_TEMP, macid("{dsn_notify}"), notify); } else macdefine(&e->e_macro, A_PERM, macid("{dsn_notify}"), NULL); /* ** Expand out this user into argument list. */ if (!clever) { expand(*mvp, buf, sizeof(buf), e); *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf); if (pvp >= &pv[MAXPV - 2]) { /* allow some space for trailing parms */ break; } } } /* see if any addresses still exist */ if (tochain == NULL) { rcode = 0; goto cleanup; } /* print out messages as full list */ strsize = 1; for (to = tochain; to != NULL; to = to->q_tchain) strsize += strlen(to->q_paddr) + 1; if (strsize < TOBUFSIZE) strsize = TOBUFSIZE; if (strsize > tobufsize) { SM_FREE_CLR(tobuf); tobuf = sm_pmalloc_x(strsize); tobufsize = strsize; } p = tobuf; *p = '\0'; for (to = tochain; to != NULL; to = to->q_tchain) { (void) sm_strlcpyn(p, tobufsize - (p - tobuf), 2, ",", to->q_paddr); p += strlen(p); } e->e_to = tobuf + 1; /* ** Fill out any parameters after the $u parameter. */ if (!clever) { while (*++mvp != NULL) { expand(*mvp, buf, sizeof(buf), e); *pvp++ = sm_rpool_strdup_x(e->e_rpool, buf); if (pvp >= &pv[MAXPV]) syserr("554 5.3.0 deliver: pv overflow after $u for %s", pv[0]); } } *pvp++ = NULL; /* ** Call the mailer. ** The argument vector gets built, pipes ** are created as necessary, and we fork & exec as ** appropriate. ** If we are running SMTP, we just need to clean up. */ /* XXX this seems a bit weird */ if (ctladdr == NULL && m != ProgMailer && m != FileMailer && bitset(QGOODUID, e->e_from.q_flags)) ctladdr = &e->e_from; #if NAMED_BIND if (ConfigLevel < 2) _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */ #endif /* NAMED_BIND */ if (tTd(11, 1)) { sm_dprintf("openmailer:"); printav(sm_debug_file(), pv); } errno = 0; SM_SET_H_ERRNO(0); CurHostName = NULL; /* ** Deal with the special case of mail handled through an IPC ** connection. ** In this case we don't actually fork. We must be ** running SMTP for this to work. We will return a ** zero pid to indicate that we are running IPC. ** We also handle a debug version that just talks to stdin/out. */ curhost = NULL; SmtpPhase = NULL; mci = NULL; #if XDEBUG { char wbuf[MAXLINE]; /* make absolutely certain 0, 1, and 2 are in use */ (void) sm_snprintf(wbuf, sizeof(wbuf), "%s... openmailer(%s)", shortenstring(e->e_to, MAXSHORTSTR), m->m_name); checkfd012(wbuf); } #endif /* XDEBUG */ /* check for 8-bit available */ if (bitset(EF_HAS8BIT, e->e_flags) && bitnset(M_7BITS, m->m_flags) && (bitset(EF_DONT_MIME, e->e_flags) || !(bitset(MM_MIME8BIT, MimeMode) || (bitset(EF_IS_MIME, e->e_flags) && bitset(MM_CVTMIME, MimeMode))))) { e->e_status = "5.6.3"; usrerrenh(e->e_status, "554 Cannot send 8-bit data to 7-bit destination"); rcode = EX_DATAERR; goto give_up; } if (tTd(62, 8)) checkfds("before delivery"); /* check for Local Person Communication -- not for mortals!!! */ if (strcmp(m->m_mailer, "[LPC]") == 0) { if (clever) { /* flush any expired connections */ (void) mci_scan(NULL); /* try to get a cached connection or just a slot */ mci = mci_get(m->m_name, m); if (mci->mci_host == NULL) mci->mci_host = m->m_name; CurHostName = mci->mci_host; if (mci->mci_state != MCIS_CLOSED) { message("Using cached SMTP/LPC connection for %s...", m->m_name); mci->mci_deliveries++; goto do_transfer; } } else { mci = mci_new(e->e_rpool); } mci->mci_in = smioin; mci->mci_out = smioout; mci->mci_mailer = m; mci->mci_host = m->m_name; if (clever) { mci->mci_state = MCIS_OPENING; mci_cache(mci); } else mci->mci_state = MCIS_OPEN; } else if (strcmp(m->m_mailer, "[IPC]") == 0) { register int i; if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0') { syserr("null destination for %s mailer", m->m_mailer); rcode = EX_CONFIG; goto give_up; } # if NETUNIX if (strcmp(pv[0], "FILE") == 0) { curhost = CurHostName = "localhost"; mux_path = pv[1]; } else # endif /* NETUNIX */ { CurHostName = pv[1]; curhost = hostsignature(m, pv[1]); } if (curhost == NULL || curhost[0] == '\0') { syserr("null host signature for %s", pv[1]); rcode = EX_CONFIG; goto give_up; } if (!clever) { syserr("554 5.3.5 non-clever IPC"); rcode = EX_CONFIG; goto give_up; } if (pv[2] != NULL # if NETUNIX && mux_path == NULL # endif /* NETUNIX */ ) { port = htons((unsigned short) atoi(pv[2])); if (port == 0) { # ifdef NO_GETSERVBYNAME syserr("Invalid port number: %s", pv[2]); # else /* NO_GETSERVBYNAME */ struct servent *sp = getservbyname(pv[2], "tcp"); if (sp == NULL) syserr("Service %s unknown", pv[2]); else port = sp->s_port; # endif /* NO_GETSERVBYNAME */ } } nummxhosts = parse_hostsignature(curhost, mxhosts, m); if (TimeOuts.to_aconnect > 0) enough = curtime() + TimeOuts.to_aconnect; tryhost: while (hostnum < nummxhosts) { char sep = ':'; char *endp; static char hostbuf[MAXNAME + 1]; bool tried_fallbacksmarthost = false; # if NETINET6 if (*mxhosts[hostnum] == '[') { endp = strchr(mxhosts[hostnum] + 1, ']'); if (endp != NULL) endp = strpbrk(endp + 1, ":,"); } else endp = strpbrk(mxhosts[hostnum], ":,"); # else /* NETINET6 */ endp = strpbrk(mxhosts[hostnum], ":,"); # endif /* NETINET6 */ if (endp != NULL) { sep = *endp; *endp = '\0'; } if (hostnum == 1 && skip_back != NULL) { /* ** Coattail piggybacking is no longer an ** option with the mail host next to be tried ** no longer the lowest MX preference ** (hostnum == 1 meaning we're on the second ** preference). We do not try to coattail ** piggyback more than the first MX preference. ** Revert 'tochain' to last location for ** coincidental piggybacking. This works this ** easily because the q_tchain kept getting ** added to the top of the linked list. */ tochain = skip_back; } if (*mxhosts[hostnum] == '\0') { syserr("deliver: null host name in signature"); hostnum++; if (endp != NULL) *endp = sep; continue; } (void) sm_strlcpy(hostbuf, mxhosts[hostnum], sizeof(hostbuf)); hostnum++; if (endp != NULL) *endp = sep; one_last_try: /* see if we already know that this host is fried */ CurHostName = hostbuf; mci = mci_get(hostbuf, m); if (mci->mci_state != MCIS_CLOSED) { char *type; if (tTd(11, 1)) { sm_dprintf("openmailer: "); mci_dump(sm_debug_file(), mci, false); } CurHostName = mci->mci_host; if (bitnset(M_LMTP, m->m_flags)) type = "L"; else if (bitset(MCIF_ESMTP, mci->mci_flags)) type = "ES"; else type = "S"; message("Using cached %sMTP connection to %s via %s...", type, hostbuf, m->m_name); mci->mci_deliveries++; break; } mci->mci_mailer = m; if (mci->mci_exitstat != EX_OK) { if (mci->mci_exitstat == EX_TEMPFAIL) goodmxfound = true; /* Try FallbackSmartHost? */ if (should_try_fbsh(e, &tried_fallbacksmarthost, hostbuf, sizeof(hostbuf), mci->mci_exitstat)) goto one_last_try; continue; } if (mci_lock_host(mci) != EX_OK) { mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL); goodmxfound = true; continue; } /* try the connection */ sm_setproctitle(true, e, "%s %s: %s", qid_printname(e), hostbuf, "user open"); # if NETUNIX if (mux_path != NULL) { message("Connecting to %s via %s...", mux_path, m->m_name); i = makeconnection_ds((char *) mux_path, mci); } else # endif /* NETUNIX */ { if (port == 0) message("Connecting to %s via %s...", hostbuf, m->m_name); else message("Connecting to %s port %d via %s...", hostbuf, ntohs(port), m->m_name); i = makeconnection(hostbuf, port, mci, e, enough); } mci->mci_errno = errno; mci->mci_lastuse = curtime(); mci->mci_deliveries = 0; mci->mci_exitstat = i; mci_clr_extensions(mci); # if NAMED_BIND mci->mci_herrno = h_errno; # endif /* NAMED_BIND */ /* ** Have we tried long enough to get a connection? ** If yes, skip to the fallback MX hosts ** (if existent). */ if (enough > 0 && mci->mci_lastuse >= enough) { int h; # if NAMED_BIND extern int NumFallbackMXHosts; # else /* NAMED_BIND */ const int NumFallbackMXHosts = 0; # endif /* NAMED_BIND */ if (hostnum < nummxhosts && LogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "Timeout.to_aconnect occurred before exhausting all addresses"); /* turn off timeout if fallback available */ if (NumFallbackMXHosts > 0) enough = 0; /* skip to a fallback MX host */ h = nummxhosts - NumFallbackMXHosts; if (hostnum < h) hostnum = h; } if (i == EX_OK) { goodmxfound = true; markstats(e, firstto, STATS_CONNECT); mci->mci_state = MCIS_OPENING; mci_cache(mci); if (TrafficLogFile != NULL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d === CONNECT %s\n", (int) CurrentPid, hostbuf); break; } else { /* Try FallbackSmartHost? */ if (should_try_fbsh(e, &tried_fallbacksmarthost, hostbuf, sizeof(hostbuf), i)) goto one_last_try; if (tTd(11, 1)) sm_dprintf("openmailer: makeconnection => stat=%d, errno=%d\n", i, errno); if (i == EX_TEMPFAIL) goodmxfound = true; mci_unlock_host(mci); } /* enter status of this host */ setstat(i); /* should print some message here for -v mode */ } if (mci == NULL) { syserr("deliver: no host name"); rcode = EX_SOFTWARE; goto give_up; } mci->mci_pid = 0; } else { /* flush any expired connections */ (void) mci_scan(NULL); mci = NULL; if (bitnset(M_LMTP, m->m_flags)) { /* try to get a cached connection */ mci = mci_get(m->m_name, m); if (mci->mci_host == NULL) mci->mci_host = m->m_name; CurHostName = mci->mci_host; if (mci->mci_state != MCIS_CLOSED) { message("Using cached LMTP connection for %s...", m->m_name); mci->mci_deliveries++; goto do_transfer; } } /* announce the connection to verbose listeners */ if (host == NULL || host[0] == '\0') message("Connecting to %s...", m->m_name); else message("Connecting to %s via %s...", host, m->m_name); if (TrafficLogFile != NULL) { char **av; (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d === EXEC", (int) CurrentPid); for (av = pv; *av != NULL; av++) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, " %s", *av); (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "\n"); } #if XDEBUG checkfd012("before creating mail pipe"); #endif /* XDEBUG */ /* create a pipe to shove the mail through */ if (pipe(mpvect) < 0) { syserr("%s... openmailer(%s): pipe (to mailer)", shortenstring(e->e_to, MAXSHORTSTR), m->m_name); if (tTd(11, 1)) sm_dprintf("openmailer: NULL\n"); rcode = EX_OSERR; goto give_up; } #if XDEBUG /* make sure we didn't get one of the standard I/O files */ if (mpvect[0] < 3 || mpvect[1] < 3) { syserr("%s... openmailer(%s): bogus mpvect %d %d", shortenstring(e->e_to, MAXSHORTSTR), m->m_name, mpvect[0], mpvect[1]); printopenfds(true); if (tTd(11, 1)) sm_dprintf("openmailer: NULL\n"); rcode = EX_OSERR; goto give_up; } /* make sure system call isn't dead meat */ checkfdopen(mpvect[0], "mpvect[0]"); checkfdopen(mpvect[1], "mpvect[1]"); if (mpvect[0] == mpvect[1] || (e->e_lockfp != NULL && (mpvect[0] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL) || mpvect[1] == sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL)))) { if (e->e_lockfp == NULL) syserr("%s... openmailer(%s): overlapping mpvect %d %d", shortenstring(e->e_to, MAXSHORTSTR), m->m_name, mpvect[0], mpvect[1]); else syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d", shortenstring(e->e_to, MAXSHORTSTR), m->m_name, mpvect[0], mpvect[1], sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL)); } #endif /* XDEBUG */ /* create a return pipe */ if (pipe(rpvect) < 0) { syserr("%s... openmailer(%s): pipe (from mailer)", shortenstring(e->e_to, MAXSHORTSTR), m->m_name); (void) close(mpvect[0]); (void) close(mpvect[1]); if (tTd(11, 1)) sm_dprintf("openmailer: NULL\n"); rcode = EX_OSERR; goto give_up; } #if XDEBUG checkfdopen(rpvect[0], "rpvect[0]"); checkfdopen(rpvect[1], "rpvect[1]"); #endif /* XDEBUG */ /* ** Actually fork the mailer process. ** DOFORK is clever about retrying. ** ** Dispose of SIGCHLD signal catchers that may be laying ** around so that endmailer will get it. */ if (e->e_xfp != NULL) /* for debugging */ (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT); (void) sm_io_flush(smioout, SM_TIME_DEFAULT); (void) sm_signal(SIGCHLD, SIG_DFL); DOFORK(FORK); /* pid is set by DOFORK */ if (pid < 0) { /* failure */ syserr("%s... openmailer(%s): cannot fork", shortenstring(e->e_to, MAXSHORTSTR), m->m_name); (void) close(mpvect[0]); (void) close(mpvect[1]); (void) close(rpvect[0]); (void) close(rpvect[1]); if (tTd(11, 1)) sm_dprintf("openmailer: NULL\n"); rcode = EX_OSERR; goto give_up; } else if (pid == 0) { int save_errno; int sff; int new_euid = NO_UID; int new_ruid = NO_UID; int new_gid = NO_GID; char *user = NULL; struct stat stb; extern int DtableSize; CurrentPid = getpid(); /* clear the events to turn off SIGALRMs */ sm_clear_events(); /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; if (e->e_lockfp != NULL) (void) close(sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL)); /* child -- set up input & exec mailer */ (void) sm_signal(SIGALRM, sm_signal_noop); (void) sm_signal(SIGCHLD, SIG_DFL); (void) sm_signal(SIGHUP, SIG_IGN); (void) sm_signal(SIGINT, SIG_IGN); (void) sm_signal(SIGTERM, SIG_DFL); # ifdef SIGUSR1 (void) sm_signal(SIGUSR1, sm_signal_noop); # endif /* SIGUSR1 */ if (m != FileMailer || stat(tochain->q_user, &stb) < 0) stb.st_mode = 0; # if HASSETUSERCONTEXT /* ** Set user resources. */ if (contextaddr != NULL) { int sucflags; struct passwd *pwd; if (contextaddr->q_ruser != NULL) pwd = sm_getpwnam(contextaddr->q_ruser); else pwd = sm_getpwnam(contextaddr->q_user); sucflags = LOGIN_SETRESOURCES|LOGIN_SETPRIORITY; #ifdef LOGIN_SETCPUMASK sucflags |= LOGIN_SETCPUMASK; #endif /* LOGIN_SETCPUMASK */ #ifdef LOGIN_SETLOGINCLASS sucflags |= LOGIN_SETLOGINCLASS; #endif /* LOGIN_SETLOGINCLASS */ #ifdef LOGIN_SETMAC sucflags |= LOGIN_SETMAC; #endif /* LOGIN_SETMAC */ if (pwd != NULL && setusercontext(NULL, pwd, pwd->pw_uid, sucflags) == -1 && suidwarn) { syserr("openmailer: setusercontext() failed"); exit(EX_TEMPFAIL); } } # endif /* HASSETUSERCONTEXT */ #if HASNICE /* tweak niceness */ if (m->m_nice != 0) (void) nice(m->m_nice); #endif /* HASNICE */ /* reset group id */ if (bitnset(M_SPECIFIC_UID, m->m_flags)) { if (m->m_gid == NO_GID) new_gid = RunAsGid; else new_gid = m->m_gid; } else if (bitset(S_ISGID, stb.st_mode)) new_gid = stb.st_gid; else if (ctladdr != NULL && ctladdr->q_gid != 0) { if (!DontInitGroups) { user = ctladdr->q_ruser; if (user == NULL) user = ctladdr->q_user; if (initgroups(user, ctladdr->q_gid) == -1 && suidwarn) { syserr("openmailer: initgroups(%s, %d) failed", user, ctladdr->q_gid); exit(EX_TEMPFAIL); } } else { GIDSET_T gidset[1]; gidset[0] = ctladdr->q_gid; if (setgroups(1, gidset) == -1 && suidwarn) { syserr("openmailer: setgroups() failed"); exit(EX_TEMPFAIL); } } new_gid = ctladdr->q_gid; } else { if (!DontInitGroups) { user = DefUser; if (initgroups(DefUser, DefGid) == -1 && suidwarn) { syserr("openmailer: initgroups(%s, %d) failed", DefUser, DefGid); exit(EX_TEMPFAIL); } } else { GIDSET_T gidset[1]; gidset[0] = DefGid; if (setgroups(1, gidset) == -1 && suidwarn) { syserr("openmailer: setgroups() failed"); exit(EX_TEMPFAIL); } } if (m->m_gid == NO_GID) new_gid = DefGid; else new_gid = m->m_gid; } if (new_gid != NO_GID) { if (RunAsUid != 0 && bitnset(M_SPECIFIC_UID, m->m_flags) && new_gid != getgid() && new_gid != getegid()) { /* Only root can change the gid */ syserr("openmailer: insufficient privileges to change gid, RunAsUid=%d, new_gid=%d, gid=%d, egid=%d", (int) RunAsUid, (int) new_gid, (int) getgid(), (int) getegid()); exit(EX_TEMPFAIL); } if (setgid(new_gid) < 0 && suidwarn) { syserr("openmailer: setgid(%ld) failed", (long) new_gid); exit(EX_TEMPFAIL); } } /* change root to some "safe" directory */ if (m->m_rootdir != NULL) { expand(m->m_rootdir, cbuf, sizeof(cbuf), e); if (tTd(11, 20)) sm_dprintf("openmailer: chroot %s\n", cbuf); if (chroot(cbuf) < 0) { syserr("openmailer: Cannot chroot(%s)", cbuf); exit(EX_TEMPFAIL); } if (chdir("/") < 0) { syserr("openmailer: cannot chdir(/)"); exit(EX_TEMPFAIL); } } /* reset user id */ endpwent(); sm_mbdb_terminate(); if (bitnset(M_SPECIFIC_UID, m->m_flags)) { if (m->m_uid == NO_UID) new_euid = RunAsUid; else new_euid = m->m_uid; /* ** Undo the effects of the uid change in main ** for signal handling. The real uid may ** be used by mailer in adding a "From " ** line. */ if (RealUid != 0 && RealUid != getuid()) { # if MAILER_SETUID_METHOD == USE_SETEUID # if HASSETREUID if (setreuid(RealUid, geteuid()) < 0) { syserr("openmailer: setreuid(%d, %d) failed", (int) RealUid, (int) geteuid()); exit(EX_OSERR); } # endif /* HASSETREUID */ # endif /* MAILER_SETUID_METHOD == USE_SETEUID */ # if MAILER_SETUID_METHOD == USE_SETREUID new_ruid = RealUid; # endif /* MAILER_SETUID_METHOD == USE_SETREUID */ } } else if (bitset(S_ISUID, stb.st_mode)) new_ruid = stb.st_uid; else if (ctladdr != NULL && ctladdr->q_uid != 0) new_ruid = ctladdr->q_uid; else if (m->m_uid != NO_UID) new_ruid = m->m_uid; else new_ruid = DefUid; # if _FFR_USE_SETLOGIN /* run disconnected from terminal and set login name */ if (setsid() >= 0 && ctladdr != NULL && ctladdr->q_uid != 0 && new_euid == ctladdr->q_uid) { struct passwd *pwd; pwd = sm_getpwuid(ctladdr->q_uid); if (pwd != NULL && suidwarn) (void) setlogin(pwd->pw_name); endpwent(); } # endif /* _FFR_USE_SETLOGIN */ if (new_euid != NO_UID) { if (RunAsUid != 0 && new_euid != RunAsUid) { /* Only root can change the uid */ syserr("openmailer: insufficient privileges to change uid, new_euid=%d, RunAsUid=%d", (int) new_euid, (int) RunAsUid); exit(EX_TEMPFAIL); } vendor_set_uid(new_euid); # if MAILER_SETUID_METHOD == USE_SETEUID if (seteuid(new_euid) < 0 && suidwarn) { syserr("openmailer: seteuid(%ld) failed", (long) new_euid); exit(EX_TEMPFAIL); } # endif /* MAILER_SETUID_METHOD == USE_SETEUID */ # if MAILER_SETUID_METHOD == USE_SETREUID if (setreuid(new_ruid, new_euid) < 0 && suidwarn) { syserr("openmailer: setreuid(%ld, %ld) failed", (long) new_ruid, (long) new_euid); exit(EX_TEMPFAIL); } # endif /* MAILER_SETUID_METHOD == USE_SETREUID */ # if MAILER_SETUID_METHOD == USE_SETUID if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn) { syserr("openmailer: setuid(%ld) failed", (long) new_euid); exit(EX_TEMPFAIL); } # endif /* MAILER_SETUID_METHOD == USE_SETUID */ } else if (new_ruid != NO_UID) { vendor_set_uid(new_ruid); if (setuid(new_ruid) < 0 && suidwarn) { syserr("openmailer: setuid(%ld) failed", (long) new_ruid); exit(EX_TEMPFAIL); } } if (tTd(11, 2)) sm_dprintf("openmailer: running as r/euid=%d/%d, r/egid=%d/%d\n", (int) getuid(), (int) geteuid(), (int) getgid(), (int) getegid()); /* move into some "safe" directory */ if (m->m_execdir != NULL) { char *q; for (p = m->m_execdir; p != NULL; p = q) { q = strchr(p, ':'); if (q != NULL) *q = '\0'; expand(p, cbuf, sizeof(cbuf), e); if (q != NULL) *q++ = ':'; if (tTd(11, 20)) sm_dprintf("openmailer: trydir %s\n", cbuf); if (cbuf[0] != '\0' && chdir(cbuf) >= 0) break; } } /* Check safety of program to be run */ sff = SFF_ROOTOK|SFF_EXECOK; if (!bitnset(DBS_RUNWRITABLEPROGRAM, DontBlameSendmail)) sff |= SFF_NOGWFILES|SFF_NOWWFILES; if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_NOPATHCHECK; else sff |= SFF_SAFEDIRPATH; ret = safefile(m->m_mailer, getuid(), getgid(), user, sff, 0, NULL); if (ret != 0) sm_syslog(LOG_INFO, e->e_id, "Warning: program %s unsafe: %s", m->m_mailer, sm_errstring(ret)); /* arrange to filter std & diag output of command */ (void) close(rpvect[0]); if (dup2(rpvect[1], STDOUT_FILENO) < 0) { syserr("%s... openmailer(%s): cannot dup pipe %d for stdout", shortenstring(e->e_to, MAXSHORTSTR), m->m_name, rpvect[1]); _exit(EX_OSERR); } (void) close(rpvect[1]); if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0) { syserr("%s... openmailer(%s): cannot dup stdout for stderr", shortenstring(e->e_to, MAXSHORTSTR), m->m_name); _exit(EX_OSERR); } /* arrange to get standard input */ (void) close(mpvect[1]); if (dup2(mpvect[0], STDIN_FILENO) < 0) { syserr("%s... openmailer(%s): cannot dup pipe %d for stdin", shortenstring(e->e_to, MAXSHORTSTR), m->m_name, mpvect[0]); _exit(EX_OSERR); } (void) close(mpvect[0]); /* arrange for all the files to be closed */ sm_close_on_exec(STDERR_FILENO + 1, DtableSize); # if !_FFR_USE_SETLOGIN /* run disconnected from terminal */ (void) setsid(); # endif /* !_FFR_USE_SETLOGIN */ /* try to execute the mailer */ (void) execve(m->m_mailer, (ARGV_T) pv, (ARGV_T) UserEnviron); save_errno = errno; syserr("Cannot exec %s", m->m_mailer); if (bitnset(M_LOCALMAILER, m->m_flags) || transienterror(save_errno)) _exit(EX_OSERR); _exit(EX_UNAVAILABLE); } /* ** Set up return value. */ if (mci == NULL) { if (clever) { /* ** Allocate from general heap, not ** envelope rpool, because this mci ** is going to be cached. */ mci = mci_new(NULL); } else { /* ** Prevent a storage leak by allocating ** this from the envelope rpool. */ mci = mci_new(e->e_rpool); } } mci->mci_mailer = m; if (clever) { mci->mci_state = MCIS_OPENING; mci_cache(mci); } else { mci->mci_state = MCIS_OPEN; } mci->mci_pid = pid; (void) close(mpvect[0]); mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &(mpvect[1]), SM_IO_WRONLY_B, NULL); if (mci->mci_out == NULL) { syserr("deliver: cannot create mailer output channel, fd=%d", mpvect[1]); (void) close(mpvect[1]); (void) close(rpvect[0]); (void) close(rpvect[1]); rcode = EX_OSERR; goto give_up; } (void) close(rpvect[1]); mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &(rpvect[0]), SM_IO_RDONLY_B, NULL); if (mci->mci_in == NULL) { syserr("deliver: cannot create mailer input channel, fd=%d", mpvect[1]); (void) close(rpvect[0]); (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT); mci->mci_out = NULL; rcode = EX_OSERR; goto give_up; } } /* ** If we are in SMTP opening state, send initial protocol. */ if (bitnset(M_7BITS, m->m_flags) && (!clever || mci->mci_state == MCIS_OPENING)) mci->mci_flags |= MCIF_7BIT; if (clever && mci->mci_state != MCIS_CLOSED) { # if STARTTLS || SASL int dotpos; char *srvname; extern SOCKADDR CurHostAddr; # endif /* STARTTLS || SASL */ # if SASL # define DONE_AUTH(f) bitset(MCIF_AUTHACT, f) # endif /* SASL */ # if STARTTLS # define DONE_STARTTLS(f) bitset(MCIF_TLSACT, f) # endif /* STARTTLS */ # define ONLY_HELO(f) bitset(MCIF_ONLY_EHLO, f) # define SET_HELO(f) f |= MCIF_ONLY_EHLO # define CLR_HELO(f) f &= ~MCIF_ONLY_EHLO # if STARTTLS || SASL /* don't use CurHostName, it is changed in many places */ if (mci->mci_host != NULL) { srvname = mci->mci_host; dotpos = strlen(srvname) - 1; if (dotpos >= 0) { if (srvname[dotpos] == '.') srvname[dotpos] = '\0'; else dotpos = -1; } } else if (mci->mci_mailer != NULL) { srvname = mci->mci_mailer->m_name; dotpos = -1; } else { srvname = "local"; dotpos = -1; } /* don't set {server_name} to NULL or "": see getauth() */ macdefine(&mci->mci_macro, A_TEMP, macid("{server_name}"), srvname); /* CurHostAddr is set by makeconnection() and mci_get() */ if (CurHostAddr.sa.sa_family != 0) { macdefine(&mci->mci_macro, A_TEMP, macid("{server_addr}"), anynet_ntoa(&CurHostAddr)); } else if (mci->mci_mailer != NULL) { /* mailer name is unique, use it as address */ macdefine(&mci->mci_macro, A_PERM, macid("{server_addr}"), mci->mci_mailer->m_name); } else { /* don't set it to NULL or "": see getauth() */ macdefine(&mci->mci_macro, A_PERM, macid("{server_addr}"), "0"); } /* undo change of srvname (mci->mci_host) */ if (dotpos >= 0) srvname[dotpos] = '.'; reconnect: /* after switching to an encrypted connection */ # endif /* STARTTLS || SASL */ /* set the current connection information */ e->e_mci = mci; # if SASL mci->mci_saslcap = NULL; # endif /* SASL */ smtpinit(m, mci, e, ONLY_HELO(mci->mci_flags)); CLR_HELO(mci->mci_flags); if (IS_DLVR_RETURN(e)) { /* ** Check whether other side can deliver e-mail ** fast enough */ if (!bitset(MCIF_DLVR_BY, mci->mci_flags)) { e->e_status = "5.4.7"; usrerrenh(e->e_status, "554 Server does not support Deliver By"); rcode = EX_UNAVAILABLE; goto give_up; } if (e->e_deliver_by > 0 && e->e_deliver_by - (curtime() - e->e_ctime) < mci->mci_min_by) { e->e_status = "5.4.7"; usrerrenh(e->e_status, "554 Message can't be delivered in time; %ld < %ld", e->e_deliver_by - (curtime() - e->e_ctime), mci->mci_min_by); rcode = EX_UNAVAILABLE; goto give_up; } } # if STARTTLS /* first TLS then AUTH to provide a security layer */ if (mci->mci_state != MCIS_CLOSED && !DONE_STARTTLS(mci->mci_flags)) { int olderrors; bool usetls; bool saveQuickAbort = QuickAbort; bool saveSuprErrs = SuprErrs; char *host = NULL; rcode = EX_OK; usetls = bitset(MCIF_TLS, mci->mci_flags); if (usetls) usetls = !iscltflgset(e, D_NOTLS); host = macvalue(macid("{server_name}"), e); if (usetls) { olderrors = Errors; QuickAbort = false; SuprErrs = true; if (rscheck("try_tls", host, NULL, e, RSF_RMCOMM, 7, host, NOQID, NULL) != EX_OK || Errors > olderrors) { usetls = false; } SuprErrs = saveSuprErrs; QuickAbort = saveQuickAbort; } if (usetls) { if ((rcode = starttls(m, mci, e)) == EX_OK) { /* start again without STARTTLS */ mci->mci_flags |= MCIF_TLSACT; } else { char *s; /* ** TLS negotiation failed, what to do? ** fall back to unencrypted connection ** or abort? How to decide? ** set a macro and call a ruleset. */ mci->mci_flags &= ~MCIF_TLS; switch (rcode) { case EX_TEMPFAIL: s = "TEMP"; break; case EX_USAGE: s = "USAGE"; break; case EX_PROTOCOL: s = "PROTOCOL"; break; case EX_SOFTWARE: s = "SOFTWARE"; break; case EX_UNAVAILABLE: s = "NONE"; break; /* everything else is a failure */ default: s = "FAILURE"; rcode = EX_TEMPFAIL; } macdefine(&e->e_macro, A_PERM, macid("{verify}"), s); } } else macdefine(&e->e_macro, A_PERM, macid("{verify}"), "NONE"); olderrors = Errors; QuickAbort = false; SuprErrs = true; /* ** rcode == EX_SOFTWARE is special: ** the TLS negotiation failed ** we have to drop the connection no matter what ** However, we call tls_server to give it the chance ** to log the problem and return an appropriate ** error code. */ if (rscheck("tls_server", macvalue(macid("{verify}"), e), NULL, e, RSF_RMCOMM|RSF_COUNT, 5, host, NOQID, NULL) != EX_OK || Errors > olderrors || rcode == EX_SOFTWARE) { char enhsc[ENHSCLEN]; extern char MsgBuf[]; if (ISSMTPCODE(MsgBuf) && extenhsc(MsgBuf + 4, ' ', enhsc) > 0) { p = sm_rpool_strdup_x(e->e_rpool, MsgBuf); } else { p = "403 4.7.0 server not authenticated."; (void) sm_strlcpy(enhsc, "4.7.0", sizeof(enhsc)); } SuprErrs = saveSuprErrs; QuickAbort = saveQuickAbort; if (rcode == EX_SOFTWARE) { /* drop the connection */ mci->mci_state = MCIS_QUITING; if (mci->mci_in != NULL) { (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT); mci->mci_in = NULL; } mci->mci_flags &= ~MCIF_TLSACT; (void) endmailer(mci, e, pv); } else { /* abort transfer */ smtpquit(m, mci, e); } /* avoid bogus error msg */ mci->mci_errno = 0; /* temp or permanent failure? */ rcode = (*p == '4') ? EX_TEMPFAIL : EX_UNAVAILABLE; mci_setstat(mci, rcode, enhsc, p); /* ** hack to get the error message into ** the envelope (done in giveresponse()) */ (void) sm_strlcpy(SmtpError, p, sizeof(SmtpError)); } else if (mci->mci_state == MCIS_CLOSED) { /* connection close caused by 421 */ mci->mci_errno = 0; rcode = EX_TEMPFAIL; mci_setstat(mci, rcode, NULL, "421"); } else rcode = 0; QuickAbort = saveQuickAbort; SuprErrs = saveSuprErrs; if (DONE_STARTTLS(mci->mci_flags) && mci->mci_state != MCIS_CLOSED) { SET_HELO(mci->mci_flags); mci_clr_extensions(mci); goto reconnect; } } # endif /* STARTTLS */ # if SASL /* if other server supports authentication let's authenticate */ if (mci->mci_state != MCIS_CLOSED && mci->mci_saslcap != NULL && !DONE_AUTH(mci->mci_flags) && !iscltflgset(e, D_NOAUTH)) { /* Should we require some minimum authentication? */ if ((ret = smtpauth(m, mci, e)) == EX_OK) { int result; sasl_ssf_t *ssf = NULL; /* Get security strength (features) */ result = sasl_getprop(mci->mci_conn, SASL_SSF, # if SASL >= 20000 (const void **) &ssf); # else /* SASL >= 20000 */ (void **) &ssf); # endif /* SASL >= 20000 */ /* XXX authid? */ if (LogLevel > 9) sm_syslog(LOG_INFO, NOQID, "AUTH=client, relay=%.100s, mech=%.16s, bits=%d", mci->mci_host, macvalue(macid("{auth_type}"), e), result == SASL_OK ? *ssf : 0); /* ** Only switch to encrypted connection ** if a security layer has been negotiated */ if (result == SASL_OK && *ssf > 0) { int tmo; /* ** Convert I/O layer to use SASL. ** If the call fails, the connection ** is aborted. */ tmo = DATA_PROGRESS_TIMEOUT * 1000; if (sfdcsasl(&mci->mci_in, &mci->mci_out, mci->mci_conn, tmo) == 0) { mci_clr_extensions(mci); mci->mci_flags |= MCIF_AUTHACT| MCIF_ONLY_EHLO; goto reconnect; } syserr("AUTH TLS switch failed in client"); } /* else? XXX */ mci->mci_flags |= MCIF_AUTHACT; } else if (ret == EX_TEMPFAIL) { if (LogLevel > 8) sm_syslog(LOG_ERR, NOQID, "AUTH=client, relay=%.100s, temporary failure, connection abort", mci->mci_host); smtpquit(m, mci, e); /* avoid bogus error msg */ mci->mci_errno = 0; rcode = EX_TEMPFAIL; mci_setstat(mci, rcode, "4.3.0", p); /* ** hack to get the error message into ** the envelope (done in giveresponse()) */ (void) sm_strlcpy(SmtpError, "Temporary AUTH failure", sizeof(SmtpError)); } } # endif /* SASL */ } do_transfer: /* clear out per-message flags from connection structure */ mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7); if (bitset(EF_HAS8BIT, e->e_flags) && !bitset(EF_DONT_MIME, e->e_flags) && bitnset(M_7BITS, m->m_flags)) mci->mci_flags |= MCIF_CVT8TO7; #if MIME7TO8 if (bitnset(M_MAKE8BIT, m->m_flags) && !bitset(MCIF_7BIT, mci->mci_flags) && (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL && (sm_strcasecmp(p, "quoted-printable") == 0 || sm_strcasecmp(p, "base64") == 0) && (p = hvalue("Content-Type", e->e_header)) != NULL) { /* may want to convert 7 -> 8 */ /* XXX should really parse it here -- and use a class XXX */ if (sm_strncasecmp(p, "text/plain", 10) == 0 && (p[10] == '\0' || p[10] == ' ' || p[10] == ';')) mci->mci_flags |= MCIF_CVT7TO8; } #endif /* MIME7TO8 */ if (tTd(11, 1)) { sm_dprintf("openmailer: "); mci_dump(sm_debug_file(), mci, false); } #if _FFR_CLIENT_SIZE /* ** See if we know the maximum size and ** abort if the message is too big. ** ** NOTE: _FFR_CLIENT_SIZE is untested. */ if (bitset(MCIF_SIZE, mci->mci_flags) && mci->mci_maxsize > 0 && e->e_msgsize > mci->mci_maxsize) { e->e_flags |= EF_NO_BODY_RETN; if (bitnset(M_LOCALMAILER, m->m_flags)) e->e_status = "5.2.3"; else e->e_status = "5.3.4"; usrerrenh(e->e_status, "552 Message is too large; %ld bytes max", mci->mci_maxsize); rcode = EX_DATAERR; /* Need an e_message for error */ (void) sm_snprintf(SmtpError, sizeof(SmtpError), "Message is too large; %ld bytes max", mci->mci_maxsize); goto give_up; } #endif /* _FFR_CLIENT_SIZE */ if (mci->mci_state != MCIS_OPEN) { /* couldn't open the mailer */ rcode = mci->mci_exitstat; errno = mci->mci_errno; SM_SET_H_ERRNO(mci->mci_herrno); if (rcode == EX_OK) { /* shouldn't happen */ syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s", (unsigned long) mci, rcode, errno, mci->mci_state, firstsig); mci_dump_all(smioout, true); rcode = EX_SOFTWARE; } else if (nummxhosts > hostnum) { /* try next MX site */ goto tryhost; } } else if (!clever) { bool ok; /* ** Format and send message. */ rcode = EX_OK; errno = 0; ok = putfromline(mci, e); if (ok) ok = (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER); if (ok) ok = (*e->e_putbody)(mci, e, NULL); if (ok && bitset(MCIF_INLONGLINE, mci->mci_flags)) ok = putline("", mci); /* ** Ignore an I/O error that was caused by EPIPE. ** Some broken mailers don't read the entire body ** but just exit() thus causing an I/O error. */ if (!ok && (sm_io_error(mci->mci_out) && errno == EPIPE)) ok = true; /* (always) get the exit status */ rcode = endmailer(mci, e, pv); if (!ok) rcode = EX_TEMPFAIL; if (rcode == EX_TEMPFAIL && SmtpError[0] == '\0') { /* ** Need an e_message for mailq display. ** We set SmtpError as */ (void) sm_snprintf(SmtpError, sizeof(SmtpError), "%s mailer (%s) exited with EX_TEMPFAIL", m->m_name, m->m_mailer); } } else { /* ** Send the MAIL FROM: protocol */ /* XXX this isn't pipelined... */ rcode = smtpmailfrom(m, mci, e); if (rcode == EX_OK) { register int i; # if PIPELINING ADDRESS *volatile pchain; # endif /* PIPELINING */ /* send the recipient list */ tobuf[0] = '\0'; mci->mci_retryrcpt = false; mci->mci_tolist = tobuf; # if PIPELINING pchain = NULL; mci->mci_nextaddr = NULL; # endif /* PIPELINING */ for (to = tochain; to != NULL; to = to->q_tchain) { if (!QS_IS_UNMARKED(to->q_state)) continue; /* mark recipient state as "ok so far" */ to->q_state = QS_OK; e->e_to = to->q_paddr; # if STARTTLS i = rscheck("tls_rcpt", to->q_user, NULL, e, RSF_RMCOMM|RSF_COUNT, 3, mci->mci_host, e->e_id, NULL); if (i != EX_OK) { markfailure(e, to, mci, i, false); giveresponse(i, to->q_status, m, mci, ctladdr, xstart, e, to); if (i == EX_TEMPFAIL) { mci->mci_retryrcpt = true; to->q_state = QS_RETRY; } continue; } # endif /* STARTTLS */ i = smtprcpt(to, m, mci, e, ctladdr, xstart); # if PIPELINING if (i == EX_OK && bitset(MCIF_PIPELINED, mci->mci_flags)) { /* ** Add new element to list of ** recipients for pipelining. */ to->q_pchain = NULL; if (mci->mci_nextaddr == NULL) mci->mci_nextaddr = to; if (pchain == NULL) pchain = to; else { pchain->q_pchain = to; pchain = pchain->q_pchain; } } # endif /* PIPELINING */ if (i != EX_OK) { markfailure(e, to, mci, i, false); giveresponse(i, to->q_status, m, mci, ctladdr, xstart, e, to); if (i == EX_TEMPFAIL) to->q_state = QS_RETRY; } } /* No recipients in list and no missing responses? */ if (tobuf[0] == '\0' # if PIPELINING && bitset(MCIF_PIPELINED, mci->mci_flags) && mci->mci_nextaddr == NULL # endif /* PIPELINING */ ) { rcode = EX_OK; e->e_to = NULL; if (bitset(MCIF_CACHED, mci->mci_flags)) smtprset(m, mci, e); } else { e->e_to = tobuf + 1; rcode = smtpdata(m, mci, e, ctladdr, xstart); } } if (rcode == EX_TEMPFAIL && nummxhosts > hostnum) { /* try next MX site */ goto tryhost; } } #if NAMED_BIND if (ConfigLevel < 2) _res.options |= RES_DEFNAMES | RES_DNSRCH; /* XXX */ #endif /* NAMED_BIND */ if (tTd(62, 1)) checkfds("after delivery"); /* ** Do final status disposal. ** We check for something in tobuf for the SMTP case. ** If we got a temporary failure, arrange to queue the ** addressees. */ give_up: if (bitnset(M_LMTP, m->m_flags)) { lmtp_rcode = rcode; tobuf[0] = '\0'; anyok = false; strsize = 0; } else anyok = rcode == EX_OK; for (to = tochain; to != NULL; to = to->q_tchain) { /* see if address already marked */ if (!QS_IS_OK(to->q_state)) continue; /* if running LMTP, get the status for each address */ if (bitnset(M_LMTP, m->m_flags)) { if (lmtp_rcode == EX_OK) rcode = smtpgetstat(m, mci, e); if (rcode == EX_OK) { strsize += sm_strlcat2(tobuf + strsize, ",", to->q_paddr, tobufsize - strsize); SM_ASSERT(strsize < tobufsize); anyok = true; } else { e->e_to = to->q_paddr; markfailure(e, to, mci, rcode, true); giveresponse(rcode, to->q_status, m, mci, ctladdr, xstart, e, to); e->e_to = tobuf + 1; continue; } } else { /* mark bad addresses */ if (rcode != EX_OK) { if (goodmxfound && rcode == EX_NOHOST) rcode = EX_TEMPFAIL; markfailure(e, to, mci, rcode, true); continue; } } /* successful delivery */ to->q_state = QS_SENT; to->q_statdate = curtime(); e->e_nsent++; /* ** Checkpoint the send list every few addresses */ if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval) { queueup(e, false, false); e->e_nsent = 0; } if (bitnset(M_LOCALMAILER, m->m_flags) && bitset(QPINGONSUCCESS, to->q_flags)) { to->q_flags |= QDELIVERED; to->q_status = "2.1.5"; (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s... Successfully delivered\n", to->q_paddr); } else if (bitset(QPINGONSUCCESS, to->q_flags) && bitset(QPRIMARY, to->q_flags) && !bitset(MCIF_DSN, mci->mci_flags)) { to->q_flags |= QRELAYED; (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s... relayed; expect no further notifications\n", to->q_paddr); } else if (IS_DLVR_NOTIFY(e) && !bitset(MCIF_DLVR_BY, mci->mci_flags) && bitset(QPRIMARY, to->q_flags) && (!bitset(QHASNOTIFY, to->q_flags) || bitset(QPINGONSUCCESS, to->q_flags) || bitset(QPINGONFAILURE, to->q_flags) || bitset(QPINGONDELAY, to->q_flags))) { /* RFC 2852, 4.1.4.2: no NOTIFY, or not NEVER */ to->q_flags |= QBYNRELAY; (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s... Deliver-by notify: relayed\n", to->q_paddr); } else if (IS_DLVR_TRACE(e) && (!bitset(QHASNOTIFY, to->q_flags) || bitset(QPINGONSUCCESS, to->q_flags) || bitset(QPINGONFAILURE, to->q_flags) || bitset(QPINGONDELAY, to->q_flags)) && bitset(QPRIMARY, to->q_flags)) { /* RFC 2852, 4.1.4: no NOTIFY, or not NEVER */ to->q_flags |= QBYTRACE; (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s... Deliver-By trace: relayed\n", to->q_paddr); } } if (bitnset(M_LMTP, m->m_flags)) { /* ** Global information applies to the last recipient only; ** clear it out to avoid bogus errors. */ rcode = EX_OK; e->e_statmsg = NULL; /* reset the mci state for the next transaction */ if (mci != NULL && (mci->mci_state == MCIS_MAIL || mci->mci_state == MCIS_RCPT || mci->mci_state == MCIS_DATA)) { mci->mci_state = MCIS_OPEN; SmtpPhase = mci->mci_phase = "idle"; sm_setproctitle(true, e, "%s: %s", CurHostName, mci->mci_phase); } } if (tobuf[0] != '\0') { giveresponse(rcode, NULL, m, mci, ctladdr, xstart, e, tochain); #if 0 /* ** This code is disabled for now because I am not ** sure that copying status from the first recipient ** to all non-status'ed recipients is a good idea. */ if (tochain->q_message != NULL && !bitnset(M_LMTP, m->m_flags) && rcode != EX_OK) { for (to = tochain->q_tchain; to != NULL; to = to->q_tchain) { /* see if address already marked */ if (QS_IS_QUEUEUP(to->q_state) && to->q_message == NULL) to->q_message = sm_rpool_strdup_x(e->e_rpool, tochain->q_message); } } #endif /* 0 */ } if (anyok) markstats(e, tochain, STATS_NORMAL); mci_store_persistent(mci); /* Some recipients were tempfailed, try them on the next host */ if (mci != NULL && mci->mci_retryrcpt && nummxhosts > hostnum) { /* try next MX site */ goto tryhost; } /* now close the connection */ if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED && !bitset(MCIF_CACHED, mci->mci_flags)) smtpquit(m, mci, e); cleanup: ; } SM_FINALLY { /* ** Restore state and return. */ #if XDEBUG char wbuf[MAXLINE]; /* make absolutely certain 0, 1, and 2 are in use */ (void) sm_snprintf(wbuf, sizeof(wbuf), "%s... end of deliver(%s)", e->e_to == NULL ? "NO-TO-LIST" : shortenstring(e->e_to, MAXSHORTSTR), m->m_name); checkfd012(wbuf); #endif /* XDEBUG */ errno = 0; /* ** It was originally necessary to set macro 'g' to NULL ** because it previously pointed to an auto buffer. ** We don't do this any more, so this may be unnecessary. */ macdefine(&e->e_macro, A_PERM, 'g', (char *) NULL); e->e_to = NULL; } SM_END_TRY return rcode; } /* ** MARKFAILURE -- mark a failure on a specific address. ** ** Parameters: ** e -- the envelope we are sending. ** q -- the address to mark. ** mci -- mailer connection information. ** rcode -- the code signifying the particular failure. ** ovr -- override an existing code? ** ** Returns: ** none. ** ** Side Effects: ** marks the address (and possibly the envelope) with the ** failure so that an error will be returned or ** the message will be queued, as appropriate. */ void markfailure(e, q, mci, rcode, ovr) register ENVELOPE *e; register ADDRESS *q; register MCI *mci; int rcode; bool ovr; { int save_errno = errno; char *status = NULL; char *rstatus = NULL; switch (rcode) { case EX_OK: break; case EX_TEMPFAIL: case EX_IOERR: case EX_OSERR: q->q_state = QS_QUEUEUP; break; default: q->q_state = QS_BADADDR; break; } /* find most specific error code possible */ if (mci != NULL && mci->mci_status != NULL) { status = sm_rpool_strdup_x(e->e_rpool, mci->mci_status); if (mci->mci_rstatus != NULL) rstatus = sm_rpool_strdup_x(e->e_rpool, mci->mci_rstatus); else rstatus = NULL; } else if (e->e_status != NULL) { status = e->e_status; rstatus = NULL; } else { switch (rcode) { case EX_USAGE: status = "5.5.4"; break; case EX_DATAERR: status = "5.5.2"; break; case EX_NOUSER: status = "5.1.1"; break; case EX_NOHOST: status = "5.1.2"; break; case EX_NOINPUT: case EX_CANTCREAT: case EX_NOPERM: status = "5.3.0"; break; case EX_UNAVAILABLE: case EX_SOFTWARE: case EX_OSFILE: case EX_PROTOCOL: case EX_CONFIG: status = "5.5.0"; break; case EX_OSERR: case EX_IOERR: status = "4.5.0"; break; case EX_TEMPFAIL: status = "4.2.0"; break; } } /* new status? */ if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL || *q->q_status == '\0' || *q->q_status < *status)) { q->q_status = status; q->q_rstatus = rstatus; } if (rcode != EX_OK && q->q_rstatus == NULL && q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL && sm_strcasecmp(q->q_mailer->m_diagtype, "X-UNIX") == 0) { char buf[16]; (void) sm_snprintf(buf, sizeof(buf), "%d", rcode); q->q_rstatus = sm_rpool_strdup_x(e->e_rpool, buf); } q->q_statdate = curtime(); if (CurHostName != NULL && CurHostName[0] != '\0' && mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags)) q->q_statmta = sm_rpool_strdup_x(e->e_rpool, CurHostName); /* restore errno */ errno = save_errno; } /* ** ENDMAILER -- Wait for mailer to terminate. ** ** We should never get fatal errors (e.g., segmentation ** violation), so we report those specially. For other ** errors, we choose a status message (into statmsg), ** and if it represents an error, we print it. ** ** Parameters: ** mci -- the mailer connection info. ** e -- the current envelope. ** pv -- the parameter vector that invoked the mailer ** (for error messages). ** ** Returns: ** exit code of mailer. ** ** Side Effects: ** none. */ static jmp_buf EndWaitTimeout; static void endwaittimeout(ignore) int ignore; { /* ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ errno = ETIMEDOUT; longjmp(EndWaitTimeout, 1); } int endmailer(mci, e, pv) register MCI *mci; register ENVELOPE *e; char **pv; { int st; int save_errno = errno; char buf[MAXLINE]; SM_EVENT *ev = NULL; mci_unlock_host(mci); /* close output to mailer */ if (mci->mci_out != NULL) { (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT); mci->mci_out = NULL; } /* copy any remaining input to transcript */ if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR && e->e_xfp != NULL) { while (sfgets(buf, sizeof(buf), mci->mci_in, TimeOuts.to_quit, "Draining Input") != NULL) (void) sm_io_fputs(e->e_xfp, SM_TIME_DEFAULT, buf); } #if SASL /* close SASL connection */ if (bitset(MCIF_AUTHACT, mci->mci_flags)) { sasl_dispose(&mci->mci_conn); mci->mci_flags &= ~MCIF_AUTHACT; } #endif /* SASL */ #if STARTTLS /* shutdown TLS */ (void) endtlsclt(mci); #endif /* STARTTLS */ /* now close the input */ if (mci->mci_in != NULL) { (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT); mci->mci_in = NULL; } mci->mci_state = MCIS_CLOSED; errno = save_errno; /* in the IPC case there is nothing to wait for */ if (mci->mci_pid == 0) return EX_OK; /* put a timeout around the wait */ if (mci->mci_mailer->m_wait > 0) { if (setjmp(EndWaitTimeout) == 0) ev = sm_setevent(mci->mci_mailer->m_wait, endwaittimeout, 0); else { syserr("endmailer %s: wait timeout (%ld)", mci->mci_mailer->m_name, (long) mci->mci_mailer->m_wait); return EX_TEMPFAIL; } } /* wait for the mailer process, collect status */ st = waitfor(mci->mci_pid); save_errno = errno; if (ev != NULL) sm_clrevent(ev); errno = save_errno; if (st == -1) { syserr("endmailer %s: wait", mci->mci_mailer->m_name); return EX_SOFTWARE; } if (WIFEXITED(st)) { /* normal death -- return status */ return (WEXITSTATUS(st)); } /* it died a horrid death */ syserr("451 4.3.0 mailer %s died with signal %d%s", mci->mci_mailer->m_name, WTERMSIG(st), WCOREDUMP(st) ? " (core dumped)" : (WIFSTOPPED(st) ? " (stopped)" : "")); /* log the arguments */ if (pv != NULL && e->e_xfp != NULL) { register char **av; (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Arguments:"); for (av = pv; *av != NULL; av++) (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, " %s", *av); (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "\n"); } ExitStat = EX_TEMPFAIL; return EX_TEMPFAIL; } /* ** GIVERESPONSE -- Interpret an error response from a mailer ** ** Parameters: ** status -- the status code from the mailer (high byte ** only; core dumps must have been taken care of ** already). ** dsn -- the DSN associated with the address, if any. ** m -- the mailer info for this mailer. ** mci -- the mailer connection info -- can be NULL if the ** response is given before the connection is made. ** ctladdr -- the controlling address for the recipient ** address(es). ** xstart -- the transaction start time, for computing ** transaction delays. ** e -- the current envelope. ** to -- the current recipient (NULL if none). ** ** Returns: ** none. ** ** Side Effects: ** Errors may be incremented. ** ExitStat may be set. */ void giveresponse(status, dsn, m, mci, ctladdr, xstart, e, to) int status; char *dsn; register MAILER *m; register MCI *mci; ADDRESS *ctladdr; time_t xstart; ENVELOPE *e; ADDRESS *to; { register const char *statmsg; int errnum = errno; int off = 4; bool usestat = false; char dsnbuf[ENHSCLEN]; char buf[MAXLINE]; char *exmsg; if (e == NULL) { syserr("giveresponse: null envelope"); /* NOTREACHED */ SM_ASSERT(0); } /* ** Compute status message from code. */ exmsg = sm_sysexmsg(status); if (status == 0) { statmsg = "250 2.0.0 Sent"; if (e->e_statmsg != NULL) { (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", statmsg, shortenstring(e->e_statmsg, 403)); statmsg = buf; } } else if (exmsg == NULL) { (void) sm_snprintf(buf, sizeof(buf), "554 5.3.0 unknown mailer error %d", status); status = EX_UNAVAILABLE; statmsg = buf; usestat = true; } else if (status == EX_TEMPFAIL) { char *bp = buf; (void) sm_strlcpy(bp, exmsg + 1, SPACELEFT(buf, bp)); bp += strlen(bp); #if NAMED_BIND if (h_errno == TRY_AGAIN) statmsg = sm_errstring(h_errno + E_DNSBASE); else #endif /* NAMED_BIND */ { if (errnum != 0) statmsg = sm_errstring(errnum); else statmsg = SmtpError; } if (statmsg != NULL && statmsg[0] != '\0') { switch (errnum) { #ifdef ENETDOWN case ENETDOWN: /* Network is down */ #endif /* ENETDOWN */ #ifdef ENETUNREACH case ENETUNREACH: /* Network is unreachable */ #endif /* ENETUNREACH */ #ifdef ENETRESET case ENETRESET: /* Network dropped connection on reset */ #endif /* ENETRESET */ #ifdef ECONNABORTED case ECONNABORTED: /* Software caused connection abort */ #endif /* ECONNABORTED */ #ifdef EHOSTDOWN case EHOSTDOWN: /* Host is down */ #endif /* EHOSTDOWN */ #ifdef EHOSTUNREACH case EHOSTUNREACH: /* No route to host */ #endif /* EHOSTUNREACH */ if (mci != NULL && mci->mci_host != NULL) { (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ", mci->mci_host); bp += strlen(bp); } break; } (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ", statmsg); usestat = true; } statmsg = buf; } #if NAMED_BIND else if (status == EX_NOHOST && h_errno != 0) { statmsg = sm_errstring(h_errno + E_DNSBASE); (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", exmsg + 1, statmsg); statmsg = buf; usestat = true; } #endif /* NAMED_BIND */ else { statmsg = exmsg; if (*statmsg++ == ':' && errnum != 0) { (void) sm_snprintf(buf, sizeof(buf), "%s: %s", statmsg, sm_errstring(errnum)); statmsg = buf; usestat = true; } else if (bitnset(M_LMTP, m->m_flags) && e->e_statmsg != NULL) { (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", statmsg, shortenstring(e->e_statmsg, 403)); statmsg = buf; usestat = true; } } /* ** Print the message as appropriate */ if (status == EX_OK || status == EX_TEMPFAIL) { extern char MsgBuf[]; if ((off = isenhsc(statmsg + 4, ' ')) > 0) { if (dsn == NULL) { (void) sm_snprintf(dsnbuf, sizeof(dsnbuf), "%.*s", off, statmsg + 4); dsn = dsnbuf; } off += 5; } else { off = 4; } message("%s", statmsg + off); if (status == EX_TEMPFAIL && e->e_xfp != NULL) (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s\n", &MsgBuf[4]); } else { char mbuf[ENHSCLEN + 4]; Errors++; if ((off = isenhsc(statmsg + 4, ' ')) > 0 && off < sizeof(mbuf) - 4) { if (dsn == NULL) { (void) sm_snprintf(dsnbuf, sizeof(dsnbuf), "%.*s", off, statmsg + 4); dsn = dsnbuf; } off += 5; /* copy only part of statmsg to mbuf */ (void) sm_strlcpy(mbuf, statmsg, off); (void) sm_strlcat(mbuf, " %s", sizeof(mbuf)); } else { dsnbuf[0] = '\0'; (void) sm_snprintf(mbuf, sizeof(mbuf), "%.3s %%s", statmsg); off = 4; } usrerr(mbuf, &statmsg[off]); } /* ** Final cleanup. ** Log a record of the transaction. Compute the new ** ExitStat -- if we already had an error, stick with ** that. */ if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) && LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6)) logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e); if (tTd(11, 2)) sm_dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s, errnum=%d\n", status, dsn == NULL ? "" : dsn, e->e_message == NULL ? "" : e->e_message, errnum); if (status != EX_TEMPFAIL) setstat(status); if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL)) e->e_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off); if (status != EX_OK && to != NULL && to->q_message == NULL) { if (!usestat && e->e_message != NULL) to->q_message = sm_rpool_strdup_x(e->e_rpool, e->e_message); else to->q_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off); } errno = 0; SM_SET_H_ERRNO(0); } /* ** LOGDELIVERY -- log the delivery in the system log ** ** Care is taken to avoid logging lines that are too long, because ** some versions of syslog have an unfortunate proclivity for core ** dumping. This is a hack, to be sure, that is at best empirical. ** ** Parameters: ** m -- the mailer info. Can be NULL for initial queue. ** mci -- the mailer connection info -- can be NULL if the ** log is occurring when no connection is active. ** dsn -- the DSN attached to the status. ** status -- the message to print for the status. ** ctladdr -- the controlling address for the to list. ** xstart -- the transaction start time, used for ** computing transaction delay. ** e -- the current envelope. ** ** Returns: ** none ** ** Side Effects: ** none */ void logdelivery(m, mci, dsn, status, ctladdr, xstart, e) MAILER *m; register MCI *mci; char *dsn; const char *status; ADDRESS *ctladdr; time_t xstart; register ENVELOPE *e; { register char *bp; register char *p; int l; time_t now = curtime(); char buf[1024]; #if (SYSLOG_BUFSIZE) >= 256 /* ctladdr: max 106 bytes */ bp = buf; if (ctladdr != NULL) { (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", ctladdr=", shortenstring(ctladdr->q_paddr, 83)); bp += strlen(bp); if (bitset(QGOODUID, ctladdr->q_flags)) { (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)", (int) ctladdr->q_uid, (int) ctladdr->q_gid); bp += strlen(bp); } } /* delay & xdelay: max 41 bytes */ (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", delay=", pintvl(now - e->e_ctime, true)); bp += strlen(bp); if (xstart != (time_t) 0) { (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=", pintvl(now - xstart, true)); bp += strlen(bp); } /* mailer: assume about 19 bytes (max 10 byte mailer name) */ if (m != NULL) { (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=", m->m_name); bp += strlen(bp); } /* pri: changes with each delivery attempt */ (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld", PRT_NONNEGL(e->e_msgpriority)); bp += strlen(bp); /* relay: max 66 bytes for IPv4 addresses */ if (mci != NULL && mci->mci_host != NULL) { extern SOCKADDR CurHostAddr; (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", relay=", shortenstring(mci->mci_host, 40)); bp += strlen(bp); if (CurHostAddr.sa.sa_family != 0) { (void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%s]", anynet_ntoa(&CurHostAddr)); } } else if (strcmp(status, "quarantined") == 0) { if (e->e_quarmsg != NULL) (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", quarantine=%s", shortenstring(e->e_quarmsg, 40)); } else if (strcmp(status, "queued") != 0) { p = macvalue('h', e); if (p != NULL && p[0] != '\0') { (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", relay=%s", shortenstring(p, 40)); } } bp += strlen(bp); /* dsn */ if (dsn != NULL && *dsn != '\0') { (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", dsn=", shortenstring(dsn, ENHSCLEN)); bp += strlen(bp); } #if _FFR_LOG_NTRIES /* ntries */ if (e->e_ntries >= 0) { (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", ntries=%d", e->e_ntries + 1); bp += strlen(bp); } #endif /* _FFR_LOG_NTRIES */ # define STATLEN (((SYSLOG_BUFSIZE) - 100) / 4) # if (STATLEN) < 63 # undef STATLEN # define STATLEN 63 # endif /* (STATLEN) < 63 */ # if (STATLEN) > 203 # undef STATLEN # define STATLEN 203 # endif /* (STATLEN) > 203 */ /* stat: max 210 bytes */ if ((bp - buf) > (sizeof(buf) - ((STATLEN) + 20))) { /* desperation move -- truncate data */ bp = buf + sizeof(buf) - ((STATLEN) + 17); (void) sm_strlcpy(bp, "...", SPACELEFT(buf, bp)); bp += 3; } (void) sm_strlcpy(bp, ", stat=", SPACELEFT(buf, bp)); bp += strlen(bp); (void) sm_strlcpy(bp, shortenstring(status, STATLEN), SPACELEFT(buf, bp)); /* id, to: max 13 + TOBUFSIZE bytes */ l = SYSLOG_BUFSIZE - 100 - strlen(buf); if (l < 0) l = 0; p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to; while (strlen(p) >= l) { register char *q; for (q = p + l; q > p; q--) { if (*q == ',') break; } if (p == q) break; sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]%s", (int) (++q - p), p, buf); p = q; } sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, p, buf); #else /* (SYSLOG_BUFSIZE) >= 256 */ l = SYSLOG_BUFSIZE - 85; if (l < 0) l = 0; p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to; while (strlen(p) >= l) { register char *q; for (q = p + l; q > p; q--) { if (*q == ',') break; } if (p == q) break; sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]", (int) (++q - p), p); p = q; } sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p); if (ctladdr != NULL) { bp = buf; (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "ctladdr=", shortenstring(ctladdr->q_paddr, 83)); bp += strlen(bp); if (bitset(QGOODUID, ctladdr->q_flags)) { (void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)", ctladdr->q_uid, ctladdr->q_gid); bp += strlen(bp); } sm_syslog(LOG_INFO, e->e_id, "%s", buf); } bp = buf; (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "delay=", pintvl(now - e->e_ctime, true)); bp += strlen(bp); if (xstart != (time_t) 0) { (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=", pintvl(now - xstart, true)); bp += strlen(bp); } if (m != NULL) { (void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=", m->m_name); bp += strlen(bp); } sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf); buf[0] = '\0'; bp = buf; if (mci != NULL && mci->mci_host != NULL) { extern SOCKADDR CurHostAddr; (void) sm_snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s", mci->mci_host); bp += strlen(bp); if (CurHostAddr.sa.sa_family != 0) (void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%.100s]", anynet_ntoa(&CurHostAddr)); } else if (strcmp(status, "quarantined") == 0) { if (e->e_quarmsg != NULL) (void) sm_snprintf(bp, SPACELEFT(buf, bp), ", quarantine=%.100s", e->e_quarmsg); } else if (strcmp(status, "queued") != 0) { p = macvalue('h', e); if (p != NULL && p[0] != '\0') (void) sm_snprintf(buf, sizeof(buf), "relay=%.100s", p); } if (buf[0] != '\0') sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf); sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63)); #endif /* (SYSLOG_BUFSIZE) >= 256 */ } /* ** PUTFROMLINE -- output a UNIX-style from line (or whatever) ** ** This can be made an arbitrary message separator by changing $l ** ** One of the ugliest hacks seen by human eyes is contained herein: ** UUCP wants those stupid "remote from " lines. Why oh why ** does a well-meaning programmer such as myself have to deal with ** this kind of antique garbage???? ** ** Parameters: ** mci -- the connection information. ** e -- the envelope. ** ** Returns: ** true iff line was written successfully ** ** Side Effects: ** outputs some text to fp. */ bool putfromline(mci, e) register MCI *mci; ENVELOPE *e; { char *template = UnixFromLine; char buf[MAXLINE]; char xbuf[MAXLINE]; if (bitnset(M_NHDR, mci->mci_mailer->m_flags)) return true; mci->mci_flags |= MCIF_INHEADER; if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags)) { char *bang; expand("\201g", buf, sizeof(buf), e); bang = strchr(buf, '!'); if (bang == NULL) { char *at; char hname[MAXNAME]; /* ** If we can construct a UUCP path, do so */ at = strrchr(buf, '@'); if (at == NULL) { expand("\201k", hname, sizeof(hname), e); at = hname; } else *at++ = '\0'; (void) sm_snprintf(xbuf, sizeof(xbuf), "From %.800s \201d remote from %.100s\n", buf, at); } else { *bang++ = '\0'; (void) sm_snprintf(xbuf, sizeof(xbuf), "From %.800s \201d remote from %.100s\n", bang, buf); template = xbuf; } } expand(template, buf, sizeof(buf), e); return putxline(buf, strlen(buf), mci, PXLF_HEADER); } /* ** PUTBODY -- put the body of a message. ** ** Parameters: ** mci -- the connection information. ** e -- the envelope to put out. ** separator -- if non-NULL, a message separator that must ** not be permitted in the resulting message. ** ** Returns: ** true iff message was written successfully ** ** Side Effects: ** The message is written onto fp. */ /* values for output state variable */ #define OSTATE_HEAD 0 /* at beginning of line */ #define OSTATE_CR 1 /* read a carriage return */ #define OSTATE_INLINE 2 /* putting rest of line */ bool putbody(mci, e, separator) register MCI *mci; register ENVELOPE *e; char *separator; { bool dead = false; bool ioerr = false; int save_errno; char buf[MAXLINE]; #if MIME8TO7 char *boundaries[MAXMIMENESTING + 1]; #endif /* MIME8TO7 */ /* ** Output the body of the message */ if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags)) { char *df = queuename(e, DATAFL_LETTER); e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df, SM_IO_RDONLY_B, NULL); if (e->e_dfp == NULL) { char *msg = "!putbody: Cannot open %s for %s from %s"; if (errno == ENOENT) msg++; syserr(msg, df, e->e_to, e->e_from.q_paddr); } } if (e->e_dfp == NULL) { if (bitset(MCIF_INHEADER, mci->mci_flags)) { if (!putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; } if (!putline("<<< No Message Collected >>>", mci)) goto writeerr; goto endofmessage; } if (e->e_dfino == (ino_t) 0) { struct stat stbuf; if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &stbuf) < 0) e->e_dfino = -1; else { e->e_dfdev = stbuf.st_dev; e->e_dfino = stbuf.st_ino; } } /* paranoia: the data file should always be in a rewound state */ (void) bfrewind(e->e_dfp); /* simulate an I/O timeout when used as source */ if (tTd(84, 101)) sleep(319); #if MIME8TO7 if (bitset(MCIF_CVT8TO7, mci->mci_flags)) { /* ** Do 8 to 7 bit MIME conversion. */ /* make sure it looks like a MIME message */ if (hvalue("MIME-Version", e->e_header) == NULL && !putline("MIME-Version: 1.0", mci)) goto writeerr; if (hvalue("Content-Type", e->e_header) == NULL) { (void) sm_snprintf(buf, sizeof(buf), "Content-Type: text/plain; charset=%s", defcharset(e)); if (!putline(buf, mci)) goto writeerr; } /* now do the hard work */ boundaries[0] = NULL; mci->mci_flags |= MCIF_INHEADER; if (mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER, 0) == SM_IO_EOF) goto writeerr; } # if MIME7TO8 else if (bitset(MCIF_CVT7TO8, mci->mci_flags)) { if (!mime7to8(mci, e->e_header, e)) goto writeerr; } # endif /* MIME7TO8 */ else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0) { bool oldsuprerrs = SuprErrs; /* Use mime8to7 to check multipart for MIME header overflows */ boundaries[0] = NULL; mci->mci_flags |= MCIF_INHEADER; /* ** If EF_DONT_MIME is set, we have a broken MIME message ** and don't want to generate a new bounce message whose ** body propagates the broken MIME. We can't just not call ** mime8to7() as is done above since we need the security ** checks. The best we can do is suppress the errors. */ if (bitset(EF_DONT_MIME, e->e_flags)) SuprErrs = true; if (mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER|M87F_NO8TO7, 0) == SM_IO_EOF) goto writeerr; /* restore SuprErrs */ SuprErrs = oldsuprerrs; } else #endif /* MIME8TO7 */ { int ostate; register char *bp; register char *pbp; register int c; register char *xp; int padc; char *buflim; int pos = 0; char peekbuf[12]; if (bitset(MCIF_INHEADER, mci->mci_flags)) { if (!putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; } /* determine end of buffer; allow for short mailer lines */ buflim = &buf[sizeof(buf) - 1]; if (mci->mci_mailer->m_linelimit > 0 && mci->mci_mailer->m_linelimit < sizeof(buf) - 1) buflim = &buf[mci->mci_mailer->m_linelimit - 1]; /* copy temp file to output with mapping */ ostate = OSTATE_HEAD; bp = buf; pbp = peekbuf; while (!sm_io_error(mci->mci_out) && !dead) { if (pbp > peekbuf) c = *--pbp; else if ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT)) == SM_IO_EOF) break; if (bitset(MCIF_7BIT, mci->mci_flags)) c &= 0x7f; switch (ostate) { case OSTATE_HEAD: if (c == '\0' && bitnset(M_NONULLS, mci->mci_mailer->m_flags)) break; if (c != '\r' && c != '\n' && bp < buflim) { *bp++ = c; break; } /* check beginning of line for special cases */ *bp = '\0'; pos = 0; padc = SM_IO_EOF; if (buf[0] == 'F' && bitnset(M_ESCFROM, mci->mci_mailer->m_flags) && strncmp(buf, "From ", 5) == 0) { padc = '>'; } if (buf[0] == '-' && buf[1] == '-' && separator != NULL) { /* possible separator */ int sl = strlen(separator); if (strncmp(&buf[2], separator, sl) == 0) padc = ' '; } if (buf[0] == '.' && bitnset(M_XDOT, mci->mci_mailer->m_flags)) { padc = '.'; } /* now copy out saved line */ if (TrafficLogFile != NULL) { (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d >>> ", (int) CurrentPid); if (padc != SM_IO_EOF) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, padc); for (xp = buf; xp < bp; xp++) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, (unsigned char) *xp); if (c == '\n') (void) sm_io_fputs(TrafficLogFile, SM_TIME_DEFAULT, mci->mci_mailer->m_eol); } if (padc != SM_IO_EOF) { if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, padc) == SM_IO_EOF) { dead = true; continue; } pos++; } for (xp = buf; xp < bp; xp++) { if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, (unsigned char) *xp) == SM_IO_EOF) { dead = true; break; } } if (dead) continue; if (c == '\n') { if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT, mci->mci_mailer->m_eol) == SM_IO_EOF) break; pos = 0; } else { pos += bp - buf; if (c != '\r') { SM_ASSERT(pbp < peekbuf + sizeof(peekbuf)); *pbp++ = c; } } bp = buf; /* determine next state */ if (c == '\n') ostate = OSTATE_HEAD; else if (c == '\r') ostate = OSTATE_CR; else ostate = OSTATE_INLINE; continue; case OSTATE_CR: if (c == '\n') { /* got CRLF */ if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT, mci->mci_mailer->m_eol) == SM_IO_EOF) continue; if (TrafficLogFile != NULL) { (void) sm_io_fputs(TrafficLogFile, SM_TIME_DEFAULT, mci->mci_mailer->m_eol); } pos = 0; ostate = OSTATE_HEAD; continue; } /* had a naked carriage return */ SM_ASSERT(pbp < peekbuf + sizeof(peekbuf)); *pbp++ = c; c = '\r'; ostate = OSTATE_INLINE; goto putch; case OSTATE_INLINE: if (c == '\r') { ostate = OSTATE_CR; continue; } if (c == '\0' && bitnset(M_NONULLS, mci->mci_mailer->m_flags)) break; putch: if (mci->mci_mailer->m_linelimit > 0 && pos >= mci->mci_mailer->m_linelimit - 1 && c != '\n') { int d; /* check next character for EOL */ if (pbp > peekbuf) d = *(pbp - 1); else if ((d = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT)) != SM_IO_EOF) { SM_ASSERT(pbp < peekbuf + sizeof(peekbuf)); *pbp++ = d; } if (d == '\n' || d == SM_IO_EOF) { if (TrafficLogFile != NULL) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, (unsigned char) c); if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, (unsigned char) c) == SM_IO_EOF) { dead = true; continue; } pos++; continue; } if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, '!') == SM_IO_EOF || sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT, mci->mci_mailer->m_eol) == SM_IO_EOF) { dead = true; continue; } if (TrafficLogFile != NULL) { (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "!%s", mci->mci_mailer->m_eol); } ostate = OSTATE_HEAD; SM_ASSERT(pbp < peekbuf + sizeof(peekbuf)); *pbp++ = c; continue; } if (c == '\n') { if (TrafficLogFile != NULL) (void) sm_io_fputs(TrafficLogFile, SM_TIME_DEFAULT, mci->mci_mailer->m_eol); if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT, mci->mci_mailer->m_eol) == SM_IO_EOF) continue; pos = 0; ostate = OSTATE_HEAD; } else { if (TrafficLogFile != NULL) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, (unsigned char) c); if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, (unsigned char) c) == SM_IO_EOF) { dead = true; continue; } pos++; ostate = OSTATE_INLINE; } break; } } /* make sure we are at the beginning of a line */ if (bp > buf) { if (TrafficLogFile != NULL) { for (xp = buf; xp < bp; xp++) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, (unsigned char) *xp); } for (xp = buf; xp < bp; xp++) { if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, (unsigned char) *xp) == SM_IO_EOF) { dead = true; break; } } pos += bp - buf; } if (!dead && pos > 0) { if (TrafficLogFile != NULL) (void) sm_io_fputs(TrafficLogFile, SM_TIME_DEFAULT, mci->mci_mailer->m_eol); if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT, mci->mci_mailer->m_eol) == SM_IO_EOF) goto writeerr; } } if (sm_io_error(e->e_dfp)) { syserr("putbody: %s/%cf%s: read error", qid_printqueue(e->e_dfqgrp, e->e_dfqdir), DATAFL_LETTER, e->e_id); ExitStat = EX_IOERR; ioerr = true; } endofmessage: /* ** Since mailfile() uses e_dfp in a child process, ** the file offset in the stdio library for the ** parent process will not agree with the in-kernel ** file offset since the file descriptor is shared ** between the processes. Therefore, it is vital ** that the file always be rewound. This forces the ** kernel offset (lseek) and stdio library (ftell) ** offset to match. */ save_errno = errno; if (e->e_dfp != NULL) (void) bfrewind(e->e_dfp); /* some mailers want extra blank line at end of message */ if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) && buf[0] != '\0' && buf[0] != '\n') { if (!putline("", mci)) goto writeerr; } if (!dead && (sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF || (sm_io_error(mci->mci_out) && errno != EPIPE))) { save_errno = errno; syserr("putbody: write error"); ExitStat = EX_IOERR; ioerr = true; } errno = save_errno; return !dead && !ioerr; writeerr: return false; } /* ** MAILFILE -- Send a message to a file. ** ** If the file has the set-user-ID/set-group-ID bits set, but NO ** execute bits, sendmail will try to become the owner of that file ** rather than the real user. Obviously, this only works if ** sendmail runs as root. ** ** This could be done as a subordinate mailer, except that it ** is used implicitly to save messages in ~/dead.letter. We ** view this as being sufficiently important as to include it ** here. For example, if the system is dying, we shouldn't have ** to create another process plus some pipes to save the message. ** ** Parameters: ** filename -- the name of the file to send to. ** mailer -- mailer definition for recipient -- if NULL, ** use FileMailer. ** ctladdr -- the controlling address header -- includes ** the userid/groupid to be when sending. ** sfflags -- flags for opening. ** e -- the current envelope. ** ** Returns: ** The exit code associated with the operation. ** ** Side Effects: ** none. */ # define RETURN(st) exit(st); static jmp_buf CtxMailfileTimeout; int mailfile(filename, mailer, ctladdr, sfflags, e) char *volatile filename; MAILER *volatile mailer; ADDRESS *ctladdr; volatile long sfflags; register ENVELOPE *e; { register SM_FILE_T *f; register pid_t pid = -1; volatile int mode; int len; off_t curoff; bool suidwarn = geteuid() == 0; char *p; char *volatile realfile; SM_EVENT *ev; char buf[MAXPATHLEN]; char targetfile[MAXPATHLEN]; if (tTd(11, 1)) { sm_dprintf("mailfile %s\n ctladdr=", filename); printaddr(sm_debug_file(), ctladdr, false); } if (mailer == NULL) mailer = FileMailer; if (e->e_xfp != NULL) (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT); /* ** Special case /dev/null. This allows us to restrict file ** delivery to regular files only. */ if (sm_path_isdevnull(filename)) return EX_OK; /* check for 8-bit available */ if (bitset(EF_HAS8BIT, e->e_flags) && bitnset(M_7BITS, mailer->m_flags) && (bitset(EF_DONT_MIME, e->e_flags) || !(bitset(MM_MIME8BIT, MimeMode) || (bitset(EF_IS_MIME, e->e_flags) && bitset(MM_CVTMIME, MimeMode))))) { e->e_status = "5.6.3"; usrerrenh(e->e_status, "554 Cannot send 8-bit data to 7-bit destination"); errno = 0; return EX_DATAERR; } /* Find the actual file */ if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0') { len = strlen(SafeFileEnv); if (strncmp(SafeFileEnv, filename, len) == 0) filename += len; if (len + strlen(filename) + 1 >= sizeof(targetfile)) { syserr("mailfile: filename too long (%s/%s)", SafeFileEnv, filename); return EX_CANTCREAT; } (void) sm_strlcpy(targetfile, SafeFileEnv, sizeof(targetfile)); realfile = targetfile + len; if (*filename == '/') filename++; if (*filename != '\0') { /* paranoia: trailing / should be removed in readcf */ if (targetfile[len - 1] != '/') (void) sm_strlcat(targetfile, "/", sizeof(targetfile)); (void) sm_strlcat(targetfile, filename, sizeof(targetfile)); } } else if (mailer->m_rootdir != NULL) { expand(mailer->m_rootdir, targetfile, sizeof(targetfile), e); len = strlen(targetfile); if (strncmp(targetfile, filename, len) == 0) filename += len; if (len + strlen(filename) + 1 >= sizeof(targetfile)) { syserr("mailfile: filename too long (%s/%s)", targetfile, filename); return EX_CANTCREAT; } realfile = targetfile + len; if (targetfile[len - 1] != '/') (void) sm_strlcat(targetfile, "/", sizeof(targetfile)); if (*filename == '/') (void) sm_strlcat(targetfile, filename + 1, sizeof(targetfile)); else (void) sm_strlcat(targetfile, filename, sizeof(targetfile)); } else { if (sm_strlcpy(targetfile, filename, sizeof(targetfile)) >= sizeof(targetfile)) { syserr("mailfile: filename too long (%s)", filename); return EX_CANTCREAT; } realfile = targetfile; } /* ** Fork so we can change permissions here. ** Note that we MUST use fork, not vfork, because of ** the complications of calling subroutines, etc. */ /* ** Dispose of SIGCHLD signal catchers that may be laying ** around so that the waitfor() below will get it. */ (void) sm_signal(SIGCHLD, SIG_DFL); DOFORK(fork); if (pid < 0) return EX_OSERR; else if (pid == 0) { /* child -- actually write to file */ struct stat stb; MCI mcibuf; int err; volatile int oflags = O_WRONLY|O_APPEND; /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; CurrentPid = getpid(); if (e->e_lockfp != NULL) { int fd; fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL); /* SM_ASSERT(fd >= 0); */ if (fd >= 0) (void) close(fd); } (void) sm_signal(SIGINT, SIG_DFL); (void) sm_signal(SIGHUP, SIG_DFL); (void) sm_signal(SIGTERM, SIG_DFL); (void) umask(OldUmask); e->e_to = filename; ExitStat = EX_OK; if (setjmp(CtxMailfileTimeout) != 0) { RETURN(EX_TEMPFAIL); } if (TimeOuts.to_fileopen > 0) ev = sm_setevent(TimeOuts.to_fileopen, mailfiletimeout, 0); else ev = NULL; /* check file mode to see if set-user-ID */ if (stat(targetfile, &stb) < 0) mode = FileMode; else mode = stb.st_mode; /* limit the errors to those actually caused in the child */ errno = 0; ExitStat = EX_OK; /* Allow alias expansions to use the S_IS{U,G}ID bits */ if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) || bitset(SFF_RUNASREALUID, sfflags)) { /* ignore set-user-ID and set-group-ID bits */ mode &= ~(S_ISGID|S_ISUID); if (tTd(11, 20)) sm_dprintf("mailfile: ignoring set-user-ID/set-group-ID bits\n"); } /* we have to open the data file BEFORE setuid() */ if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags)) { char *df = queuename(e, DATAFL_LETTER); e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df, SM_IO_RDONLY_B, NULL); if (e->e_dfp == NULL) { syserr("mailfile: Cannot open %s for %s from %s", df, e->e_to, e->e_from.q_paddr); } } /* select a new user to run as */ if (!bitset(SFF_RUNASREALUID, sfflags)) { if (bitnset(M_SPECIFIC_UID, mailer->m_flags)) { RealUserName = NULL; if (mailer->m_uid == NO_UID) RealUid = RunAsUid; else RealUid = mailer->m_uid; if (RunAsUid != 0 && RealUid != RunAsUid) { /* Only root can change the uid */ syserr("mailfile: insufficient privileges to change uid, RunAsUid=%d, RealUid=%d", (int) RunAsUid, (int) RealUid); RETURN(EX_TEMPFAIL); } } else if (bitset(S_ISUID, mode)) { RealUserName = NULL; RealUid = stb.st_uid; } else if (ctladdr != NULL && ctladdr->q_uid != 0) { if (ctladdr->q_ruser != NULL) RealUserName = ctladdr->q_ruser; else RealUserName = ctladdr->q_user; RealUid = ctladdr->q_uid; } else if (mailer != NULL && mailer->m_uid != NO_UID) { RealUserName = DefUser; RealUid = mailer->m_uid; } else { RealUserName = DefUser; RealUid = DefUid; } /* select a new group to run as */ if (bitnset(M_SPECIFIC_UID, mailer->m_flags)) { if (mailer->m_gid == NO_GID) RealGid = RunAsGid; else RealGid = mailer->m_gid; if (RunAsUid != 0 && (RealGid != getgid() || RealGid != getegid())) { /* Only root can change the gid */ syserr("mailfile: insufficient privileges to change gid, RealGid=%d, RunAsUid=%d, gid=%d, egid=%d", (int) RealGid, (int) RunAsUid, (int) getgid(), (int) getegid()); RETURN(EX_TEMPFAIL); } } else if (bitset(S_ISGID, mode)) RealGid = stb.st_gid; else if (ctladdr != NULL && ctladdr->q_uid == DefUid && ctladdr->q_gid == 0) { /* ** Special case: This means it is an ** alias and we should act as DefaultUser. ** See alias()'s comments. */ RealGid = DefGid; RealUserName = DefUser; } else if (ctladdr != NULL && ctladdr->q_uid != 0) RealGid = ctladdr->q_gid; else if (mailer != NULL && mailer->m_gid != NO_GID) RealGid = mailer->m_gid; else RealGid = DefGid; } /* last ditch */ if (!bitset(SFF_ROOTOK, sfflags)) { if (RealUid == 0) RealUid = DefUid; if (RealGid == 0) RealGid = DefGid; } /* set group id list (needs /etc/group access) */ if (RealUserName != NULL && !DontInitGroups) { if (initgroups(RealUserName, RealGid) == -1 && suidwarn) { syserr("mailfile: initgroups(%s, %d) failed", RealUserName, RealGid); RETURN(EX_TEMPFAIL); } } else { GIDSET_T gidset[1]; gidset[0] = RealGid; if (setgroups(1, gidset) == -1 && suidwarn) { syserr("mailfile: setgroups() failed"); RETURN(EX_TEMPFAIL); } } /* ** If you have a safe environment, go into it. */ if (realfile != targetfile) { char save; save = *realfile; *realfile = '\0'; if (tTd(11, 20)) sm_dprintf("mailfile: chroot %s\n", targetfile); if (chroot(targetfile) < 0) { syserr("mailfile: Cannot chroot(%s)", targetfile); RETURN(EX_CANTCREAT); } *realfile = save; } if (tTd(11, 40)) sm_dprintf("mailfile: deliver to %s\n", realfile); if (chdir("/") < 0) { syserr("mailfile: cannot chdir(/)"); RETURN(EX_CANTCREAT); } /* now reset the group and user ids */ endpwent(); sm_mbdb_terminate(); if (setgid(RealGid) < 0 && suidwarn) { syserr("mailfile: setgid(%ld) failed", (long) RealGid); RETURN(EX_TEMPFAIL); } vendor_set_uid(RealUid); if (setuid(RealUid) < 0 && suidwarn) { syserr("mailfile: setuid(%ld) failed", (long) RealUid); RETURN(EX_TEMPFAIL); } if (tTd(11, 2)) sm_dprintf("mailfile: running as r/euid=%d/%d, r/egid=%d/%d\n", (int) getuid(), (int) geteuid(), (int) getgid(), (int) getegid()); /* move into some "safe" directory */ if (mailer->m_execdir != NULL) { char *q; for (p = mailer->m_execdir; p != NULL; p = q) { q = strchr(p, ':'); if (q != NULL) *q = '\0'; expand(p, buf, sizeof(buf), e); if (q != NULL) *q++ = ':'; if (tTd(11, 20)) sm_dprintf("mailfile: trydir %s\n", buf); if (buf[0] != '\0' && chdir(buf) >= 0) break; } } /* ** Recheck the file after we have assumed the ID of the ** delivery user to make sure we can deliver to it as ** that user. This is necessary if sendmail is running ** as root and the file is on an NFS mount which treats ** root as nobody. */ #if HASLSTAT if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail)) err = stat(realfile, &stb); else err = lstat(realfile, &stb); #else /* HASLSTAT */ err = stat(realfile, &stb); #endif /* HASLSTAT */ if (err < 0) { stb.st_mode = ST_MODE_NOFILE; mode = FileMode; oflags |= O_CREAT|O_EXCL; } else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) || (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail) && stb.st_nlink != 1) || (realfile != targetfile && !S_ISREG(mode))) exit(EX_CANTCREAT); else mode = stb.st_mode; if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail)) sfflags |= SFF_NOSLINK; if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail)) sfflags |= SFF_NOHLINK; sfflags &= ~SFF_OPENASROOT; f = safefopen(realfile, oflags, mode, sfflags); if (f == NULL) { if (transienterror(errno)) { usrerr("454 4.3.0 cannot open %s: %s", shortenstring(realfile, MAXSHORTSTR), sm_errstring(errno)); RETURN(EX_TEMPFAIL); } else { usrerr("554 5.3.0 cannot open %s: %s", shortenstring(realfile, MAXSHORTSTR), sm_errstring(errno)); RETURN(EX_CANTCREAT); } } if (filechanged(realfile, sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb)) { syserr("554 5.3.0 file changed after open"); RETURN(EX_CANTCREAT); } if (fstat(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb) < 0) { syserr("554 5.3.0 cannot fstat %s", sm_errstring(errno)); RETURN(EX_CANTCREAT); } curoff = stb.st_size; if (ev != NULL) sm_clrevent(ev); memset(&mcibuf, '\0', sizeof(mcibuf)); mcibuf.mci_mailer = mailer; mcibuf.mci_out = f; if (bitnset(M_7BITS, mailer->m_flags)) mcibuf.mci_flags |= MCIF_7BIT; /* clear out per-message flags from connection structure */ mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7); if (bitset(EF_HAS8BIT, e->e_flags) && !bitset(EF_DONT_MIME, e->e_flags) && bitnset(M_7BITS, mailer->m_flags)) mcibuf.mci_flags |= MCIF_CVT8TO7; #if MIME7TO8 if (bitnset(M_MAKE8BIT, mailer->m_flags) && !bitset(MCIF_7BIT, mcibuf.mci_flags) && (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL && (sm_strcasecmp(p, "quoted-printable") == 0 || sm_strcasecmp(p, "base64") == 0) && (p = hvalue("Content-Type", e->e_header)) != NULL) { /* may want to convert 7 -> 8 */ /* XXX should really parse it here -- and use a class XXX */ if (sm_strncasecmp(p, "text/plain", 10) == 0 && (p[10] == '\0' || p[10] == ' ' || p[10] == ';')) mcibuf.mci_flags |= MCIF_CVT7TO8; } #endif /* MIME7TO8 */ if (!putfromline(&mcibuf, e) || !(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER) || !(*e->e_putbody)(&mcibuf, e, NULL) || !putline("\n", &mcibuf) || (sm_io_flush(f, SM_TIME_DEFAULT) != 0 || (SuperSafe != SAFE_NO && fsync(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL)) < 0) || sm_io_error(f))) { setstat(EX_IOERR); #if !NOFTRUNCATE (void) ftruncate(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), curoff); #endif /* !NOFTRUNCATE */ } /* reset ISUID & ISGID bits for paranoid systems */ #if HASFCHMOD (void) fchmod(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), (MODE_T) mode); #else /* HASFCHMOD */ (void) chmod(filename, (MODE_T) mode); #endif /* HASFCHMOD */ if (sm_io_close(f, SM_TIME_DEFAULT) < 0) setstat(EX_IOERR); (void) sm_io_flush(smioout, SM_TIME_DEFAULT); (void) setuid(RealUid); exit(ExitStat); /* NOTREACHED */ } else { /* parent -- wait for exit status */ int st; st = waitfor(pid); if (st == -1) { syserr("mailfile: %s: wait", mailer->m_name); return EX_SOFTWARE; } if (WIFEXITED(st)) { errno = 0; return (WEXITSTATUS(st)); } else { syserr("mailfile: %s: child died on signal %d", mailer->m_name, st); return EX_UNAVAILABLE; } /* NOTREACHED */ } return EX_UNAVAILABLE; /* avoid compiler warning on IRIX */ } static void mailfiletimeout(ignore) int ignore; { /* ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ errno = ETIMEDOUT; longjmp(CtxMailfileTimeout, 1); } /* ** HOSTSIGNATURE -- return the "signature" for a host. ** ** The signature describes how we are going to send this -- it ** can be just the hostname (for non-Internet hosts) or can be ** an ordered list of MX hosts. ** ** Parameters: ** m -- the mailer describing this host. ** host -- the host name. ** ** Returns: ** The signature for this host. ** ** Side Effects: ** Can tweak the symbol table. */ #define MAXHOSTSIGNATURE 8192 /* max len of hostsignature */ char * hostsignature(m, host) register MAILER *m; char *host; { register char *p; register STAB *s; time_t now; #if NAMED_BIND char sep = ':'; char prevsep = ':'; int i; int len; int nmx; int hl; char *hp; char *endp; int oldoptions = _res.options; char *mxhosts[MAXMXHOSTS + 1]; unsigned short mxprefs[MAXMXHOSTS + 1]; #endif /* NAMED_BIND */ if (tTd(17, 3)) sm_dprintf("hostsignature(%s)\n", host); /* ** If local delivery (and not remote), just return a constant. */ if (bitnset(M_LOCALMAILER, m->m_flags) && strcmp(m->m_mailer, "[IPC]") != 0 && !(m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0)) return "localhost"; /* an empty host does not have MX records */ if (*host == '\0') return "_empty_"; /* ** Check to see if this uses IPC -- if not, it can't have MX records. */ if (strcmp(m->m_mailer, "[IPC]") != 0 || CurEnv->e_sendmode == SM_DEFER) { /* just an ordinary mailer or deferred mode */ return host; } #if NETUNIX else if (m->m_argv[0] != NULL && strcmp(m->m_argv[0], "FILE") == 0) { /* rendezvous in the file system, no MX records */ return host; } #endif /* NETUNIX */ /* ** Look it up in the symbol table. */ now = curtime(); s = stab(host, ST_HOSTSIG, ST_ENTER); if (s->s_hostsig.hs_sig != NULL) { if (s->s_hostsig.hs_exp >= now) { if (tTd(17, 3)) sm_dprintf("hostsignature(): stab(%s) found %s\n", host, s->s_hostsig.hs_sig); return s->s_hostsig.hs_sig; } /* signature is expired: clear it */ sm_free(s->s_hostsig.hs_sig); s->s_hostsig.hs_sig = NULL; } /* set default TTL */ s->s_hostsig.hs_exp = now + SM_DEFAULT_TTL; /* ** Not already there or expired -- create a signature. */ #if NAMED_BIND if (ConfigLevel < 2) _res.options &= ~(RES_DEFNAMES | RES_DNSRCH); /* XXX */ for (hp = host; hp != NULL; hp = endp) { #if NETINET6 if (*hp == '[') { endp = strchr(hp + 1, ']'); if (endp != NULL) endp = strpbrk(endp + 1, ":,"); } else endp = strpbrk(hp, ":,"); #else /* NETINET6 */ endp = strpbrk(hp, ":,"); #endif /* NETINET6 */ if (endp != NULL) { sep = *endp; *endp = '\0'; } if (bitnset(M_NOMX, m->m_flags)) { /* skip MX lookups */ nmx = 1; mxhosts[0] = hp; } else { auto int rcode; int ttl; nmx = getmxrr(hp, mxhosts, mxprefs, true, &rcode, true, &ttl); if (nmx <= 0) { int save_errno; register MCI *mci; /* update the connection info for this host */ save_errno = errno; mci = mci_get(hp, m); mci->mci_errno = save_errno; mci->mci_herrno = h_errno; mci->mci_lastuse = now; if (rcode == EX_NOHOST) mci_setstat(mci, rcode, "5.1.2", "550 Host unknown"); else mci_setstat(mci, rcode, NULL, NULL); /* use the original host name as signature */ nmx = 1; mxhosts[0] = hp; } if (tTd(17, 3)) sm_dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n", nmx, mxhosts[0]); /* ** Set new TTL: we use only one! ** We could try to use the minimum instead. */ s->s_hostsig.hs_exp = now + SM_MIN(ttl, SM_DEFAULT_TTL); } len = 0; for (i = 0; i < nmx; i++) len += strlen(mxhosts[i]) + 1; if (s->s_hostsig.hs_sig != NULL) len += strlen(s->s_hostsig.hs_sig) + 1; if (len < 0 || len >= MAXHOSTSIGNATURE) { sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d", host, MAXHOSTSIGNATURE, len); len = MAXHOSTSIGNATURE; } p = sm_pmalloc_x(len); if (s->s_hostsig.hs_sig != NULL) { (void) sm_strlcpy(p, s->s_hostsig.hs_sig, len); sm_free(s->s_hostsig.hs_sig); /* XXX */ s->s_hostsig.hs_sig = p; hl = strlen(p); p += hl; *p++ = prevsep; len -= hl + 1; } else s->s_hostsig.hs_sig = p; for (i = 0; i < nmx; i++) { hl = strlen(mxhosts[i]); if (len - 1 < hl || len <= 1) { /* force to drop out of outer loop */ len = -1; break; } if (i != 0) { if (mxprefs[i] == mxprefs[i - 1]) *p++ = ','; else *p++ = ':'; len--; } (void) sm_strlcpy(p, mxhosts[i], len); p += hl; len -= hl; } /* ** break out of loop if len exceeded MAXHOSTSIGNATURE ** because we won't have more space for further hosts ** anyway (separated by : in the .cf file). */ if (len < 0) break; if (endp != NULL) *endp++ = sep; prevsep = sep; } makelower(s->s_hostsig.hs_sig); if (ConfigLevel < 2) _res.options = oldoptions; #else /* NAMED_BIND */ /* not using BIND -- the signature is just the host name */ /* ** 'host' points to storage that will be freed after we are ** done processing the current envelope, so we copy it. */ s->s_hostsig.hs_sig = sm_pstrdup_x(host); #endif /* NAMED_BIND */ if (tTd(17, 1)) sm_dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig.hs_sig); return s->s_hostsig.hs_sig; } /* ** PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array. ** ** The signature describes how we are going to send this -- it ** can be just the hostname (for non-Internet hosts) or can be ** an ordered list of MX hosts which must be randomized for equal ** MX preference values. ** ** Parameters: ** sig -- the host signature. ** mxhosts -- array to populate. ** mailer -- mailer. ** ** Returns: ** The number of hosts inserted into mxhosts array. ** ** Side Effects: ** Randomizes equal MX preference hosts in mxhosts. */ static int parse_hostsignature(sig, mxhosts, mailer) char *sig; char **mxhosts; MAILER *mailer; { unsigned short curpref = 0; int nmx = 0, i, j; /* NOTE: i, j, and nmx must have same type */ char *hp, *endp; unsigned short prefer[MAXMXHOSTS]; long rndm[MAXMXHOSTS]; for (hp = sig; hp != NULL; hp = endp) { char sep = ':'; #if NETINET6 if (*hp == '[') { endp = strchr(hp + 1, ']'); if (endp != NULL) endp = strpbrk(endp + 1, ":,"); } else endp = strpbrk(hp, ":,"); #else /* NETINET6 */ endp = strpbrk(hp, ":,"); #endif /* NETINET6 */ if (endp != NULL) { sep = *endp; *endp = '\0'; } mxhosts[nmx] = hp; prefer[nmx] = curpref; if (mci_match(hp, mailer)) rndm[nmx] = 0; else rndm[nmx] = get_random(); if (endp != NULL) { /* ** Since we don't have the original MX prefs, ** make our own. If the separator is a ':', that ** means the preference for the next host will be ** higher than this one, so simply increment curpref. */ if (sep == ':') curpref++; *endp++ = sep; } if (++nmx >= MAXMXHOSTS) break; } /* sort the records using the random factor for equal preferences */ for (i = 0; i < nmx; i++) { for (j = i + 1; j < nmx; j++) { /* ** List is already sorted by MX preference, only ** need to look for equal preference MX records */ if (prefer[i] < prefer[j]) break; if (prefer[i] > prefer[j] || (prefer[i] == prefer[j] && rndm[i] > rndm[j])) { register unsigned short tempp; register long tempr; register char *temp1; tempp = prefer[i]; prefer[i] = prefer[j]; prefer[j] = tempp; temp1 = mxhosts[i]; mxhosts[i] = mxhosts[j]; mxhosts[j] = temp1; tempr = rndm[i]; rndm[i] = rndm[j]; rndm[j] = tempr; } } } return nmx; } # if STARTTLS static SSL_CTX *clt_ctx = NULL; static bool tls_ok_clt = true; /* ** SETCLTTLS -- client side TLS: allow/disallow. ** ** Parameters: ** tls_ok -- should tls be done? ** ** Returns: ** none. ** ** Side Effects: ** sets tls_ok_clt (static variable in this module) */ void setclttls(tls_ok) bool tls_ok; { tls_ok_clt = tls_ok; return; } /* ** INITCLTTLS -- initialize client side TLS ** ** Parameters: ** tls_ok -- should tls initialization be done? ** ** Returns: ** succeeded? ** ** Side Effects: ** sets tls_ok_clt (static variable in this module) */ bool initclttls(tls_ok) bool tls_ok; { if (!tls_ok_clt) return false; tls_ok_clt = tls_ok; if (!tls_ok_clt) return false; if (clt_ctx != NULL) return true; /* already done */ tls_ok_clt = inittls(&clt_ctx, TLS_I_CLT, Clt_SSL_Options, false, CltCertFile, CltKeyFile, CACertPath, CACertFile, DHParams); return tls_ok_clt; } /* ** STARTTLS -- try to start secure connection (client side) ** ** Parameters: ** m -- the mailer. ** mci -- the mailer connection info. ** e -- the envelope. ** ** Returns: ** success? ** (maybe this should be some other code than EX_ ** that denotes which stage failed.) */ static int starttls(m, mci, e) MAILER *m; MCI *mci; ENVELOPE *e; { int smtpresult; int result = 0; int rfd, wfd; SSL *clt_ssl = NULL; time_t tlsstart; if (clt_ctx == NULL && !initclttls(true)) return EX_TEMPFAIL; # if USE_OPENSSL_ENGINE if (!SSLEngineInitialized && !SSL_set_engine(NULL)) { sm_syslog(LOG_ERR, NOQID, "STARTTLS=client, SSL_set_engine=failed"); return EX_TEMPFAIL; } SSLEngineInitialized = true; # endif /* USE_OPENSSL_ENGINE */ smtpmessage("STARTTLS", m, mci); /* get the reply */ smtpresult = reply(m, mci, e, TimeOuts.to_starttls, NULL, NULL, XS_STARTTLS); /* check return code from server */ if (REPLYTYPE(smtpresult) == 4) return EX_TEMPFAIL; if (smtpresult == 501) return EX_USAGE; if (smtpresult == -1) return smtpresult; /* not an expected reply but we have to deal with it */ if (REPLYTYPE(smtpresult) == 5) return EX_UNAVAILABLE; if (smtpresult != 220) return EX_PROTOCOL; if (LogLevel > 13) sm_syslog(LOG_INFO, NOQID, "STARTTLS=client, start=ok"); /* start connection */ if ((clt_ssl = SSL_new(clt_ctx)) == NULL) { if (LogLevel > 5) { sm_syslog(LOG_ERR, NOQID, "STARTTLS=client, error: SSL_new failed"); if (LogLevel > 9) - tlslogerr("client"); + tlslogerr(LOG_WARNING, "client"); } return EX_SOFTWARE; } rfd = sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL); wfd = sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL); /* SSL_clear(clt_ssl); ? */ if (rfd < 0 || wfd < 0 || (result = SSL_set_rfd(clt_ssl, rfd)) != 1 || (result = SSL_set_wfd(clt_ssl, wfd)) != 1) { if (LogLevel > 5) { sm_syslog(LOG_ERR, NOQID, "STARTTLS=client, error: SSL_set_xfd failed=%d", result); if (LogLevel > 9) - tlslogerr("client"); + tlslogerr(LOG_WARNING, "client"); } return EX_SOFTWARE; } SSL_set_connect_state(clt_ssl); tlsstart = curtime(); ssl_retry: if ((result = SSL_connect(clt_ssl)) <= 0) { int i, ssl_err; ssl_err = SSL_get_error(clt_ssl, result); i = tls_retry(clt_ssl, rfd, wfd, tlsstart, TimeOuts.to_starttls, ssl_err, "client"); if (i > 0) goto ssl_retry; if (LogLevel > 5) { unsigned long l; const char *sr; l = ERR_peek_error(); sr = ERR_reason_error_string(l); sm_syslog(LOG_WARNING, NOQID, "STARTTLS=client, error: connect failed=%d, reason=%s, SSL_error=%d, errno=%d, retry=%d", result, sr == NULL ? "unknown" : sr, ssl_err, errno, i); if (LogLevel > 9) - tlslogerr("client"); + tlslogerr(LOG_WARNING, "client"); } SSL_free(clt_ssl); clt_ssl = NULL; return EX_SOFTWARE; } mci->mci_ssl = clt_ssl; result = tls_get_info(mci->mci_ssl, false, mci->mci_host, &mci->mci_macro, true); /* switch to use TLS... */ if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0) return EX_OK; /* failure */ SSL_free(clt_ssl); clt_ssl = NULL; return EX_SOFTWARE; } /* ** ENDTLSCLT -- shutdown secure connection (client side) ** ** Parameters: ** mci -- the mailer connection info. ** ** Returns: ** success? */ static int endtlsclt(mci) MCI *mci; { int r; if (!bitset(MCIF_TLSACT, mci->mci_flags)) return EX_OK; r = endtls(mci->mci_ssl, "client"); mci->mci_flags &= ~MCIF_TLSACT; return r; } # endif /* STARTTLS */ # if STARTTLS || SASL /* ** ISCLTFLGSET -- check whether client flag is set. ** ** Parameters: ** e -- envelope. ** flag -- flag to check in {client_flags} ** ** Returns: ** true iff flag is set. */ static bool iscltflgset(e, flag) ENVELOPE *e; int flag; { char *p; p = macvalue(macid("{client_flags}"), e); if (p == NULL) return false; for (; *p != '\0'; p++) { /* look for just this one flag */ if (*p == (char) flag) return true; } return false; } # endif /* STARTTLS || SASL */ Index: head/contrib/sendmail/src/main.c =================================================================== --- head/contrib/sendmail/src/main.c (revision 249728) +++ head/contrib/sendmail/src/main.c (revision 249729) @@ -1,4576 +1,4582 @@ /* * Copyright (c) 1998-2006, 2008, 2009, 2011 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #define _DEFINE #include #include #include #include #ifndef lint SM_UNUSED(static char copyright[]) = "@(#) Copyright (c) 1998-2003 Sendmail, Inc. and its suppliers.\n\ All rights reserved.\n\ Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.\n\ Copyright (c) 1988, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* ! lint */ -SM_RCSID("@(#)$Id: main.c,v 8.981 2012/06/14 23:54:02 ca Exp $") +SM_RCSID("@(#)$Id: main.c,v 8.983 2013/03/12 15:24:52 ca Exp $") #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ /* for getcfname() */ #include static SM_DEBUG_T DebugNoPRestart = SM_DEBUG_INITIALIZER("no_persistent_restart", "@(#)$Debug: no_persistent_restart - don't restart, log only $"); static void dump_class __P((STAB *, int)); static void obsolete __P((char **)); static void testmodeline __P((char *, ENVELOPE *)); static char *getextenv __P((const char *)); static void sm_printoptions __P((char **)); static SIGFUNC_DECL intindebug __P((int)); static SIGFUNC_DECL sighup __P((int)); static SIGFUNC_DECL sigpipe __P((int)); static SIGFUNC_DECL sigterm __P((int)); #ifdef SIGUSR1 static SIGFUNC_DECL sigusr1 __P((int)); #endif /* SIGUSR1 */ /* ** SENDMAIL -- Post mail to a set of destinations. ** ** This is the basic mail router. All user mail programs should ** call this routine to actually deliver mail. Sendmail in ** turn calls a bunch of mail servers that do the real work of ** delivering the mail. ** ** Sendmail is driven by settings read in from /etc/mail/sendmail.cf ** (read by readcf.c). ** ** Usage: ** /usr/lib/sendmail [flags] addr ... ** ** See the associated documentation for details. ** ** Authors: ** Eric Allman, UCB/INGRES (until 10/81). ** Britton-Lee, Inc., purveyors of fine ** database computers (11/81 - 10/88). ** International Computer Science Institute ** (11/88 - 9/89). ** UCB/Mammoth Project (10/89 - 7/95). ** InReference, Inc. (8/95 - 1/97). ** Sendmail, Inc. (1/98 - present). ** The support of my employers is gratefully acknowledged. ** Few of them (Britton-Lee in particular) have had ** anything to gain from my involvement in this project. ** ** Gregory Neil Shapiro, ** Worcester Polytechnic Institute (until 3/98). ** Sendmail, Inc. (3/98 - present). ** ** Claus Assmann, ** Sendmail, Inc. (12/98 - present). */ char *FullName; /* sender's full name */ ENVELOPE BlankEnvelope; /* a "blank" envelope */ static ENVELOPE MainEnvelope; /* the envelope around the basic letter */ ADDRESS NullAddress = /* a null address */ { "", "", NULL, "" }; char *CommandLineArgs; /* command line args for pid file */ bool Warn_Q_option = false; /* warn about Q option use */ static int MissingFds = 0; /* bit map of fds missing on startup */ char *Mbdb = "pw"; /* mailbox database defaults to /etc/passwd */ #ifdef NGROUPS_MAX GIDSET_T InitialGidSet[NGROUPS_MAX]; #endif /* NGROUPS_MAX */ #define MAXCONFIGLEVEL 10 /* highest config version level known */ #if SASL static sasl_callback_t srvcallbacks[] = { { SASL_CB_VERIFYFILE, (sasl_callback_ft)&safesaslfile, NULL }, { SASL_CB_PROXY_POLICY, (sasl_callback_ft)&proxy_policy, NULL }, { SASL_CB_LIST_END, NULL, NULL } }; #endif /* SASL */ unsigned int SubmitMode; int SyslogPrefixLen; /* estimated length of syslog prefix */ #define PIDLEN 6 /* pid length for computing SyslogPrefixLen */ #ifndef SL_FUDGE # define SL_FUDGE 10 /* fudge offset for SyslogPrefixLen */ #endif /* ! SL_FUDGE */ #define SLDLL 8 /* est. length of default syslog label */ /* Some options are dangerous to allow users to use in non-submit mode */ #define CHECK_AGAINST_OPMODE(cmd) \ { \ if (extraprivs && \ OpMode != MD_DELIVER && OpMode != MD_SMTP && \ OpMode != MD_ARPAFTP && OpMode != MD_CHECKCONFIG && \ OpMode != MD_VERIFY && OpMode != MD_TEST) \ { \ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \ "WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \ (cmd)); \ break; \ } \ if (extraprivs && queuerun) \ { \ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \ "WARNING: Ignoring submission mode -%c option with -q\n", \ (cmd)); \ break; \ } \ } int main(argc, argv, envp) int argc; char **argv; char **envp; { register char *p; char **av; extern char Version[]; char *ep, *from; STAB *st; register int i; int j; int dp; int fill_errno; int qgrp = NOQGRP; /* queue group to process */ bool safecf = true; BITMAP256 *p_flags = NULL; /* daemon flags */ bool warn_C_flag = false; bool auth = true; /* whether to set e_auth_param */ char warn_f_flag = '\0'; bool run_in_foreground = false; /* -bD mode */ bool queuerun = false, debug = false; struct passwd *pw; struct hostent *hp; char *nullserver = NULL; char *authinfo = NULL; char *sysloglabel = NULL; /* label for syslog */ char *conffile = NULL; /* name of .cf file */ char *queuegroup = NULL; /* queue group to process */ char *quarantining = NULL; /* quarantine queue items? */ bool extraprivs; bool forged, negate; bool queuepersistent = false; /* queue runner process runs forever */ bool foregroundqueue = false; /* queue run in foreground */ bool save_val; /* to save some bool var. */ int cftype; /* which cf file to use? */ SM_FILE_T *smdebug; static time_t starttime = 0; /* when was process started */ struct stat traf_st; /* for TrafficLog FIFO check */ char buf[MAXLINE]; char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */ static char rnamebuf[MAXNAME]; /* holds RealUserName */ char *emptyenviron[1]; #if STARTTLS bool tls_ok; #endif /* STARTTLS */ QUEUE_CHAR *new; ENVELOPE *e; extern int DtableSize; extern int optind; extern int opterr; extern char *optarg; extern char **environ; #if SASL extern void sm_sasl_init __P((void)); #endif /* SASL */ #if USE_ENVIRON envp = environ; #endif /* USE_ENVIRON */ /* turn off profiling */ SM_PROF(0); /* install default exception handler */ sm_exc_newthread(fatal_error); /* set the default in/out channel so errors reported to screen */ InChannel = smioin; OutChannel = smioout; /* ** Check to see if we reentered. ** This would normally happen if e_putheader or e_putbody ** were NULL when invoked. */ if (starttime != 0) { syserr("main: reentered!"); abort(); } starttime = curtime(); /* avoid null pointer dereferences */ TermEscape.te_rv_on = TermEscape.te_under_on = TermEscape.te_normal = ""; RealUid = getuid(); RealGid = getgid(); /* Check if sendmail is running with extra privs */ extraprivs = (RealUid != 0 && (geteuid() != getuid() || getegid() != getgid())); CurrentPid = getpid(); /* get whatever .cf file is right for the opmode */ cftype = SM_GET_RIGHT_CF; /* in 4.4BSD, the table can be huge; impose a reasonable limit */ DtableSize = getdtsize(); if (DtableSize > 256) DtableSize = 256; /* ** Be sure we have enough file descriptors. ** But also be sure that 0, 1, & 2 are open. */ /* reset errno and fill_errno; the latter is used way down below */ errno = fill_errno = 0; fill_fd(STDIN_FILENO, NULL); if (errno != 0) fill_errno = errno; fill_fd(STDOUT_FILENO, NULL); if (errno != 0) fill_errno = errno; fill_fd(STDERR_FILENO, NULL); if (errno != 0) fill_errno = errno; sm_closefrom(STDERR_FILENO + 1, DtableSize); errno = 0; smdebug = NULL; #if LOG # ifndef SM_LOG_STR # define SM_LOG_STR "sendmail" # endif /* ! SM_LOG_STR */ # ifdef LOG_MAIL openlog(SM_LOG_STR, LOG_PID, LOG_MAIL); # else /* LOG_MAIL */ openlog(SM_LOG_STR, LOG_PID); # endif /* LOG_MAIL */ #endif /* LOG */ /* ** Seed the random number generator. ** Used for queue file names, picking a queue directory, and ** MX randomization. */ seed_random(); /* do machine-dependent initializations */ init_md(argc, argv); SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL; /* reset status from syserr() calls for missing file descriptors */ Errors = 0; ExitStat = EX_OK; SubmitMode = SUBMIT_UNKNOWN; #if _FFR_LOCAL_DAEMON LocalDaemon = false; # if NETINET6 V6LoopbackAddrFound = false; # endif /* NETINET6 */ #endif /* _FFR_LOCAL_DAEMON */ #if XDEBUG checkfd012("after openlog"); #endif /* XDEBUG */ tTsetup(tTdvect, sizeof(tTdvect), "0-99.1,*_trace_*.1"); #ifdef NGROUPS_MAX /* save initial group set for future checks */ i = getgroups(NGROUPS_MAX, InitialGidSet); if (i <= 0) { InitialGidSet[0] = (GID_T) -1; i = 0; } while (i < NGROUPS_MAX) InitialGidSet[i++] = InitialGidSet[0]; #endif /* NGROUPS_MAX */ /* drop group id privileges (RunAsUser not yet set) */ dp = drop_privileges(false); setstat(dp); #ifdef SIGUSR1 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */ if (!extraprivs) { /* arrange to dump state on user-1 signal */ (void) sm_signal(SIGUSR1, sigusr1); } else { /* ignore user-1 signal */ (void) sm_signal(SIGUSR1, SIG_IGN); } #endif /* SIGUSR1 */ /* initialize for setproctitle */ initsetproctitle(argc, argv, envp); /* Handle any non-getoptable constructions. */ obsolete(argv); /* ** Do a quick prescan of the argument list. */ /* find initial opMode */ OpMode = MD_DELIVER; av = argv; p = strrchr(*av, '/'); if (p++ == NULL) p = *av; if (strcmp(p, "newaliases") == 0) OpMode = MD_INITALIAS; else if (strcmp(p, "mailq") == 0) OpMode = MD_PRINT; else if (strcmp(p, "smtpd") == 0) OpMode = MD_DAEMON; else if (strcmp(p, "hoststat") == 0) OpMode = MD_HOSTSTAT; else if (strcmp(p, "purgestat") == 0) OpMode = MD_PURGESTAT; #if defined(__osf__) || defined(_AIX3) # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:x" #endif /* defined(__osf__) || defined(_AIX3) */ #if defined(sony_news) # define OPTIONS "A:B:b:C:cD:d:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:" #endif /* defined(sony_news) */ #ifndef OPTIONS # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:" #endif /* ! OPTIONS */ /* Set to 0 to allow -b; need to check optarg before using it! */ opterr = 0; while ((j = getopt(argc, argv, OPTIONS)) != -1) { switch (j) { case 'b': /* operations mode */ j = (optarg == NULL) ? ' ' : *optarg; switch (j) { case MD_DAEMON: case MD_FGDAEMON: case MD_SMTP: case MD_INITALIAS: case MD_DELIVER: case MD_VERIFY: case MD_TEST: case MD_PRINT: case MD_PRINTNQE: case MD_HOSTSTAT: case MD_PURGESTAT: case MD_ARPAFTP: #if _FFR_CHECKCONFIG case MD_CHECKCONFIG: #endif /* _FFR_CHECKCONFIG */ OpMode = j; break; #if _FFR_LOCAL_DAEMON case MD_LOCAL: OpMode = MD_DAEMON; LocalDaemon = true; break; #endif /* _FFR_LOCAL_DAEMON */ case MD_FREEZE: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Frozen configurations unsupported\n"); return EX_USAGE; default: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Invalid operation mode %c\n", j); return EX_USAGE; } break; case 'D': if (debug) { errno = 0; syserr("-D file must be before -d"); ExitStat = EX_USAGE; break; } dp = drop_privileges(true); setstat(dp); smdebug = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, optarg, SM_IO_APPEND, NULL); if (smdebug == NULL) { syserr("cannot open %s", optarg); ExitStat = EX_CANTCREAT; break; } sm_debug_setfile(smdebug); break; case 'd': debug = true; tTflag(optarg); (void) sm_io_setvbuf(sm_debug_file(), SM_TIME_DEFAULT, (char *) NULL, SM_IO_NBF, SM_IO_BUFSIZ); break; case 'G': /* relay (gateway) submission */ SubmitMode = SUBMIT_MTA; break; case 'L': if (optarg == NULL) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "option requires an argument -- '%c'", (char) j); return EX_USAGE; } j = SM_MIN(strlen(optarg), 32) + 1; sysloglabel = xalloc(j); (void) sm_strlcpy(sysloglabel, optarg, j); SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + j; break; case 'Q': case 'q': /* just check if it is there */ queuerun = true; break; } } opterr = 1; /* Don't leak queue information via debug flags */ if (extraprivs && queuerun && debug) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: Can not use -d with -q. Disabling debugging.\n"); sm_debug_close(); sm_debug_setfile(NULL); (void) memset(tTdvect, '\0', sizeof(tTdvect)); } #if LOG if (sysloglabel != NULL) { /* Sanitize the string */ for (p = sysloglabel; *p != '\0'; p++) { if (!isascii(*p) || !isprint(*p) || *p == '%') *p = '*'; } closelog(); # ifdef LOG_MAIL openlog(sysloglabel, LOG_PID, LOG_MAIL); # else /* LOG_MAIL */ openlog(sysloglabel, LOG_PID); # endif /* LOG_MAIL */ } #endif /* LOG */ /* set up the blank envelope */ BlankEnvelope.e_puthdr = putheader; BlankEnvelope.e_putbody = putbody; BlankEnvelope.e_xfp = NULL; STRUCTCOPY(NullAddress, BlankEnvelope.e_from); CurEnv = &BlankEnvelope; STRUCTCOPY(NullAddress, MainEnvelope.e_from); /* ** Set default values for variables. ** These cannot be in initialized data space. */ setdefaults(&BlankEnvelope); initmacros(&BlankEnvelope); /* reset macro */ set_op_mode(OpMode); if (OpMode == MD_DAEMON) DaemonPid = CurrentPid; /* needed for finis() to work */ pw = sm_getpwuid(RealUid); if (pw != NULL) (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof(rnamebuf)); else (void) sm_snprintf(rnamebuf, sizeof(rnamebuf), "Unknown UID %d", (int) RealUid); RealUserName = rnamebuf; if (tTd(0, 101)) { sm_dprintf("Version %s\n", Version); finis(false, true, EX_OK); /* NOTREACHED */ } /* ** if running non-set-user-ID binary as non-root, pretend ** we are the RunAsUid */ if (RealUid != 0 && geteuid() == RealUid) { if (tTd(47, 1)) sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n", (int) RealUid); RunAsUid = RealUid; } else if (geteuid() != 0) RunAsUid = geteuid(); EffGid = getegid(); if (RealUid != 0 && EffGid == RealGid) RunAsGid = RealGid; if (tTd(47, 5)) { sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n", (int) geteuid(), (int) getuid(), (int) getegid(), (int) getgid()); sm_dprintf("main: RunAsUser = %d:%d\n", (int) RunAsUid, (int) RunAsGid); } /* save command line arguments */ j = 0; for (av = argv; *av != NULL; ) j += strlen(*av++) + 1; SaveArgv = (char **) xalloc(sizeof(char *) * (argc + 1)); CommandLineArgs = xalloc(j); p = CommandLineArgs; for (av = argv, i = 0; *av != NULL; ) { int h; SaveArgv[i++] = newstr(*av); if (av != argv) *p++ = ' '; (void) sm_strlcpy(p, *av++, j); h = strlen(p); p += h; j -= h + 1; } SaveArgv[i] = NULL; if (tTd(0, 1)) { extern char *CompileOptions[]; sm_dprintf("Version %s\n Compiled with:", Version); sm_printoptions(CompileOptions); } if (tTd(0, 10)) { extern char *OsCompileOptions[]; sm_dprintf(" OS Defines:"); sm_printoptions(OsCompileOptions); #ifdef _PATH_UNIX sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX); #endif /* _PATH_UNIX */ sm_dprintf(" Conf file:\t%s (default for MSP)\n", getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF, conffile)); sm_dprintf(" Conf file:\t%s (default for MTA)\n", getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF, conffile)); sm_dprintf(" Pid file:\t%s (default)\n", PidFile); } if (tTd(0, 12)) { extern char *SmCompileOptions[]; sm_dprintf(" libsm Defines:"); sm_printoptions(SmCompileOptions); } if (tTd(0, 13)) { extern char *FFRCompileOptions[]; sm_dprintf(" FFR Defines:"); sm_printoptions(FFRCompileOptions); } /* clear sendmail's environment */ ExternalEnviron = environ; emptyenviron[0] = NULL; environ = emptyenviron; /* ** restore any original TZ setting until TimeZoneSpec has been ** determined - or early log messages may get bogus time stamps */ if ((p = getextenv("TZ")) != NULL) { char *tz; int tzlen; /* XXX check for reasonable length? */ tzlen = strlen(p) + 4; tz = xalloc(tzlen); (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p); /* XXX check return code? */ (void) putenv(tz); } /* prime the child environment */ sm_setuserenv("AGENT", "sendmail"); (void) sm_signal(SIGPIPE, SIG_IGN); OldUmask = umask(022); FullName = getextenv("NAME"); if (FullName != NULL) FullName = newstr(FullName); /* ** Initialize name server if it is going to be used. */ #if NAMED_BIND if (!bitset(RES_INIT, _res.options)) (void) res_init(); if (tTd(8, 8)) _res.options |= RES_DEBUG; else _res.options &= ~RES_DEBUG; # ifdef RES_NOALIASES _res.options |= RES_NOALIASES; # endif /* RES_NOALIASES */ TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry; TimeOuts.res_retry[RES_TO_FIRST] = _res.retry; TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry; TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans; TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans; TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans; #endif /* NAMED_BIND */ errno = 0; from = NULL; /* initialize some macros, etc. */ init_vendor_macros(&BlankEnvelope); /* version */ macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version); /* hostname */ hp = myhostname(jbuf, sizeof(jbuf)); if (jbuf[0] != '\0') { struct utsname utsname; if (tTd(0, 4)) sm_dprintf("Canonical name: %s\n", jbuf); macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf); macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf); setclass('w', jbuf); p = strchr(jbuf, '.'); if (p != NULL && p[1] != '\0') macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm', &p[1]); if (uname(&utsname) >= 0) p = utsname.nodename; else { if (tTd(0, 22)) sm_dprintf("uname failed (%s)\n", sm_errstring(errno)); makelower(jbuf); p = jbuf; } if (tTd(0, 4)) sm_dprintf(" UUCP nodename: %s\n", p); macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p); setclass('k', p); setclass('w', p); } if (hp != NULL) { for (av = hp->h_aliases; av != NULL && *av != NULL; av++) { if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", *av); setclass('w', *av); } #if NETINET || NETINET6 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++) { # if NETINET6 char *addr; char buf6[INET6_ADDRSTRLEN]; struct in6_addr ia6; # endif /* NETINET6 */ # if NETINET struct in_addr ia; # endif /* NETINET */ char ipbuf[103]; ipbuf[0] = '\0'; switch (hp->h_addrtype) { # if NETINET case AF_INET: if (hp->h_length != INADDRSZ) break; memmove(&ia, hp->h_addr_list[i], INADDRSZ); (void) sm_snprintf(ipbuf, sizeof(ipbuf), "[%.100s]", inet_ntoa(ia)); break; # endif /* NETINET */ # if NETINET6 case AF_INET6: if (hp->h_length != IN6ADDRSZ) break; memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ); addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); if (addr != NULL) (void) sm_snprintf(ipbuf, sizeof(ipbuf), "[%.100s]", addr); break; # endif /* NETINET6 */ } if (ipbuf[0] == '\0') break; if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", ipbuf); setclass('w', ipbuf); } #endif /* NETINET || NETINET6 */ #if NETINET6 freehostent(hp); hp = NULL; #endif /* NETINET6 */ } /* current time */ macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL)); /* current load average */ sm_getla(); QueueLimitRecipient = (QUEUE_CHAR *) NULL; QueueLimitSender = (QUEUE_CHAR *) NULL; QueueLimitId = (QUEUE_CHAR *) NULL; QueueLimitQuarantine = (QUEUE_CHAR *) NULL; /* ** Crack argv. */ optind = 1; while ((j = getopt(argc, argv, OPTIONS)) != -1) { switch (j) { case 'b': /* operations mode */ /* already done */ break; case 'A': /* use Alternate sendmail/submit.cf */ cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF : SM_GET_SENDMAIL_CF; break; case 'B': /* body type */ CHECK_AGAINST_OPMODE(j); BlankEnvelope.e_bodytype = newstr(optarg); break; case 'C': /* select configuration file (already done) */ if (RealUid != 0) warn_C_flag = true; conffile = newstr(optarg); dp = drop_privileges(true); setstat(dp); safecf = false; break; case 'D': case 'd': /* debugging */ /* already done */ break; case 'f': /* from address */ case 'r': /* obsolete -f flag */ CHECK_AGAINST_OPMODE(j); if (from != NULL) { usrerr("More than one \"from\" person"); ExitStat = EX_USAGE; break; } if (optarg[0] == '\0') from = newstr("<>"); else from = newstr(denlstring(optarg, true, true)); if (strcmp(RealUserName, from) != 0) warn_f_flag = j; break; case 'F': /* set full name */ CHECK_AGAINST_OPMODE(j); FullName = newstr(optarg); break; case 'G': /* relay (gateway) submission */ /* already set */ CHECK_AGAINST_OPMODE(j); break; case 'h': /* hop count */ CHECK_AGAINST_OPMODE(j); BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep, 10); (void) sm_snprintf(buf, sizeof(buf), "%d", BlankEnvelope.e_hopcount); macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf); if (*ep) { usrerr("Bad hop count (%s)", optarg); ExitStat = EX_USAGE; } break; case 'L': /* program label */ /* already set */ break; case 'n': /* don't alias */ CHECK_AGAINST_OPMODE(j); NoAlias = true; break; case 'N': /* delivery status notifications */ CHECK_AGAINST_OPMODE(j); DefaultNotify |= QHASNOTIFY; macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{dsn_notify}"), optarg); if (sm_strcasecmp(optarg, "never") == 0) break; for (p = optarg; p != NULL; optarg = p) { p = strchr(p, ','); if (p != NULL) *p++ = '\0'; if (sm_strcasecmp(optarg, "success") == 0) DefaultNotify |= QPINGONSUCCESS; else if (sm_strcasecmp(optarg, "failure") == 0) DefaultNotify |= QPINGONFAILURE; else if (sm_strcasecmp(optarg, "delay") == 0) DefaultNotify |= QPINGONDELAY; else { usrerr("Invalid -N argument"); ExitStat = EX_USAGE; } } break; case 'o': /* set option */ setoption(*optarg, optarg + 1, false, true, &BlankEnvelope); break; case 'O': /* set option (long form) */ setoption(' ', optarg, false, true, &BlankEnvelope); break; case 'p': /* set protocol */ CHECK_AGAINST_OPMODE(j); p = strchr(optarg, ':'); if (p != NULL) { *p++ = '\0'; if (*p != '\0') { i = strlen(p) + 1; ep = sm_malloc_x(i); cleanstrcpy(ep, p, i); macdefine(&BlankEnvelope.e_macro, A_HEAP, 's', ep); } } if (*optarg != '\0') { i = strlen(optarg) + 1; ep = sm_malloc_x(i); cleanstrcpy(ep, optarg, i); macdefine(&BlankEnvelope.e_macro, A_HEAP, 'r', ep); } break; case 'Q': /* change quarantining on queued items */ /* sanity check */ if (OpMode != MD_DELIVER && OpMode != MD_QUEUERUN) { usrerr("Can not use -Q with -b%c", OpMode); ExitStat = EX_USAGE; break; } if (OpMode == MD_DELIVER) set_op_mode(MD_QUEUERUN); FullName = NULL; quarantining = newstr(optarg); break; case 'q': /* run queue files at intervals */ /* sanity check */ if (OpMode != MD_DELIVER && OpMode != MD_DAEMON && OpMode != MD_FGDAEMON && OpMode != MD_PRINT && OpMode != MD_PRINTNQE && OpMode != MD_QUEUERUN) { usrerr("Can not use -q with -b%c", OpMode); ExitStat = EX_USAGE; break; } /* don't override -bd, -bD or -bp */ if (OpMode == MD_DELIVER) set_op_mode(MD_QUEUERUN); FullName = NULL; negate = optarg[0] == '!'; if (negate) { /* negate meaning of pattern match */ optarg++; /* skip '!' for next switch */ } switch (optarg[0]) { case 'G': /* Limit by queue group name */ if (negate) { usrerr("Can not use -q!G"); ExitStat = EX_USAGE; break; } if (queuegroup != NULL) { usrerr("Can not use multiple -qG options"); ExitStat = EX_USAGE; break; } queuegroup = newstr(&optarg[1]); break; case 'I': /* Limit by ID */ new = (QUEUE_CHAR *) xalloc(sizeof(*new)); new->queue_match = newstr(&optarg[1]); new->queue_negate = negate; new->queue_next = QueueLimitId; QueueLimitId = new; break; case 'R': /* Limit by recipient */ new = (QUEUE_CHAR *) xalloc(sizeof(*new)); new->queue_match = newstr(&optarg[1]); new->queue_negate = negate; new->queue_next = QueueLimitRecipient; QueueLimitRecipient = new; break; case 'S': /* Limit by sender */ new = (QUEUE_CHAR *) xalloc(sizeof(*new)); new->queue_match = newstr(&optarg[1]); new->queue_negate = negate; new->queue_next = QueueLimitSender; QueueLimitSender = new; break; case 'f': /* foreground queue run */ foregroundqueue = true; break; case 'Q': /* Limit by quarantine message */ if (optarg[1] != '\0') { new = (QUEUE_CHAR *) xalloc(sizeof(*new)); new->queue_match = newstr(&optarg[1]); new->queue_negate = negate; new->queue_next = QueueLimitQuarantine; QueueLimitQuarantine = new; } QueueMode = QM_QUARANTINE; break; case 'L': /* act on lost items */ QueueMode = QM_LOST; break; case 'p': /* Persistent queue */ queuepersistent = true; if (QueueIntvl == 0) QueueIntvl = 1; if (optarg[1] == '\0') break; ++optarg; /* FALLTHROUGH */ default: i = Errors; QueueIntvl = convtime(optarg, 'm'); if (QueueIntvl < 0) { usrerr("Invalid -q value"); ExitStat = EX_USAGE; } /* check for bad conversion */ if (i < Errors) ExitStat = EX_USAGE; break; } break; case 'R': /* DSN RET: what to return */ CHECK_AGAINST_OPMODE(j); if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags)) { usrerr("Duplicate -R flag"); ExitStat = EX_USAGE; break; } BlankEnvelope.e_flags |= EF_RET_PARAM; if (sm_strcasecmp(optarg, "hdrs") == 0) BlankEnvelope.e_flags |= EF_NO_BODY_RETN; else if (sm_strcasecmp(optarg, "full") != 0) { usrerr("Invalid -R value"); ExitStat = EX_USAGE; } macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{dsn_ret}"), optarg); break; case 't': /* read recipients from message */ CHECK_AGAINST_OPMODE(j); GrabTo = true; break; case 'V': /* DSN ENVID: set "original" envelope id */ CHECK_AGAINST_OPMODE(j); if (!xtextok(optarg)) { usrerr("Invalid syntax in -V flag"); ExitStat = EX_USAGE; } else { BlankEnvelope.e_envid = newstr(optarg); macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{dsn_envid}"), optarg); } break; case 'X': /* traffic log file */ dp = drop_privileges(true); setstat(dp); if (stat(optarg, &traf_st) == 0 && S_ISFIFO(traf_st.st_mode)) TrafficLogFile = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, optarg, SM_IO_WRONLY, NULL); else TrafficLogFile = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, optarg, SM_IO_APPEND, NULL); if (TrafficLogFile == NULL) { syserr("cannot open %s", optarg); ExitStat = EX_CANTCREAT; break; } (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT, NULL, SM_IO_LBF, 0); break; /* compatibility flags */ case 'c': /* connect to non-local mailers */ case 'i': /* don't let dot stop me */ case 'm': /* send to me too */ case 'T': /* set timeout interval */ case 'v': /* give blow-by-blow description */ setoption(j, "T", false, true, &BlankEnvelope); break; case 'e': /* error message disposition */ case 'M': /* define macro */ setoption(j, optarg, false, true, &BlankEnvelope); break; case 's': /* save From lines in headers */ setoption('f', "T", false, true, &BlankEnvelope); break; #ifdef DBM case 'I': /* initialize alias DBM file */ set_op_mode(MD_INITALIAS); break; #endif /* DBM */ #if defined(__osf__) || defined(_AIX3) case 'x': /* random flag that OSF/1 & AIX mailx passes */ break; #endif /* defined(__osf__) || defined(_AIX3) */ #if defined(sony_news) case 'E': case 'J': /* ignore flags for Japanese code conversion implemented on Sony NEWS */ break; #endif /* defined(sony_news) */ default: finis(true, true, EX_USAGE); /* NOTREACHED */ break; } } /* if we've had errors so far, exit now */ if ((ExitStat != EX_OK && OpMode != MD_TEST && OpMode != MD_CHECKCONFIG) || ExitStat == EX_OSERR) { finis(false, true, ExitStat); /* NOTREACHED */ } if (bitset(SUBMIT_MTA, SubmitMode)) { /* If set daemon_flags on command line, don't reset it */ if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL) macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{daemon_flags}"), "CC f"); } else if (OpMode == MD_DELIVER || OpMode == MD_SMTP) { SubmitMode = SUBMIT_MSA; /* If set daemon_flags on command line, don't reset it */ if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL) macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{daemon_flags}"), "c u"); } /* ** Do basic initialization. ** Read system control file. ** Extract special fields for local use. */ #if XDEBUG checkfd012("before readcf"); #endif /* XDEBUG */ vendor_pre_defaults(&BlankEnvelope); readcf(getcfname(OpMode, SubmitMode, cftype, conffile), safecf, &BlankEnvelope); #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) ConfigFileRead = true; #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */ vendor_post_defaults(&BlankEnvelope); /* now we can complain about missing fds */ if (MissingFds != 0 && LogLevel > 8) { char mbuf[MAXLINE]; mbuf[0] = '\0'; if (bitset(1 << STDIN_FILENO, MissingFds)) (void) sm_strlcat(mbuf, ", stdin", sizeof(mbuf)); if (bitset(1 << STDOUT_FILENO, MissingFds)) (void) sm_strlcat(mbuf, ", stdout", sizeof(mbuf)); if (bitset(1 << STDERR_FILENO, MissingFds)) (void) sm_strlcat(mbuf, ", stderr", sizeof(mbuf)); /* Notice: fill_errno is from high above: fill_fd() */ sm_syslog(LOG_WARNING, NOQID, "File descriptors missing on startup: %s; %s", &mbuf[2], sm_errstring(fill_errno)); } /* Remove the ability for a normal user to send signals */ if (RealUid != 0 && RealUid != geteuid()) { uid_t new_uid = geteuid(); #if HASSETREUID /* ** Since we can differentiate between uid and euid, ** make the uid a different user so the real user ** can't send signals. However, it doesn't need to be ** root (euid has root). */ if (new_uid == 0) new_uid = DefUid; if (tTd(47, 5)) sm_dprintf("Changing real uid to %d\n", (int) new_uid); if (setreuid(new_uid, geteuid()) < 0) { syserr("main: setreuid(%d, %d) failed", (int) new_uid, (int) geteuid()); finis(false, true, EX_OSERR); /* NOTREACHED */ } if (tTd(47, 10)) sm_dprintf("Now running as e/ruid %d:%d\n", (int) geteuid(), (int) getuid()); #else /* HASSETREUID */ /* ** Have to change both effective and real so need to ** change them both to effective to keep privs. */ if (tTd(47, 5)) sm_dprintf("Changing uid to %d\n", (int) new_uid); if (setuid(new_uid) < 0) { syserr("main: setuid(%d) failed", (int) new_uid); finis(false, true, EX_OSERR); /* NOTREACHED */ } if (tTd(47, 10)) sm_dprintf("Now running as e/ruid %d:%d\n", (int) geteuid(), (int) getuid()); #endif /* HASSETREUID */ } #if NAMED_BIND if (FallbackMX != NULL) (void) getfallbackmxrr(FallbackMX); #endif /* NAMED_BIND */ if (SuperSafe == SAFE_INTERACTIVE && !SM_IS_INTERACTIVE(CurEnv->e_sendmode)) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n"); } if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)) { usrerr("Mail submission program cannot be used as daemon"); finis(false, true, EX_USAGE); } if (OpMode == MD_DELIVER || OpMode == MD_SMTP || OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP || OpMode == MD_DAEMON || OpMode == MD_FGDAEMON) makeworkgroups(); /* set up the basic signal handlers */ if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN) (void) sm_signal(SIGINT, intsig); (void) sm_signal(SIGTERM, intsig); /* Enforce use of local time (null string overrides this) */ if (TimeZoneSpec == NULL) unsetenv("TZ"); else if (TimeZoneSpec[0] != '\0') sm_setuserenv("TZ", TimeZoneSpec); else sm_setuserenv("TZ", NULL); tzset(); /* initialize mailbox database */ i = sm_mbdb_initialize(Mbdb); if (i != EX_OK) { usrerr("Can't initialize mailbox database \"%s\": %s", Mbdb, sm_strexit(i)); ExitStat = i; } /* avoid denial-of-service attacks */ resetlimits(); if (OpMode == MD_TEST) { /* can't be done after readcf if RunAs* is used */ dp = drop_privileges(true); if (dp != EX_OK) { finis(false, true, dp); /* NOTREACHED */ } } else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON) { /* drop privileges -- daemon mode done after socket/bind */ dp = drop_privileges(false); setstat(dp); if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0)) { usrerr("Mail submission program must have RunAsUser set to non root user"); finis(false, true, EX_CONFIG); /* NOTREACHED */ } } #if NAMED_BIND _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT]; _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT]; #endif /* NAMED_BIND */ /* ** Find our real host name for future logging. */ authinfo = getauthinfo(STDIN_FILENO, &forged); macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo); /* suppress error printing if errors mailed back or whatever */ if (BlankEnvelope.e_errormode != EM_PRINT) HoldErrs = true; /* set up the $=m class now, after .cf has a chance to redefine $m */ expand("\201m", jbuf, sizeof(jbuf), &BlankEnvelope); if (jbuf[0] != '\0') setclass('m', jbuf); /* probe interfaces and locate any additional names */ if (DontProbeInterfaces != DPI_PROBENONE) load_if_names(); if (tTd(0, 10)) { char pidpath[MAXPATHLEN]; /* Now we know which .cf file we use */ sm_dprintf(" Conf file:\t%s (selected)\n", getcfname(OpMode, SubmitMode, cftype, conffile)); expand(PidFile, pidpath, sizeof(pidpath), &BlankEnvelope); sm_dprintf(" Pid file:\t%s (selected)\n", pidpath); } if (tTd(0, 1)) { sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============"); sm_dprintf("\n (short domain name) $w = "); xputs(sm_debug_file(), macvalue('w', &BlankEnvelope)); sm_dprintf("\n (canonical domain name) $j = "); xputs(sm_debug_file(), macvalue('j', &BlankEnvelope)); sm_dprintf("\n (subdomain name) $m = "); xputs(sm_debug_file(), macvalue('m', &BlankEnvelope)); sm_dprintf("\n (node name) $k = "); xputs(sm_debug_file(), macvalue('k', &BlankEnvelope)); sm_dprintf("\n========================================================\n\n"); } /* ** Do more command line checking -- these are things that ** have to modify the results of reading the config file. */ /* process authorization warnings from command line */ if (warn_C_flag) auth_warning(&BlankEnvelope, "Processed by %s with -C %s", RealUserName, conffile); if (Warn_Q_option && !wordinclass(RealUserName, 't')) auth_warning(&BlankEnvelope, "Processed from queue %s", QueueDir); if (sysloglabel != NULL && !wordinclass(RealUserName, 't') && RealUid != 0 && RealUid != TrustedUid && LogLevel > 1) sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label", (int) RealUid); /* check body type for legality */ i = check_bodytype(BlankEnvelope.e_bodytype); if (i == BODYTYPE_ILLEGAL) { usrerr("Illegal body type %s", BlankEnvelope.e_bodytype); BlankEnvelope.e_bodytype = NULL; } else if (i != BODYTYPE_NONE) SevenBitInput = (i == BODYTYPE_7BIT); /* tweak default DSN notifications */ if (DefaultNotify == 0) DefaultNotify = QPINGONFAILURE|QPINGONDELAY; /* check for sane configuration level */ if (ConfigLevel > MAXCONFIGLEVEL) { syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)", ConfigLevel, Version, MAXCONFIGLEVEL); } /* need MCI cache to have persistence */ if (HostStatDir != NULL && MaxMciCache == 0) { HostStatDir = NULL; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n"); } /* need HostStatusDir in order to have SingleThreadDelivery */ if (SingleThreadDelivery && HostStatDir == NULL) { SingleThreadDelivery = false; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: HostStatusDirectory required for SingleThreadDelivery\n"); } #if _FFR_MEMSTAT j = sm_memstat_open(); if (j < 0 && (RefuseLowMem > 0 || QueueLowMem > 0) && LogLevel > 4) { sm_syslog(LOG_WARNING, NOQID, "cannot get memory statistics, settings ignored, error=%d" , j); } #endif /* _FFR_MEMSTAT */ /* check for permissions */ if (RealUid != 0 && RealUid != TrustedUid) { char *action = NULL; switch (OpMode) { case MD_QUEUERUN: if (quarantining != NULL) action = "quarantine jobs"; else { /* Normal users can do a single queue run */ if (QueueIntvl == 0) break; } /* but not persistent queue runners */ if (action == NULL) action = "start a queue runner daemon"; /* FALLTHROUGH */ case MD_PURGESTAT: if (action == NULL) action = "purge host status"; /* FALLTHROUGH */ case MD_DAEMON: case MD_FGDAEMON: if (action == NULL) action = "run daemon"; if (tTd(65, 1)) sm_dprintf("Deny user %d attempt to %s\n", (int) RealUid, action); if (LogLevel > 1) sm_syslog(LOG_ALERT, NOQID, "user %d attempted to %s", (int) RealUid, action); HoldErrs = false; usrerr("Permission denied (real uid not trusted)"); finis(false, true, EX_USAGE); /* NOTREACHED */ break; case MD_VERIFY: if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags)) { /* ** If -bv and RestrictExpand, ** drop privs to prevent normal ** users from reading private ** aliases/forwards/:include:s */ if (tTd(65, 1)) sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n", (int) RealUid); dp = drop_privileges(true); /* Fake address safety */ if (tTd(65, 1)) sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n"); setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail); if (dp != EX_OK) { if (tTd(65, 1)) sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n", (int) RealUid); CurEnv->e_id = NULL; finis(true, true, dp); /* NOTREACHED */ } } break; case MD_TEST: case MD_CHECKCONFIG: case MD_PRINT: case MD_PRINTNQE: case MD_FREEZE: case MD_HOSTSTAT: /* Nothing special to check */ break; case MD_INITALIAS: if (!wordinclass(RealUserName, 't')) { if (tTd(65, 1)) sm_dprintf("Deny user %d attempt to rebuild the alias map\n", (int) RealUid); if (LogLevel > 1) sm_syslog(LOG_ALERT, NOQID, "user %d attempted to rebuild the alias map", (int) RealUid); HoldErrs = false; usrerr("Permission denied (real uid not trusted)"); finis(false, true, EX_USAGE); /* NOTREACHED */ } if (UseMSP) { HoldErrs = false; usrerr("User %d cannot rebuild aliases in mail submission program", (int) RealUid); finis(false, true, EX_USAGE); /* NOTREACHED */ } /* FALLTHROUGH */ default: if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) && Verbose != 0) { /* ** If -v and RestrictExpand, reset ** Verbose to prevent normal users ** from seeing the expansion of ** aliases/forwards/:include:s */ if (tTd(65, 1)) sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n", (int) RealUid); Verbose = 0; } break; } } if (MeToo) BlankEnvelope.e_flags |= EF_METOO; switch (OpMode) { case MD_TEST: /* don't have persistent host status in test mode */ HostStatDir = NULL; /* FALLTHROUGH */ case MD_CHECKCONFIG: if (Verbose == 0) Verbose = 2; BlankEnvelope.e_errormode = EM_PRINT; HoldErrs = false; break; case MD_VERIFY: BlankEnvelope.e_errormode = EM_PRINT; HoldErrs = false; /* arrange to exit cleanly on hangup signal */ if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL) (void) sm_signal(SIGHUP, intsig); if (geteuid() != 0) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Notice: -bv may give misleading output for non-privileged user\n"); break; case MD_FGDAEMON: run_in_foreground = true; set_op_mode(MD_DAEMON); /* FALLTHROUGH */ case MD_DAEMON: vendor_daemon_setup(&BlankEnvelope); /* remove things that don't make sense in daemon mode */ FullName = NULL; GrabTo = false; /* arrange to restart on hangup signal */ if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/') sm_syslog(LOG_WARNING, NOQID, "daemon invoked without full pathname; kill -1 won't work"); break; case MD_INITALIAS: Verbose = 2; BlankEnvelope.e_errormode = EM_PRINT; HoldErrs = false; /* FALLTHROUGH */ default: /* arrange to exit cleanly on hangup signal */ if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL) (void) sm_signal(SIGHUP, intsig); break; } /* special considerations for FullName */ if (FullName != NULL) { char *full = NULL; /* full names can't have newlines */ if (strchr(FullName, '\n') != NULL) { full = newstr(denlstring(FullName, true, true)); FullName = full; } /* check for characters that may have to be quoted */ if (!rfc822_string(FullName)) { /* ** Quote a full name with special characters ** as a comment so crackaddr() doesn't destroy ** the name portion of the address. */ FullName = addquotes(FullName, NULL); if (full != NULL) sm_free(full); /* XXX */ } } /* do heuristic mode adjustment */ if (Verbose) { /* turn off noconnect option */ setoption('c', "F", true, false, &BlankEnvelope); /* turn on interactive delivery */ setoption('d', "", true, false, &BlankEnvelope); } #ifdef VENDOR_CODE /* check for vendor mismatch */ if (VendorCode != VENDOR_CODE) { message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s", getvendor(VENDOR_CODE), getvendor(VendorCode)); } #endif /* VENDOR_CODE */ /* check for out of date configuration level */ if (ConfigLevel < MAXCONFIGLEVEL) { message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d", Version, MAXCONFIGLEVEL, ConfigLevel); } if (ConfigLevel < 3) UseErrorsTo = true; /* set options that were previous macros */ if (SmtpGreeting == NULL) { if (ConfigLevel < 7 && (p = macvalue('e', &BlankEnvelope)) != NULL) SmtpGreeting = newstr(p); else SmtpGreeting = "\201j Sendmail \201v ready at \201b"; } if (UnixFromLine == NULL) { if (ConfigLevel < 7 && (p = macvalue('l', &BlankEnvelope)) != NULL) UnixFromLine = newstr(p); else UnixFromLine = "From \201g \201d"; } SmtpError[0] = '\0'; /* our name for SMTP codes */ expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope); if (jbuf[0] == '\0') PSTRSET(MyHostName, "localhost"); else PSTRSET(MyHostName, jbuf); if (strchr(MyHostName, '.') == NULL) message("WARNING: local host name (%s) is not qualified; see cf/README: WHO AM I?", MyHostName); /* make certain that this name is part of the $=w class */ setclass('w', MyHostName); /* fill in the structure of the *default* queue */ st = stab("mqueue", ST_QUEUE, ST_FIND); if (st == NULL) syserr("No default queue (mqueue) defined"); else set_def_queueval(st->s_quegrp, true); /* the indices of built-in mailers */ st = stab("local", ST_MAILER, ST_FIND); if (st != NULL) LocalMailer = st->s_mailer; else if (OpMode != MD_TEST || !warn_C_flag) syserr("No local mailer defined"); st = stab("prog", ST_MAILER, ST_FIND); if (st == NULL) syserr("No prog mailer defined"); else { ProgMailer = st->s_mailer; clrbitn(M_MUSER, ProgMailer->m_flags); } st = stab("*file*", ST_MAILER, ST_FIND); if (st == NULL) syserr("No *file* mailer defined"); else { FileMailer = st->s_mailer; clrbitn(M_MUSER, FileMailer->m_flags); } st = stab("*include*", ST_MAILER, ST_FIND); if (st == NULL) syserr("No *include* mailer defined"); else InclMailer = st->s_mailer; if (ConfigLevel < 6) { /* heuristic tweaking of local mailer for back compat */ if (LocalMailer != NULL) { setbitn(M_ALIASABLE, LocalMailer->m_flags); setbitn(M_HASPWENT, LocalMailer->m_flags); setbitn(M_TRYRULESET5, LocalMailer->m_flags); setbitn(M_CHECKINCLUDE, LocalMailer->m_flags); setbitn(M_CHECKPROG, LocalMailer->m_flags); setbitn(M_CHECKFILE, LocalMailer->m_flags); setbitn(M_CHECKUDB, LocalMailer->m_flags); } if (ProgMailer != NULL) setbitn(M_RUNASRCPT, ProgMailer->m_flags); if (FileMailer != NULL) setbitn(M_RUNASRCPT, FileMailer->m_flags); } if (ConfigLevel < 7) { if (LocalMailer != NULL) setbitn(M_VRFY250, LocalMailer->m_flags); if (ProgMailer != NULL) setbitn(M_VRFY250, ProgMailer->m_flags); if (FileMailer != NULL) setbitn(M_VRFY250, FileMailer->m_flags); } /* MIME Content-Types that cannot be transfer encoded */ setclass('n', "multipart/signed"); /* MIME message/xxx subtypes that can be treated as messages */ setclass('s', "rfc822"); /* MIME Content-Transfer-Encodings that can be encoded */ setclass('e', "7bit"); setclass('e', "8bit"); setclass('e', "binary"); #ifdef USE_B_CLASS /* MIME Content-Types that should be treated as binary */ setclass('b', "image"); setclass('b', "audio"); setclass('b', "video"); setclass('b', "application/octet-stream"); #endif /* USE_B_CLASS */ /* MIME headers which have fields to check for overflow */ setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition"); setclass(macid("{checkMIMEFieldHeaders}"), "content-type"); /* MIME headers to check for length overflow */ setclass(macid("{checkMIMETextHeaders}"), "content-description"); /* MIME headers to check for overflow and rebalance */ setclass(macid("{checkMIMEHeaders}"), "content-disposition"); setclass(macid("{checkMIMEHeaders}"), "content-id"); setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding"); setclass(macid("{checkMIMEHeaders}"), "content-type"); setclass(macid("{checkMIMEHeaders}"), "mime-version"); /* Macros to save in the queue file -- don't remove any */ setclass(macid("{persistentMacros}"), "r"); setclass(macid("{persistentMacros}"), "s"); setclass(macid("{persistentMacros}"), "_"); setclass(macid("{persistentMacros}"), "{if_addr}"); setclass(macid("{persistentMacros}"), "{daemon_flags}"); /* operate in queue directory */ if (QueueDir == NULL || *QueueDir == '\0') { if (OpMode != MD_TEST) { syserr("QueueDirectory (Q) option must be set"); ExitStat = EX_CONFIG; } } else { if (OpMode != MD_TEST) setup_queues(OpMode == MD_DAEMON); } /* check host status directory for validity */ if (HostStatDir != NULL && !path_is_dir(HostStatDir, false)) { /* cannot use this value */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Cannot use HostStatusDirectory = %s: %s\n", HostStatDir, sm_errstring(errno)); HostStatDir = NULL; } if (OpMode == MD_QUEUERUN && RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags)) { struct stat stbuf; /* check to see if we own the queue directory */ if (stat(".", &stbuf) < 0) syserr("main: cannot stat %s", QueueDir); if (stbuf.st_uid != RealUid) { /* nope, really a botch */ HoldErrs = false; usrerr("You do not have permission to process the queue"); finis(false, true, EX_NOPERM); /* NOTREACHED */ } } #if MILTER /* sanity checks on milter filters */ if (OpMode == MD_DAEMON || OpMode == MD_SMTP) { milter_config(InputFilterList, InputFilters, MAXFILTERS); setup_daemon_milters(); } #endif /* MILTER */ /* Convert queuegroup string to qgrp number */ if (queuegroup != NULL) { qgrp = name2qid(queuegroup); if (qgrp == NOQGRP) { HoldErrs = false; usrerr("Queue group %s unknown", queuegroup); finis(false, true, ExitStat); /* NOTREACHED */ } } /* if checking config or have had errors so far, exit now */ if (OpMode == MD_CHECKCONFIG || (ExitStat != EX_OK && OpMode != MD_TEST)) { finis(false, true, ExitStat); /* NOTREACHED */ } #if SASL /* sendmail specific SASL initialization */ sm_sasl_init(); #endif /* SASL */ #if XDEBUG checkfd012("before main() initmaps"); #endif /* XDEBUG */ /* ** Do operation-mode-dependent initialization. */ switch (OpMode) { case MD_PRINT: /* print the queue */ HoldErrs = false; (void) dropenvelope(&BlankEnvelope, true, false); (void) sm_signal(SIGPIPE, sigpipe); if (qgrp != NOQGRP) { int j; /* Selecting a particular queue group to run */ for (j = 0; j < Queue[qgrp]->qg_numqueues; j++) { if (StopRequest) stop_sendmail(); (void) print_single_queue(qgrp, j); } finis(false, true, EX_OK); /* NOTREACHED */ } printqueue(); finis(false, true, EX_OK); /* NOTREACHED */ break; case MD_PRINTNQE: /* print number of entries in queue */ (void) dropenvelope(&BlankEnvelope, true, false); (void) sm_signal(SIGPIPE, sigpipe); printnqe(smioout, NULL); finis(false, true, EX_OK); /* NOTREACHED */ break; case MD_QUEUERUN: /* only handle quarantining here */ if (quarantining == NULL) break; if (QueueMode != QM_QUARANTINE && QueueMode != QM_NORMAL) { HoldErrs = false; usrerr("Can not use -Q with -q%c", QueueMode); ExitStat = EX_USAGE; finis(false, true, ExitStat); /* NOTREACHED */ } quarantine_queue(quarantining, qgrp); finis(false, true, EX_OK); break; case MD_HOSTSTAT: (void) sm_signal(SIGPIPE, sigpipe); (void) mci_traverse_persistent(mci_print_persistent, NULL); finis(false, true, EX_OK); /* NOTREACHED */ break; case MD_PURGESTAT: (void) mci_traverse_persistent(mci_purge_persistent, NULL); finis(false, true, EX_OK); /* NOTREACHED */ break; case MD_INITALIAS: /* initialize maps */ initmaps(); finis(false, true, ExitStat); /* NOTREACHED */ break; case MD_SMTP: case MD_DAEMON: /* reset DSN parameters */ DefaultNotify = QPINGONFAILURE|QPINGONDELAY; macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{dsn_notify}"), NULL); BlankEnvelope.e_envid = NULL; macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{dsn_envid}"), NULL); BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN); macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{dsn_ret}"), NULL); /* don't open maps for daemon -- done below in child */ break; } if (tTd(0, 15)) { /* print configuration table (or at least part of it) */ if (tTd(0, 90)) printrules(); for (i = 0; i < MAXMAILERS; i++) { if (Mailer[i] != NULL) printmailer(sm_debug_file(), Mailer[i]); } } /* ** Switch to the main envelope. */ CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope, sm_rpool_new_x(NULL)); MainEnvelope.e_flags = BlankEnvelope.e_flags; /* ** If test mode, read addresses from stdin and process. */ if (OpMode == MD_TEST) { if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL))) Verbose = 2; if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n"); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Enter
\n"); } macdefine(&(MainEnvelope.e_macro), A_PERM, macid("{addr_type}"), "e r"); for (;;) { SM_TRY { (void) sm_signal(SIGINT, intindebug); (void) sm_releasesignal(SIGINT); if (Verbose == 2) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "> "); (void) sm_io_flush(smioout, SM_TIME_DEFAULT); if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf, - sizeof(buf)) == NULL) + sizeof(buf)) < 0) testmodeline("/quit", &MainEnvelope); p = strchr(buf, '\n'); if (p != NULL) *p = '\0'; if (Verbose < 2) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "> %s\n", buf); testmodeline(buf, &MainEnvelope); } SM_EXCEPT(exc, "[!F]*") { /* ** 8.10 just prints \n on interrupt. ** I'm printing the exception here in case ** sendmail is extended to raise additional ** exceptions in this context. */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n"); sm_exc_print(exc, smioout); } SM_END_TRY } } #if STARTTLS tls_ok = true; if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER || OpMode == MD_ARPAFTP) { /* check whether STARTTLS is turned off for the client */ if (chkclientmodifiers(D_NOTLS)) tls_ok = false; } else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON || OpMode == MD_SMTP) { /* check whether STARTTLS is turned off */ if (chkdaemonmodifiers(D_NOTLS) && chkclientmodifiers(D_NOTLS)) tls_ok = false; } else /* other modes don't need STARTTLS */ tls_ok = false; if (tls_ok) { /* basic TLS initialization */ - tls_ok = init_tls_library(); + tls_ok = init_tls_library(FipsMode); + if (!tls_ok && FipsMode) + { + (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, + "ERROR: FIPSMode failed to initialize\n"); + exit(EX_USAGE); + } } if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER)) { /* disable TLS for client */ setclttls(false); } #endif /* STARTTLS */ /* ** If collecting stuff from the queue, go start doing that. */ if (OpMode == MD_QUEUERUN && QueueIntvl == 0) { pid_t pid = -1; #if STARTTLS /* init TLS for client, ignore result for now */ (void) initclttls(tls_ok); #endif /* STARTTLS */ /* ** The parent process of the caller of runqueue() needs ** to stay around for a possible SIGTERM. The SIGTERM will ** tell this process that all of the queue runners children ** need to be sent SIGTERM as well. At the same time, we ** want to return control to the command line. So we do an ** extra fork(). */ if (Verbose || foregroundqueue || (pid = fork()) <= 0) { /* ** If the fork() failed we should still try to do ** the queue run. If it succeeded then the child ** is going to start the run and wait for all ** of the children to finish. */ if (pid == 0) { /* Reset global flags */ RestartRequest = NULL; ShutdownRequest = NULL; PendingSignal = 0; /* disconnect from terminal */ disconnect(2, CurEnv); } CurrentPid = getpid(); if (qgrp != NOQGRP) { int rwgflags = RWG_NONE; /* ** To run a specific queue group mark it to ** be run, select the work group it's in and ** increment the work counter. */ for (i = 0; i < NumQueue && Queue[i] != NULL; i++) Queue[i]->qg_nextrun = (time_t) -1; Queue[qgrp]->qg_nextrun = 0; if (Verbose) rwgflags |= RWG_VERBOSE; if (queuepersistent) rwgflags |= RWG_PERSISTENT; rwgflags |= RWG_FORCE; (void) run_work_group(Queue[qgrp]->qg_wgrp, rwgflags); } else (void) runqueue(false, Verbose, queuepersistent, true); /* set the title to make it easier to find */ sm_setproctitle(true, CurEnv, "Queue control"); (void) sm_signal(SIGCHLD, SIG_DFL); while (CurChildren > 0) { int status; pid_t ret; errno = 0; while ((ret = sm_wait(&status)) <= 0) { if (errno == ECHILD) { /* ** Oops... something got messed ** up really bad. Waiting for ** non-existent children ** shouldn't happen. Let's get ** out of here. */ CurChildren = 0; break; } continue; } /* something is really really wrong */ if (errno == ECHILD) { sm_syslog(LOG_ERR, NOQID, "queue control process: lost all children: wait returned ECHILD"); break; } /* Only drop when a child gives status */ if (WIFSTOPPED(status)) continue; proc_list_drop(ret, status, NULL); } } finis(true, true, ExitStat); /* NOTREACHED */ } # if SASL if (OpMode == MD_SMTP || OpMode == MD_DAEMON) { /* check whether AUTH is turned off for the server */ if (!chkdaemonmodifiers(D_NOAUTH) && (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK) syserr("!sasl_server_init failed! [%s]", sasl_errstring(i, NULL, NULL)); } # endif /* SASL */ if (OpMode == MD_SMTP) { proc_list_add(CurrentPid, "Sendmail SMTP Agent", PROC_DAEMON, 0, -1, NULL); /* clean up background delivery children */ (void) sm_signal(SIGCHLD, reapchild); } /* ** If a daemon, wait for a request. ** getrequests will always return in a child. ** If we should also be processing the queue, start ** doing it in background. ** We check for any errors that might have happened ** during startup. */ if (OpMode == MD_DAEMON || QueueIntvl > 0) { char dtype[200]; /* avoid cleanup in finis(), DaemonPid will be set below */ DaemonPid = 0; if (!run_in_foreground && !tTd(99, 100)) { /* put us in background */ i = fork(); if (i < 0) syserr("daemon: cannot fork"); if (i != 0) { finis(false, true, EX_OK); /* NOTREACHED */ } /* ** Initialize exception stack and default exception ** handler for child process. */ /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; CurrentPid = getpid(); sm_exc_newthread(fatal_error); /* disconnect from our controlling tty */ disconnect(2, &MainEnvelope); } dtype[0] = '\0'; if (OpMode == MD_DAEMON) { (void) sm_strlcat(dtype, "+SMTP", sizeof(dtype)); DaemonPid = CurrentPid; } if (QueueIntvl > 0) { (void) sm_strlcat2(dtype, queuepersistent ? "+persistent-queueing@" : "+queueing@", pintvl(QueueIntvl, true), sizeof(dtype)); } if (tTd(0, 1)) (void) sm_strlcat(dtype, "+debugging", sizeof(dtype)); sm_syslog(LOG_INFO, NOQID, "starting daemon (%s): %s", Version, dtype + 1); #if XLA xla_create_file(); #endif /* XLA */ /* save daemon type in a macro for possible PidFile use */ macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{daemon_info}"), dtype + 1); /* save queue interval in a macro for possible PidFile use */ macdefine(&MainEnvelope.e_macro, A_TEMP, macid("{queue_interval}"), pintvl(QueueIntvl, true)); /* workaround: can't seem to release the signal in the parent */ (void) sm_signal(SIGHUP, sighup); (void) sm_releasesignal(SIGHUP); (void) sm_signal(SIGTERM, sigterm); if (QueueIntvl > 0) { #if _FFR_RUNPQG if (qgrp != NOQGRP) { int rwgflags = RWG_NONE; /* ** To run a specific queue group mark it to ** be run, select the work group it's in and ** increment the work counter. */ for (i = 0; i < NumQueue && Queue[i] != NULL; i++) Queue[i]->qg_nextrun = (time_t) -1; Queue[qgrp]->qg_nextrun = 0; if (Verbose) rwgflags |= RWG_VERBOSE; if (queuepersistent) rwgflags |= RWG_PERSISTENT; rwgflags |= RWG_FORCE; (void) run_work_group(Queue[qgrp]->qg_wgrp, rwgflags); } else #endif /* _FFR_RUNPQG */ (void) runqueue(true, false, queuepersistent, true); /* ** If queuepersistent but not in daemon mode then ** we're going to do the queue runner monitoring here. ** If in daemon mode then the monitoring will happen ** elsewhere. */ if (OpMode != MD_DAEMON && queuepersistent) { /* ** Write the pid to file ** XXX Overwrites sendmail.pid */ log_sendmail_pid(&MainEnvelope); /* set the title to make it easier to find */ sm_setproctitle(true, CurEnv, "Queue control"); (void) sm_signal(SIGCHLD, SIG_DFL); while (CurChildren > 0) { int status; pid_t ret; int group; CHECK_RESTART; errno = 0; while ((ret = sm_wait(&status)) <= 0) { /* ** Waiting for non-existent ** children shouldn't happen. ** Let's get out of here if ** it occurs. */ if (errno == ECHILD) { CurChildren = 0; break; } continue; } /* something is really really wrong */ if (errno == ECHILD) { sm_syslog(LOG_ERR, NOQID, "persistent queue runner control process: lost all children: wait returned ECHILD"); break; } if (WIFSTOPPED(status)) continue; /* Probe only on a child status */ proc_list_drop(ret, status, &group); if (WIFSIGNALED(status)) { if (WCOREDUMP(status)) { sm_syslog(LOG_ERR, NOQID, "persistent queue runner=%d core dumped, signal=%d", group, WTERMSIG(status)); /* don't restart this */ mark_work_group_restart( group, -1); continue; } sm_syslog(LOG_ERR, NOQID, "persistent queue runner=%d died, pid=%ld, signal=%d", group, (long) ret, WTERMSIG(status)); } /* ** When debugging active, don't ** restart the persistent queues. ** But do log this as info. */ if (sm_debug_active(&DebugNoPRestart, 1)) { sm_syslog(LOG_DEBUG, NOQID, "persistent queue runner=%d, exited", group); mark_work_group_restart(group, -1); } CHECK_RESTART; } finis(true, true, ExitStat); /* NOTREACHED */ } if (OpMode != MD_DAEMON) { char qtype[200]; /* ** Write the pid to file ** XXX Overwrites sendmail.pid */ log_sendmail_pid(&MainEnvelope); /* set the title to make it easier to find */ qtype[0] = '\0'; (void) sm_strlcpyn(qtype, sizeof(qtype), 4, "Queue runner@", pintvl(QueueIntvl, true), " for ", QueueDir); sm_setproctitle(true, CurEnv, qtype); for (;;) { (void) pause(); CHECK_RESTART; if (doqueuerun()) (void) runqueue(true, false, false, false); } } } (void) dropenvelope(&MainEnvelope, true, false); #if STARTTLS /* init TLS for server, ignore result for now */ (void) initsrvtls(tls_ok); #endif /* STARTTLS */ nextreq: p_flags = getrequests(&MainEnvelope); /* drop privileges */ (void) drop_privileges(false); /* ** Get authentication data ** Set _ macro in BlankEnvelope before calling newenvelope(). */ authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL), &forged); macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo); if (tTd(75, 9)) sm_syslog(LOG_INFO, NOQID, "main: where=after_getauthinfo, RealHostAddr=%s", anynet_ntoa(&RealHostAddr)); /* at this point we are in a child: reset state */ sm_rpool_free(MainEnvelope.e_rpool); (void) newenvelope(&MainEnvelope, &MainEnvelope, sm_rpool_new_x(NULL)); } if (LogLevel > 9) { /* log connection information */ sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo); } /* ** If running SMTP protocol, start collecting and executing ** commands. This will never return. */ if (OpMode == MD_SMTP || OpMode == MD_DAEMON) { char pbuf[20]; /* ** Save some macros for check_* rulesets. */ if (forged) { char ipbuf[103]; (void) sm_snprintf(ipbuf, sizeof(ipbuf), "[%.100s]", anynet_ntoa(&RealHostAddr)); macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{client_name}"), ipbuf); } else macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{client_name}"), RealHostName); macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{client_ptr}"), RealHostName); macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{client_addr}"), anynet_ntoa(&RealHostAddr)); sm_getla(); switch (RealHostAddr.sa.sa_family) { #if NETINET case AF_INET: (void) sm_snprintf(pbuf, sizeof(pbuf), "%d", RealHostAddr.sin.sin_port); break; #endif /* NETINET */ #if NETINET6 case AF_INET6: (void) sm_snprintf(pbuf, sizeof(pbuf), "%d", RealHostAddr.sin6.sin6_port); break; #endif /* NETINET6 */ default: (void) sm_snprintf(pbuf, sizeof(pbuf), "0"); break; } macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{client_port}"), pbuf); if (OpMode == MD_DAEMON) { ENVELOPE *saved_env; /* validate the connection */ HoldErrs = true; saved_env = CurEnv; CurEnv = &BlankEnvelope; nullserver = validate_connection(&RealHostAddr, macvalue(macid("{client_name}"), &BlankEnvelope), &BlankEnvelope); if (bitset(EF_DISCARD, BlankEnvelope.e_flags)) MainEnvelope.e_flags |= EF_DISCARD; CurEnv = saved_env; HoldErrs = false; } else if (p_flags == NULL) { p_flags = (BITMAP256 *) xalloc(sizeof(*p_flags)); clrbitmap(p_flags); } #if STARTTLS if (OpMode == MD_SMTP) (void) initsrvtls(tls_ok); #endif /* STARTTLS */ /* turn off profiling */ SM_PROF(1); smtp(nullserver, *p_flags, &MainEnvelope); if (tTd(93, 100)) { /* turn off profiling */ SM_PROF(0); if (OpMode == MD_DAEMON) goto nextreq; } } sm_rpool_free(MainEnvelope.e_rpool); clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL)); if (OpMode == MD_VERIFY) { set_delivery_mode(SM_VERIFY, &MainEnvelope); PostMasterCopy = NULL; } else { /* interactive -- all errors are global */ MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER; } /* ** Do basic system initialization and set the sender */ initsys(&MainEnvelope); macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0"); macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0"); setsender(from, &MainEnvelope, NULL, '\0', false); if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') && (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) || strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0)) { auth_warning(&MainEnvelope, "%s set sender to %s using -%c", RealUserName, from, warn_f_flag); #if SASL auth = false; #endif /* SASL */ } if (auth) { char *fv; /* set the initial sender for AUTH= to $f@$j */ fv = macvalue('f', &MainEnvelope); if (fv == NULL || *fv == '\0') MainEnvelope.e_auth_param = NULL; else { if (strchr(fv, '@') == NULL) { i = strlen(fv) + strlen(macvalue('j', &MainEnvelope)) + 2; p = sm_malloc_x(i); (void) sm_strlcpyn(p, i, 3, fv, "@", macvalue('j', &MainEnvelope)); } else p = sm_strdup_x(fv); MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool, xtextify(p, "=")); sm_free(p); /* XXX */ } } if (macvalue('s', &MainEnvelope) == NULL) macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName); av = argv + optind; if (*av == NULL && !GrabTo) { MainEnvelope.e_to = NULL; MainEnvelope.e_flags |= EF_GLOBALERRS; HoldErrs = false; SuperSafe = SAFE_NO; usrerr("Recipient names must be specified"); /* collect body for UUCP return */ if (OpMode != MD_VERIFY) collect(InChannel, false, NULL, &MainEnvelope, true); finis(true, true, EX_USAGE); /* NOTREACHED */ } /* ** Scan argv and deliver the message to everyone. */ save_val = LogUsrErrs; LogUsrErrs = true; sendtoargv(av, &MainEnvelope); LogUsrErrs = save_val; /* if we have had errors sofar, arrange a meaningful exit stat */ if (Errors > 0 && ExitStat == EX_OK) ExitStat = EX_USAGE; #if _FFR_FIX_DASHT /* ** If using -t, force not sending to argv recipients, even ** if they are mentioned in the headers. */ if (GrabTo) { ADDRESS *q; for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next) q->q_state = QS_REMOVED; } #endif /* _FFR_FIX_DASHT */ /* ** Read the input mail. */ MainEnvelope.e_to = NULL; if (OpMode != MD_VERIFY || GrabTo) { int savederrors; unsigned long savedflags; /* ** workaround for compiler warning on Irix: ** do not initialize variable in the definition, but ** later on: ** warning(1548): transfer of control bypasses ** initialization of: ** variable "savederrors" (declared at line 2570) ** variable "savedflags" (declared at line 2571) ** goto giveup; */ savederrors = Errors; savedflags = MainEnvelope.e_flags & EF_FATALERRS; MainEnvelope.e_flags |= EF_GLOBALERRS; MainEnvelope.e_flags &= ~EF_FATALERRS; Errors = 0; buffer_errors(); collect(InChannel, false, NULL, &MainEnvelope, true); /* header checks failed */ if (Errors > 0) { giveup: if (!GrabTo) { /* Log who the mail would have gone to */ logundelrcpts(&MainEnvelope, MainEnvelope.e_message, 8, false); } flush_errors(true); finis(true, true, ExitStat); /* NOTREACHED */ return -1; } /* bail out if message too large */ if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags)) { finis(true, true, ExitStat != EX_OK ? ExitStat : EX_DATAERR); /* NOTREACHED */ return -1; } /* set message size */ (void) sm_snprintf(buf, sizeof(buf), "%ld", PRT_NONNEGL(MainEnvelope.e_msgsize)); macdefine(&MainEnvelope.e_macro, A_TEMP, macid("{msg_size}"), buf); Errors = savederrors; MainEnvelope.e_flags |= savedflags; } errno = 0; if (tTd(1, 1)) sm_dprintf("From person = \"%s\"\n", MainEnvelope.e_from.q_paddr); /* Check if quarantining stats should be updated */ if (MainEnvelope.e_quarmsg != NULL) markstats(&MainEnvelope, NULL, STATS_QUARANTINE); /* ** Actually send everything. ** If verifying, just ack. */ if (Errors == 0) { if (!split_by_recipient(&MainEnvelope) && bitset(EF_FATALERRS, MainEnvelope.e_flags)) goto giveup; } /* make sure we deliver at least the first envelope */ i = FastSplit > 0 ? 0 : -1; for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++) { ENVELOPE *next; e->e_from.q_state = QS_SENDER; if (tTd(1, 5)) { sm_dprintf("main[%d]: QS_SENDER ", i); printaddr(sm_debug_file(), &e->e_from, false); } e->e_to = NULL; sm_getla(); GrabTo = false; #if NAMED_BIND _res.retry = TimeOuts.res_retry[RES_TO_FIRST]; _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST]; #endif /* NAMED_BIND */ next = e->e_sibling; e->e_sibling = NULL; /* after FastSplit envelopes: queue up */ sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT); e->e_sibling = next; } /* ** All done. ** Don't send return error message if in VERIFY mode. */ finis(true, true, ExitStat); /* NOTREACHED */ return ExitStat; } /* ** STOP_SENDMAIL -- Stop the running program ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** exits. */ void stop_sendmail() { /* reset uid for process accounting */ endpwent(); (void) setuid(RealUid); exit(EX_OK); } /* ** FINIS -- Clean up and exit. ** ** Parameters: ** drop -- whether or not to drop CurEnv envelope ** cleanup -- call exit() or _exit()? ** exitstat -- exit status to use for exit() call ** ** Returns: ** never ** ** Side Effects: ** exits sendmail */ void finis(drop, cleanup, exitstat) bool drop; bool cleanup; volatile int exitstat; { char pidpath[MAXPATHLEN]; pid_t pid; /* Still want to process new timeouts added below */ sm_clear_events(); (void) sm_releasesignal(SIGALRM); if (tTd(2, 1)) { sm_dprintf("\n====finis: stat %d e_id=%s e_flags=", exitstat, CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id); printenvflags(CurEnv); } if (tTd(2, 9)) printopenfds(false); SM_TRY /* ** Clean up. This might raise E:mta.quickabort */ /* clean up temp files */ CurEnv->e_to = NULL; if (drop) { if (CurEnv->e_id != NULL) { int r; r = dropenvelope(CurEnv, true, false); if (exitstat == EX_OK) exitstat = r; sm_rpool_free(CurEnv->e_rpool); CurEnv->e_rpool = NULL; /* these may have pointed to the rpool */ CurEnv->e_to = NULL; CurEnv->e_message = NULL; CurEnv->e_statmsg = NULL; CurEnv->e_quarmsg = NULL; CurEnv->e_bodytype = NULL; CurEnv->e_id = NULL; CurEnv->e_envid = NULL; CurEnv->e_auth_param = NULL; } else poststats(StatFile); } /* flush any cached connections */ mci_flush(true, NULL); /* close maps belonging to this pid */ closemaps(false); #if USERDB /* close UserDatabase */ _udbx_close(); #endif /* USERDB */ #if SASL stop_sasl_client(); #endif /* SASL */ #if XLA /* clean up extended load average stuff */ xla_all_end(); #endif /* XLA */ SM_FINALLY /* ** And exit. */ if (LogLevel > 78) sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d", (int) CurrentPid); if (exitstat == EX_TEMPFAIL || CurEnv->e_errormode == EM_BERKNET) exitstat = EX_OK; /* XXX clean up queues and related data structures */ cleanup_queues(); pid = getpid(); #if SM_CONF_SHM cleanup_shm(DaemonPid == pid); #endif /* SM_CONF_SHM */ /* close locked pid file */ close_sendmail_pid(); if (DaemonPid == pid || PidFilePid == pid) { /* blow away the pid file */ expand(PidFile, pidpath, sizeof(pidpath), CurEnv); (void) unlink(pidpath); } /* reset uid for process accounting */ endpwent(); sm_mbdb_terminate(); #if _FFR_MEMSTAT (void) sm_memstat_close(); #endif /* _FFR_MEMSTAT */ (void) setuid(RealUid); #if SM_HEAP_CHECK /* dump the heap, if we are checking for memory leaks */ if (sm_debug_active(&SmHeapCheck, 2)) sm_heap_report(smioout, sm_debug_level(&SmHeapCheck) - 1); #endif /* SM_HEAP_CHECK */ if (sm_debug_active(&SmXtrapReport, 1)) sm_dprintf("xtrap count = %d\n", SmXtrapCount); if (cleanup) exit(exitstat); else _exit(exitstat); SM_END_TRY } /* ** INTINDEBUG -- signal handler for SIGINT in -bt mode ** ** Parameters: ** sig -- incoming signal. ** ** Returns: ** none. ** ** Side Effects: ** longjmps back to test mode loop. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ /* Type of an exception generated on SIGINT during address test mode. */ static const SM_EXC_TYPE_T EtypeInterrupt = { SmExcTypeMagic, "S:mta.interrupt", "", sm_etype_printf, "interrupt", }; /* ARGSUSED */ static SIGFUNC_DECL intindebug(sig) int sig; { int save_errno = errno; FIX_SYSV_SIGNAL(sig, intindebug); errno = save_errno; CHECK_CRITICAL(sig); errno = save_errno; sm_exc_raisenew_x(&EtypeInterrupt); errno = save_errno; return SIGFUNC_RETURN; } /* ** SIGTERM -- SIGTERM handler for the daemon ** ** Parameters: ** sig -- signal number. ** ** Returns: ** none. ** ** Side Effects: ** Sets ShutdownRequest which will hopefully trigger ** the daemon to exit. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ /* ARGSUSED */ static SIGFUNC_DECL sigterm(sig) int sig; { int save_errno = errno; FIX_SYSV_SIGNAL(sig, sigterm); ShutdownRequest = "signal"; errno = save_errno; return SIGFUNC_RETURN; } /* ** SIGHUP -- handle a SIGHUP signal ** ** Parameters: ** sig -- incoming signal. ** ** Returns: ** none. ** ** Side Effects: ** Sets RestartRequest which should cause the daemon ** to restart. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ /* ARGSUSED */ static SIGFUNC_DECL sighup(sig) int sig; { int save_errno = errno; FIX_SYSV_SIGNAL(sig, sighup); RestartRequest = "signal"; errno = save_errno; return SIGFUNC_RETURN; } /* ** SIGPIPE -- signal handler for SIGPIPE ** ** Parameters: ** sig -- incoming signal. ** ** Returns: ** none. ** ** Side Effects: ** Sets StopRequest which should cause the mailq/hoststatus ** display to stop. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ /* ARGSUSED */ static SIGFUNC_DECL sigpipe(sig) int sig; { int save_errno = errno; FIX_SYSV_SIGNAL(sig, sigpipe); StopRequest = true; errno = save_errno; return SIGFUNC_RETURN; } /* ** INTSIG -- clean up on interrupt ** ** This just arranges to exit. It pessimizes in that it ** may resend a message. ** ** Parameters: ** sig -- incoming signal. ** ** Returns: ** none. ** ** Side Effects: ** Unlocks the current job. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ /* ARGSUSED */ SIGFUNC_DECL intsig(sig) int sig; { bool drop = false; int save_errno = errno; FIX_SYSV_SIGNAL(sig, intsig); errno = save_errno; CHECK_CRITICAL(sig); sm_allsignals(true); IntSig = true; FileName = NULL; /* Clean-up on aborted stdin message submission */ if (OpMode == MD_SMTP || OpMode == MD_DELIVER || OpMode == MD_ARPAFTP) { if (CurEnv->e_id != NULL) { char *fn; fn = queuename(CurEnv, DATAFL_LETTER); if (fn != NULL) (void) unlink(fn); fn = queuename(CurEnv, ANYQFL_LETTER); if (fn != NULL) (void) unlink(fn); } _exit(EX_OK); /* NOTREACHED */ } if (sig != 0 && LogLevel > 79) sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt"); if (OpMode != MD_TEST) unlockqueue(CurEnv); finis(drop, false, EX_OK); /* NOTREACHED */ } /* ** DISCONNECT -- remove our connection with any foreground process ** ** Parameters: ** droplev -- how "deeply" we should drop the line. ** 0 -- ignore signals, mail back errors, make sure ** output goes to stdout. ** 1 -- also, make stdout go to /dev/null. ** 2 -- also, disconnect from controlling terminal ** (only for daemon mode). ** e -- the current envelope. ** ** Returns: ** none ** ** Side Effects: ** Trys to insure that we are immune to vagaries of ** the controlling tty. */ void disconnect(droplev, e) int droplev; register ENVELOPE *e; { int fd; if (tTd(52, 1)) sm_dprintf("disconnect: In %d Out %d, e=%p\n", sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL), sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e); if (tTd(52, 100)) { sm_dprintf("don't\n"); return; } if (LogLevel > 93) sm_syslog(LOG_DEBUG, e->e_id, "disconnect level %d", droplev); /* be sure we don't get nasty signals */ (void) sm_signal(SIGINT, SIG_IGN); (void) sm_signal(SIGQUIT, SIG_IGN); /* we can't communicate with our caller, so.... */ HoldErrs = true; CurEnv->e_errormode = EM_MAIL; Verbose = 0; DisConnected = true; /* all input from /dev/null */ if (InChannel != smioin) { (void) sm_io_close(InChannel, SM_TIME_DEFAULT); InChannel = smioin; } if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL, SM_IO_RDONLY, NULL, smioin) == NULL) sm_syslog(LOG_ERR, e->e_id, "disconnect: sm_io_reopen(\"%s\") failed: %s", SM_PATH_DEVNULL, sm_errstring(errno)); /* ** output to the transcript ** We also compare the fd numbers here since OutChannel ** might be a layer on top of smioout due to encryption ** (see sfsasl.c). */ if (OutChannel != smioout && sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) != sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL)) { (void) sm_io_close(OutChannel, SM_TIME_DEFAULT); OutChannel = smioout; #if 0 /* ** Has smioout been closed? Reopen it. ** This shouldn't happen anymore, the code is here ** just as a reminder. */ if (smioout->sm_magic == NULL && sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL, SM_IO_WRONLY, NULL, smioout) == NULL) sm_syslog(LOG_ERR, e->e_id, "disconnect: sm_io_reopen(\"%s\") failed: %s", SM_PATH_DEVNULL, sm_errstring(errno)); #endif /* 0 */ } if (droplev > 0) { fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666); if (fd == -1) { sm_syslog(LOG_ERR, e->e_id, "disconnect: open(\"%s\") failed: %s", SM_PATH_DEVNULL, sm_errstring(errno)); } (void) sm_io_flush(smioout, SM_TIME_DEFAULT); if (fd >= 0) { (void) dup2(fd, STDOUT_FILENO); (void) dup2(fd, STDERR_FILENO); (void) close(fd); } } /* drop our controlling TTY completely if possible */ if (droplev > 1) { (void) setsid(); errno = 0; } #if XDEBUG checkfd012("disconnect"); #endif /* XDEBUG */ if (LogLevel > 71) sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d", (int) CurrentPid); errno = 0; } static void obsolete(argv) char *argv[]; { register char *ap; register char *op; while ((ap = *++argv) != NULL) { /* Return if "--" or not an option of any form. */ if (ap[0] != '-' || ap[1] == '-') return; /* Don't allow users to use "-Q." or "-Q ." */ if ((ap[1] == 'Q' && ap[2] == '.') || (ap[1] == 'Q' && argv[1] != NULL && argv[1][0] == '.' && argv[1][1] == '\0')) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Can not use -Q.\n"); exit(EX_USAGE); } /* skip over options that do have a value */ op = strchr(OPTIONS, ap[1]); if (op != NULL && *++op == ':' && ap[2] == '\0' && ap[1] != 'd' && #if defined(sony_news) ap[1] != 'E' && ap[1] != 'J' && #endif /* defined(sony_news) */ argv[1] != NULL && argv[1][0] != '-') { argv++; continue; } /* If -C doesn't have an argument, use sendmail.cf. */ #define __DEFPATH "sendmail.cf" if (ap[1] == 'C' && ap[2] == '\0') { *argv = xalloc(sizeof(__DEFPATH) + 2); (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2, "-C", __DEFPATH); } /* If -q doesn't have an argument, run it once. */ if (ap[1] == 'q' && ap[2] == '\0') *argv = "-q0"; /* If -Q doesn't have an argument, disable quarantining */ if (ap[1] == 'Q' && ap[2] == '\0') *argv = "-Q."; /* if -d doesn't have an argument, use 0-99.1 */ if (ap[1] == 'd' && ap[2] == '\0') *argv = "-d0-99.1"; #if defined(sony_news) /* if -E doesn't have an argument, use -EC */ if (ap[1] == 'E' && ap[2] == '\0') *argv = "-EC"; /* if -J doesn't have an argument, use -JJ */ if (ap[1] == 'J' && ap[2] == '\0') *argv = "-JJ"; #endif /* defined(sony_news) */ } } /* ** AUTH_WARNING -- specify authorization warning ** ** Parameters: ** e -- the current envelope. ** msg -- the text of the message. ** args -- arguments to the message. ** ** Returns: ** none. */ void #ifdef __STDC__ auth_warning(register ENVELOPE *e, const char *msg, ...) #else /* __STDC__ */ auth_warning(e, msg, va_alist) register ENVELOPE *e; const char *msg; va_dcl #endif /* __STDC__ */ { char buf[MAXLINE]; SM_VA_LOCAL_DECL if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags)) { register char *p; static char hostbuf[48]; if (hostbuf[0] == '\0') { struct hostent *hp; hp = myhostname(hostbuf, sizeof(hostbuf)); #if NETINET6 if (hp != NULL) { freehostent(hp); hp = NULL; } #endif /* NETINET6 */ } (void) sm_strlcpyn(buf, sizeof(buf), 2, hostbuf, ": "); p = &buf[strlen(buf)]; SM_VA_START(ap, msg); (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap); SM_VA_END(ap); addheader("X-Authentication-Warning", buf, 0, e, true); if (LogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Authentication-Warning: %.400s", buf); } } /* ** GETEXTENV -- get from external environment ** ** Parameters: ** envar -- the name of the variable to retrieve ** ** Returns: ** The value, if any. */ static char * getextenv(envar) const char *envar; { char **envp; int l; l = strlen(envar); for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++) { if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=') return &(*envp)[l + 1]; } return NULL; } /* ** SM_SETUSERENV -- set an environment variable in the propagated environment ** ** Parameters: ** envar -- the name of the environment variable. ** value -- the value to which it should be set. If ** null, this is extracted from the incoming ** environment. If that is not set, the call ** to sm_setuserenv is ignored. ** ** Returns: ** none. */ void sm_setuserenv(envar, value) const char *envar; const char *value; { int i, l; char **evp = UserEnviron; char *p; if (value == NULL) { value = getextenv(envar); if (value == NULL) return; } /* XXX enforce reasonable size? */ i = strlen(envar) + 1; l = strlen(value) + i + 1; p = (char *) xalloc(l); (void) sm_strlcpyn(p, l, 3, envar, "=", value); while (*evp != NULL && strncmp(*evp, p, i) != 0) evp++; if (*evp != NULL) { *evp++ = p; } else if (evp < &UserEnviron[MAXUSERENVIRON]) { *evp++ = p; *evp = NULL; } /* make sure it is in our environment as well */ if (putenv(p) < 0) syserr("sm_setuserenv: putenv(%s) failed", p); } /* ** DUMPSTATE -- dump state ** ** For debugging. */ void dumpstate(when) char *when; { register char *j = macvalue('j', CurEnv); int rs; extern int NextMacroId; sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- dumping state on %s: $j = %s ---", when, j == NULL ? "" : j); if (j != NULL) { if (!wordinclass(j, 'w')) sm_syslog(LOG_DEBUG, CurEnv->e_id, "*** $j not in $=w ***"); } sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren); sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)", NextMacroId, MAXMACROID); sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---"); printopenfds(true); sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---"); mci_dump_all(smioout, true); rs = strtorwset("debug_dumpstate", NULL, ST_FIND); if (rs > 0) { int status; register char **pvp; char *pv[MAXATOM + 1]; pv[0] = NULL; status = REWRITE(pv, rs, CurEnv); sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- ruleset debug_dumpstate returns stat %d, pv: ---", status); for (pvp = pv; *pvp != NULL; pvp++) sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp); } sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---"); } #ifdef SIGUSR1 /* ** SIGUSR1 -- Signal a request to dump state. ** ** Parameters: ** sig -- calling signal. ** ** Returns: ** none. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. ** ** XXX: More work is needed for this signal handler. */ /* ARGSUSED */ static SIGFUNC_DECL sigusr1(sig) int sig; { int save_errno = errno; FIX_SYSV_SIGNAL(sig, sigusr1); errno = save_errno; CHECK_CRITICAL(sig); dumpstate("user signal"); # if SM_HEAP_CHECK dumpstab(); # endif /* SM_HEAP_CHECK */ errno = save_errno; return SIGFUNC_RETURN; } #endif /* SIGUSR1 */ /* ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option ** ** Parameters: ** to_real_uid -- if set, drop to the real uid instead ** of the RunAsUser. ** ** Returns: ** EX_OSERR if the setuid failed. ** EX_OK otherwise. */ int drop_privileges(to_real_uid) bool to_real_uid; { int rval = EX_OK; GIDSET_T emptygidset[1]; if (tTd(47, 1)) sm_dprintf("drop_privileges(%d): Real[UG]id=%d:%d, get[ug]id=%d:%d, gete[ug]id=%d:%d, RunAs[UG]id=%d:%d\n", (int) to_real_uid, (int) RealUid, (int) RealGid, (int) getuid(), (int) getgid(), (int) geteuid(), (int) getegid(), (int) RunAsUid, (int) RunAsGid); if (to_real_uid) { RunAsUserName = RealUserName; RunAsUid = RealUid; RunAsGid = RealGid; EffGid = RunAsGid; } /* make sure no one can grab open descriptors for secret files */ endpwent(); sm_mbdb_terminate(); /* reset group permissions; these can be set later */ emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid(); /* ** Notice: on some OS (Linux...) the setgroups() call causes ** a logfile entry if sendmail is not run by root. ** However, it is unclear (no POSIX standard) whether ** setgroups() can only succeed if executed by root. ** So for now we keep it as it is; if you want to change it, use ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1) */ if (setgroups(1, emptygidset) == -1 && geteuid() == 0) { syserr("drop_privileges: setgroups(1, %d) failed", (int) emptygidset[0]); rval = EX_OSERR; } /* reset primary group id */ if (to_real_uid) { /* ** Drop gid to real gid. ** On some OS we must reset the effective[/real[/saved]] gid, ** and then use setgid() to finally drop all group privileges. ** Later on we check whether we can get back the ** effective gid. */ #if HASSETEGID if (setegid(RunAsGid) < 0) { syserr("drop_privileges: setegid(%d) failed", (int) RunAsGid); rval = EX_OSERR; } #else /* HASSETEGID */ # if HASSETREGID if (setregid(RunAsGid, RunAsGid) < 0) { syserr("drop_privileges: setregid(%d, %d) failed", (int) RunAsGid, (int) RunAsGid); rval = EX_OSERR; } # else /* HASSETREGID */ # if HASSETRESGID if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0) { syserr("drop_privileges: setresgid(%d, %d, %d) failed", (int) RunAsGid, (int) RunAsGid, (int) RunAsGid); rval = EX_OSERR; } # endif /* HASSETRESGID */ # endif /* HASSETREGID */ #endif /* HASSETEGID */ } if (rval == EX_OK && (to_real_uid || RunAsGid != 0)) { if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid)) { syserr("drop_privileges: setgid(%d) failed", (int) RunAsGid); rval = EX_OSERR; } errno = 0; if (rval == EX_OK && getegid() != RunAsGid) { syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d", (int) getegid(), (int) RunAsGid); rval = EX_OSERR; } } /* fiddle with uid */ if (to_real_uid || RunAsUid != 0) { uid_t euid; /* ** Try to setuid(RunAsUid). ** euid must be RunAsUid, ** ruid must be RunAsUid unless (e|r)uid wasn't 0 ** and we didn't have to drop privileges to the real uid. */ if (setuid(RunAsUid) < 0 || geteuid() != RunAsUid || (getuid() != RunAsUid && (to_real_uid || geteuid() == 0 || getuid() == 0))) { #if HASSETREUID /* ** if ruid != RunAsUid, euid == RunAsUid, then ** try resetting just the real uid, then using ** setuid() to drop the saved-uid as well. */ if (geteuid() == RunAsUid) { if (setreuid(RunAsUid, -1) < 0) { syserr("drop_privileges: setreuid(%d, -1) failed", (int) RunAsUid); rval = EX_OSERR; } if (setuid(RunAsUid) < 0) { syserr("drop_privileges: second setuid(%d) attempt failed", (int) RunAsUid); rval = EX_OSERR; } } else #endif /* HASSETREUID */ { syserr("drop_privileges: setuid(%d) failed", (int) RunAsUid); rval = EX_OSERR; } } euid = geteuid(); if (RunAsUid != 0 && setuid(0) == 0) { /* ** Believe it or not, the Linux capability model ** allows a non-root process to override setuid() ** on a process running as root and prevent that ** process from dropping privileges. */ syserr("drop_privileges: setuid(0) succeeded (when it should not)"); rval = EX_OSERR; } else if (RunAsUid != euid && setuid(euid) == 0) { /* ** Some operating systems will keep the saved-uid ** if a non-root effective-uid calls setuid(real-uid) ** making it possible to set it back again later. */ syserr("drop_privileges: Unable to drop non-root set-user-ID privileges"); rval = EX_OSERR; } } if ((to_real_uid || RunAsGid != 0) && rval == EX_OK && RunAsGid != EffGid && getuid() != 0 && geteuid() != 0) { errno = 0; if (setgid(EffGid) == 0) { syserr("drop_privileges: setgid(%d) succeeded (when it should not)", (int) EffGid); rval = EX_OSERR; } } if (tTd(47, 5)) { sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n", (int) geteuid(), (int) getuid(), (int) getegid(), (int) getgid()); sm_dprintf("drop_privileges: RunAsUser = %d:%d\n", (int) RunAsUid, (int) RunAsGid); if (tTd(47, 10)) sm_dprintf("drop_privileges: rval = %d\n", rval); } return rval; } /* ** FILL_FD -- make sure a file descriptor has been properly allocated ** ** Used to make sure that stdin/out/err are allocated on startup ** ** Parameters: ** fd -- the file descriptor to be filled. ** where -- a string used for logging. If NULL, this is ** being called on startup, and logging should ** not be done. ** ** Returns: ** none ** ** Side Effects: ** possibly changes MissingFds */ void fill_fd(fd, where) int fd; char *where; { int i; struct stat stbuf; if (fstat(fd, &stbuf) >= 0 || errno != EBADF) return; if (where != NULL) syserr("fill_fd: %s: fd %d not open", where, fd); else MissingFds |= 1 << fd; i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666); if (i < 0) { syserr("!fill_fd: %s: cannot open %s", where == NULL ? "startup" : where, SM_PATH_DEVNULL); } if (fd != i) { (void) dup2(i, fd); (void) close(i); } } /* ** SM_PRINTOPTIONS -- print options ** ** Parameters: ** options -- array of options. ** ** Returns: ** none. */ static void sm_printoptions(options) char **options; { int ll; char **av; av = options; ll = 7; while (*av != NULL) { if (ll + strlen(*av) > 63) { sm_dprintf("\n"); ll = 0; } if (ll == 0) sm_dprintf("\t\t"); else sm_dprintf(" "); sm_dprintf("%s", *av); ll += strlen(*av++) + 1; } sm_dprintf("\n"); } /* ** TO8BIT -- convert \octal sequences in a test mode input line ** ** Parameters: ** str -- the input line. ** ** Returns: ** none. ** ** Side Effects: ** replaces \0octal in str with octal value. */ static bool to8bit __P((char *)); static bool to8bit(str) char *str; { int c, len; char *out, *in; bool changed; if (str == NULL) return false; in = out = str; changed = false; len = 0; while ((c = (*str++ & 0377)) != '\0') { int oct, nxtc; ++len; if (c == '\\' && (nxtc = (*str & 0377)) == '0') { oct = 0; while ((nxtc = (*str & 0377)) != '\0' && isascii(nxtc) && isdigit(nxtc)) { oct <<= 3; oct += nxtc - '0'; ++str; ++len; } changed = true; c = oct; } *out++ = c; } *out++ = c; if (changed) { char *q; q = quote_internal_chars(in, in, &len); if (q != in) sm_strlcpy(in, q, len); } return changed; } /* ** TESTMODELINE -- process a test mode input line ** ** Parameters: ** line -- the input line. ** e -- the current environment. ** Syntax: ** # a comment ** .X process X as a configuration line ** =X dump a configuration item (such as mailers) ** $X dump a macro or class ** /X try an activity ** X normal process through rule set X */ static void testmodeline(line, e) char *line; ENVELOPE *e; { register char *p; char *q; auto char *delimptr; int mid; int i, rs; STAB *map; char **s; struct rewrite *rw; ADDRESS a; char *lbp; auto int lbs; static int tryflags = RF_COPYNONE; char exbuf[MAXLINE]; char lbuf[MAXLINE]; extern unsigned char TokTypeNoC[]; bool eightbit; /* skip leading spaces */ while (*line == ' ') line++; lbp = NULL; eightbit = false; switch (line[0]) { case '#': case '\0': return; case '?': help("-bt", e); return; case '.': /* config-style settings */ switch (line[1]) { case 'D': mid = macid_parse(&line[2], &delimptr); if (mid == 0) return; lbs = sizeof(lbuf); lbp = translate_dollars(delimptr, lbuf, &lbs); macdefine(&e->e_macro, A_TEMP, mid, lbp); if (lbp != lbuf) SM_FREE(lbp); break; case 'C': if (line[2] == '\0') /* not to call syserr() */ return; mid = macid_parse(&line[2], &delimptr); if (mid == 0) return; lbs = sizeof(lbuf); lbp = translate_dollars(delimptr, lbuf, &lbs); expand(lbp, exbuf, sizeof(exbuf), e); if (lbp != lbuf) SM_FREE(lbp); p = exbuf; while (*p != '\0') { register char *wd; char delim; while (*p != '\0' && isascii(*p) && isspace(*p)) p++; wd = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; delim = *p; *p = '\0'; if (wd[0] != '\0') setclass(mid, wd); *p = delim; } break; case '\0': (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: .[DC]macro value(s)\n"); break; default: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Unknown \".\" command %s\n", line); break; } return; case '=': /* config-style settings */ switch (line[1]) { case 'S': /* dump rule set */ rs = strtorwset(&line[2], NULL, ST_FIND); if (rs < 0) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Undefined ruleset %s\n", &line[2]); return; } rw = RewriteRules[rs]; if (rw == NULL) return; do { (void) sm_io_putc(smioout, SM_TIME_DEFAULT, 'R'); s = rw->r_lhs; while (*s != NULL) { xputs(smioout, *s++); (void) sm_io_putc(smioout, SM_TIME_DEFAULT, ' '); } (void) sm_io_putc(smioout, SM_TIME_DEFAULT, '\t'); (void) sm_io_putc(smioout, SM_TIME_DEFAULT, '\t'); s = rw->r_rhs; while (*s != NULL) { xputs(smioout, *s++); (void) sm_io_putc(smioout, SM_TIME_DEFAULT, ' '); } (void) sm_io_putc(smioout, SM_TIME_DEFAULT, '\n'); } while ((rw = rw->r_next) != NULL); break; case 'M': for (i = 0; i < MAXMAILERS; i++) { if (Mailer[i] != NULL) printmailer(smioout, Mailer[i]); } break; case '\0': (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: =Sruleset or =M\n"); break; default: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Unknown \"=\" command %s\n", line); break; } return; case '-': /* set command-line-like opts */ switch (line[1]) { case 'd': tTflag(&line[2]); break; case '\0': (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: -d{debug arguments}\n"); break; default: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Unknown \"-\" command %s\n", line); break; } return; case '$': if (line[1] == '=') { mid = macid(&line[2]); if (mid != 0) stabapply(dump_class, mid); return; } mid = macid(&line[1]); if (mid == 0) return; p = macvalue(mid, e); if (p == NULL) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Undefined\n"); else { xputs(smioout, p); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n"); } return; case '/': /* miscellaneous commands */ p = &line[strlen(line)]; while (--p >= line && isascii(*p) && isspace(*p)) *p = '\0'; p = strpbrk(line, " \t"); if (p != NULL) { while (isascii(*p) && isspace(*p)) *p++ = '\0'; } else p = ""; if (line[1] == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: /[canon|map|mx|parse|try|tryflags]\n"); return; } if (sm_strcasecmp(&line[1], "quit") == 0) { CurEnv->e_id = NULL; finis(true, true, ExitStat); /* NOTREACHED */ } if (sm_strcasecmp(&line[1], "mx") == 0) { #if NAMED_BIND /* look up MX records */ int nmx; auto int rcode; char *mxhosts[MAXMXHOSTS + 1]; if (*p == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: /mx address\n"); return; } nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true, NULL); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "getmxrr(%s) returns %d value(s):\n", p, nmx); for (i = 0; i < nmx; i++) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\t%s\n", mxhosts[i]); #else /* NAMED_BIND */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "No MX code compiled in\n"); #endif /* NAMED_BIND */ } else if (sm_strcasecmp(&line[1], "canon") == 0) { char host[MAXHOSTNAMELEN]; if (*p == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: /canon address\n"); return; } else if (sm_strlcpy(host, p, sizeof(host)) >= sizeof(host)) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Name too long\n"); return; } (void) getcanonname(host, sizeof(host), !HasWildcardMX, NULL); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "getcanonname(%s) returns %s\n", p, host); } else if (sm_strcasecmp(&line[1], "map") == 0) { auto int rcode = EX_OK; char *av[2]; if (*p == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: /map mapname key\n"); return; } for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q)); q++) continue; if (*q == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "No key specified\n"); return; } *q++ = '\0'; map = stab(p, ST_MAP, ST_FIND); if (map == NULL) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Map named \"%s\" not found\n", p); return; } if (!bitset(MF_OPEN, map->s_map.map_mflags) && !openmap(&(map->s_map))) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Map named \"%s\" not open\n", p); return; } (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "map_lookup: %s (%s) ", p, q); av[0] = q; av[1] = NULL; p = (*map->s_map.map_class->map_lookup) (&map->s_map, q, av, &rcode); if (p == NULL) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "no match (%d)\n", rcode); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "returns %s (%d)\n", p, rcode); } else if (sm_strcasecmp(&line[1], "try") == 0) { MAILER *m; STAB *st; auto int rcode = EX_OK; q = strpbrk(p, " \t"); if (q != NULL) { while (isascii(*q) && isspace(*q)) *q++ = '\0'; } if (q == NULL || *q == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: /try mailer address\n"); return; } st = stab(p, ST_MAILER, ST_FIND); if (st == NULL) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Unknown mailer %s\n", p); return; } m = st->s_mailer; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Trying %s %s address %s for mailer %s\n", bitset(RF_HEADERADDR, tryflags) ? "header" : "envelope", bitset(RF_SENDERADDR, tryflags) ? "sender" : "recipient", q, p); p = remotename(q, m, tryflags, &rcode, CurEnv); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Rcode = %d, addr = %s\n", rcode, p == NULL ? "" : p); e->e_to = NULL; } else if (sm_strcasecmp(&line[1], "tryflags") == 0) { if (*p == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: /tryflags [Hh|Ee][Ss|Rr]\n"); return; } for (; *p != '\0'; p++) { switch (*p) { case 'H': case 'h': tryflags |= RF_HEADERADDR; break; case 'E': case 'e': tryflags &= ~RF_HEADERADDR; break; case 'S': case 's': tryflags |= RF_SENDERADDR; break; case 'R': case 'r': tryflags &= ~RF_SENDERADDR; break; } } exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e'; exbuf[1] = ' '; exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r'; exbuf[3] = '\0'; macdefine(&e->e_macro, A_TEMP, macid("{addr_type}"), exbuf); } else if (sm_strcasecmp(&line[1], "parse") == 0) { if (*p == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Usage: /parse address\n"); return; } q = crackaddr(p, e); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Cracked address = "); xputs(smioout, q); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\nParsing %s %s address\n", bitset(RF_HEADERADDR, tryflags) ? "header" : "envelope", bitset(RF_SENDERADDR, tryflags) ? "sender" : "recipient"); if (parseaddr(p, &a, tryflags, '\0', NULL, e, true) == NULL) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Cannot parse\n"); else if (a.q_host != NULL && a.q_host[0] != '\0') (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "mailer %s, host %s, user %s\n", a.q_mailer->m_name, a.q_host, a.q_user); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "mailer %s, user %s\n", a.q_mailer->m_name, a.q_user); e->e_to = NULL; } else if (sm_strcasecmp(&line[1], "header") == 0) { unsigned long ul; ul = chompheader(p, CHHDR_CHECK|CHHDR_USER, NULL, e); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "ul = %lu\n", ul); } else { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Unknown \"/\" command %s\n", line); } (void) sm_io_flush(smioout, SM_TIME_DEFAULT); return; } for (p = line; isascii(*p) && isspace(*p); p++) continue; q = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p == '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "No address!\n"); return; } *p = '\0'; if (tTd(23, 101)) eightbit = to8bit(p + 1); if (invalidaddr(p + 1, NULL, true)) return; do { register char **pvp; char pvpbuf[PSBUFSIZE]; pvp = prescan(++p, ',', pvpbuf, sizeof(pvpbuf), &delimptr, ConfigLevel >= 9 ? TokTypeNoC : ExtTokenTab, false); if (pvp == NULL) continue; p = q; while (*p != '\0') { int status; rs = strtorwset(p, NULL, ST_FIND); if (rs < 0) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Undefined ruleset %s\n", p); break; } status = REWRITE(pvp, rs, e); if (status != EX_OK) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "== Ruleset %s (%d) status %d\n", p, rs, status); else if (eightbit) { cataddr(pvp, NULL, exbuf, sizeof(exbuf), '\0', true); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "cataddr: %s\n", str2prt(exbuf)); } while (*p != '\0' && *p++ != ',') continue; } } while (*(p = delimptr) != '\0'); (void) sm_io_flush(smioout, SM_TIME_DEFAULT); } static void dump_class(s, id) register STAB *s; int id; { if (s->s_symtype != ST_CLASS) return; if (bitnset(bitidx(id), s->s_class)) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s\n", s->s_name); } /* ** An exception type used to create QuickAbort exceptions. ** This is my first cut at converting QuickAbort from longjmp to exceptions. ** These exceptions have a single integer argument, which is the argument ** to longjmp in the original code (either 1 or 2). I don't know the ** significance of 1 vs 2: the calls to setjmp don't care. */ const SM_EXC_TYPE_T EtypeQuickAbort = { SmExcTypeMagic, "E:mta.quickabort", "i", sm_etype_printf, "quick abort %0", }; Index: head/contrib/sendmail/src/map.c =================================================================== --- head/contrib/sendmail/src/map.c (revision 249728) +++ head/contrib/sendmail/src/map.c (revision 249729) @@ -1,8013 +1,8016 @@ /* * Copyright (c) 1998-2008 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1992, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: map.c,v 8.709 2012/04/20 18:47:09 ca Exp $") +SM_RCSID("@(#)$Id: map.c,v 8.711 2013/03/12 15:24:52 ca Exp $") #if LDAPMAP # include #endif /* LDAPMAP */ #if NDBM # include # ifdef R_FIRST ERROR README: You are running the Berkeley DB version of ndbm.h. See ERROR README: the README file about tweaking Berkeley DB so it can ERROR README: coexist with NDBM, or delete -DNDBM from the Makefile ERROR README: and use -DNEWDB instead. # endif /* R_FIRST */ #endif /* NDBM */ #if NEWDB # include "sm/bdb.h" #endif /* NEWDB */ #if NIS struct dom_binding; /* forward reference needed on IRIX */ # include # if NDBM # define NDBM_YP_COMPAT /* create YP-compatible NDBM files */ # endif /* NDBM */ #endif /* NIS */ #include "map.h" #if NEWDB # if DB_VERSION_MAJOR < 2 static bool db_map_open __P((MAP *, int, char *, DBTYPE, const void *)); # endif /* DB_VERSION_MAJOR < 2 */ # if DB_VERSION_MAJOR == 2 static bool db_map_open __P((MAP *, int, char *, DBTYPE, DB_INFO *)); # endif /* DB_VERSION_MAJOR == 2 */ # if DB_VERSION_MAJOR > 2 static bool db_map_open __P((MAP *, int, char *, DBTYPE, void **)); # endif /* DB_VERSION_MAJOR > 2 */ #endif /* NEWDB */ static bool extract_canonname __P((char *, char *, char *, char[], int)); static void map_close __P((STAB *, int)); static void map_init __P((STAB *, int)); #ifdef LDAPMAP static STAB * ldapmap_findconn __P((SM_LDAP_STRUCT *)); #endif /* LDAPMAP */ #if NISPLUS static bool nisplus_getcanonname __P((char *, int, int *)); #endif /* NISPLUS */ #if NIS static bool nis_getcanonname __P((char *, int, int *)); #endif /* NIS */ #if NETINFO static bool ni_getcanonname __P((char *, int, int *)); #endif /* NETINFO */ static bool text_getcanonname __P((char *, int, int *)); #if SOCKETMAP static STAB *socket_map_findconn __P((const char*)); /* XXX arbitrary limit for sanity */ # define SOCKETMAP_MAXL 1000000 #endif /* SOCKETMAP */ /* default error message for trying to open a map in write mode */ #ifdef ENOSYS # define SM_EMAPCANTWRITE ENOSYS #else /* ENOSYS */ # ifdef EFTYPE # define SM_EMAPCANTWRITE EFTYPE # else /* EFTYPE */ # define SM_EMAPCANTWRITE ENXIO # endif /* EFTYPE */ #endif /* ENOSYS */ /* ** MAP.C -- implementations for various map classes. ** ** Each map class implements a series of functions: ** ** bool map_parse(MAP *map, char *args) ** Parse the arguments from the config file. Return true ** if they were ok, false otherwise. Fill in map with the ** values. ** ** char *map_lookup(MAP *map, char *key, char **args, int *pstat) ** Look up the key in the given map. If found, do any ** rewriting the map wants (including "args" if desired) ** and return the value. Set *pstat to the appropriate status ** on error and return NULL. Args will be NULL if called ** from the alias routines, although this should probably ** not be relied upon. It is suggested you call map_rewrite ** to return the results -- it takes care of null termination ** and uses a dynamically expanded buffer as needed. ** ** void map_store(MAP *map, char *key, char *value) ** Store the key:value pair in the map. ** ** bool map_open(MAP *map, int mode) ** Open the map for the indicated mode. Mode should ** be either O_RDONLY or O_RDWR. Return true if it ** was opened successfully, false otherwise. If the open ** failed and the MF_OPTIONAL flag is not set, it should ** also print an error. If the MF_ALIAS bit is set ** and this map class understands the @:@ convention, it ** should call aliaswait() before returning. ** ** void map_close(MAP *map) ** Close the map. ** ** This file also includes the implementation for getcanonname. ** It is currently implemented in a pretty ad-hoc manner; it ought ** to be more properly integrated into the map structure. */ #if O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL # define LOCK_ON_OPEN 1 /* we can open/create a locked file */ #else /* O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL */ # define LOCK_ON_OPEN 0 /* no such luck -- bend over backwards */ #endif /* O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL */ /* ** MAP_PARSEARGS -- parse config line arguments for database lookup ** ** This is a generic version of the map_parse method. ** ** Parameters: ** map -- the map being initialized. ** ap -- a pointer to the args on the config line. ** ** Returns: ** true -- if everything parsed OK. ** false -- otherwise. ** ** Side Effects: ** null terminates the filename; stores it in map */ bool map_parseargs(map, ap) MAP *map; char *ap; { register char *p = ap; /* ** There is no check whether there is really an argument, ** but that's not important enough to warrant extra code. */ map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL; map->map_spacesub = SpaceSub; /* default value */ for (;;) { while (isascii(*p) && isspace(*p)) p++; if (*p != '-') break; switch (*++p) { case 'N': map->map_mflags |= MF_INCLNULL; map->map_mflags &= ~MF_TRY0NULL; break; case 'O': map->map_mflags &= ~MF_TRY1NULL; break; case 'o': map->map_mflags |= MF_OPTIONAL; break; case 'f': map->map_mflags |= MF_NOFOLDCASE; break; case 'm': map->map_mflags |= MF_MATCHONLY; break; case 'A': map->map_mflags |= MF_APPEND; break; case 'q': map->map_mflags |= MF_KEEPQUOTES; break; case 'a': map->map_app = ++p; break; case 'T': map->map_tapp = ++p; break; case 'k': while (isascii(*++p) && isspace(*p)) continue; map->map_keycolnm = p; break; case 'v': while (isascii(*++p) && isspace(*p)) continue; map->map_valcolnm = p; break; case 'z': if (*++p != '\\') map->map_coldelim = *p; else { switch (*++p) { case 'n': map->map_coldelim = '\n'; break; case 't': map->map_coldelim = '\t'; break; default: map->map_coldelim = '\\'; } } break; case 't': map->map_mflags |= MF_NODEFER; break; case 'S': map->map_spacesub = *++p; break; case 'D': map->map_mflags |= MF_DEFER; break; default: syserr("Illegal option %c map %s", *p, map->map_mname); break; } while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; } if (map->map_app != NULL) map->map_app = newstr(map->map_app); if (map->map_tapp != NULL) map->map_tapp = newstr(map->map_tapp); if (map->map_keycolnm != NULL) map->map_keycolnm = newstr(map->map_keycolnm); if (map->map_valcolnm != NULL) map->map_valcolnm = newstr(map->map_valcolnm); if (*p != '\0') { map->map_file = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; map->map_file = newstr(map->map_file); } while (*p != '\0' && isascii(*p) && isspace(*p)) p++; if (*p != '\0') map->map_rebuild = newstr(p); if (map->map_file == NULL && !bitset(MCF_OPTFILE, map->map_class->map_cflags)) { syserr("No file name for %s map %s", map->map_class->map_cname, map->map_mname); return false; } return true; } /* ** MAP_REWRITE -- rewrite a database key, interpolating %n indications. ** ** It also adds the map_app string. It can be used as a utility ** in the map_lookup method. ** ** Parameters: ** map -- the map that causes this. ** s -- the string to rewrite, NOT necessarily null terminated. ** slen -- the length of s. ** av -- arguments to interpolate into buf. ** ** Returns: ** Pointer to rewritten result. This is static data that ** should be copied if it is to be saved! */ char * map_rewrite(map, s, slen, av) register MAP *map; register const char *s; size_t slen; char **av; { register char *bp; register char c; char **avp; register char *ap; size_t l; size_t len; static size_t buflen = 0; static char *buf = NULL; if (tTd(39, 1)) { sm_dprintf("map_rewrite(%.*s), av =", (int) slen, s); if (av == NULL) sm_dprintf(" (nullv)"); else { for (avp = av; *avp != NULL; avp++) sm_dprintf("\n\t%s", *avp); } sm_dprintf("\n"); } /* count expected size of output (can safely overestimate) */ l = len = slen; if (av != NULL) { const char *sp = s; while (l-- > 0 && (c = *sp++) != '\0') { if (c != '%') continue; if (l-- <= 0) break; c = *sp++; if (!(isascii(c) && isdigit(c))) continue; for (avp = av; --c >= '0' && *avp != NULL; avp++) continue; if (*avp == NULL) continue; len += strlen(*avp); } } if (map->map_app != NULL) len += strlen(map->map_app); if (buflen < ++len) { /* need to malloc additional space */ buflen = len; if (buf != NULL) sm_free(buf); buf = sm_pmalloc_x(buflen); } bp = buf; if (av == NULL) { memmove(bp, s, slen); bp += slen; /* assert(len > slen); */ len -= slen; } else { while (slen-- > 0 && (c = *s++) != '\0') { if (c != '%') { pushc: if (len-- <= 1) break; *bp++ = c; continue; } if (slen-- <= 0 || (c = *s++) == '\0') c = '%'; if (c == '%') goto pushc; if (!(isascii(c) && isdigit(c))) { if (len-- <= 1) break; *bp++ = '%'; goto pushc; } for (avp = av; --c >= '0' && *avp != NULL; avp++) continue; if (*avp == NULL) continue; /* transliterate argument into output string */ for (ap = *avp; (c = *ap++) != '\0' && len > 0; --len) *bp++ = c; } } if (map->map_app != NULL && len > 0) (void) sm_strlcpy(bp, map->map_app, len); else *bp = '\0'; if (tTd(39, 1)) sm_dprintf("map_rewrite => %s\n", buf); return buf; } /* ** INITMAPS -- rebuild alias maps ** ** Parameters: ** none. ** ** Returns: ** none. */ void initmaps() { #if XDEBUG checkfd012("entering initmaps"); #endif /* XDEBUG */ stabapply(map_init, 0); #if XDEBUG checkfd012("exiting initmaps"); #endif /* XDEBUG */ } /* ** MAP_INIT -- rebuild a map ** ** Parameters: ** s -- STAB entry: if map: try to rebuild ** unused -- unused variable ** ** Returns: ** none. ** ** Side Effects: ** will close already open rebuildable map. */ /* ARGSUSED1 */ static void map_init(s, unused) register STAB *s; int unused; { register MAP *map; /* has to be a map */ if (s->s_symtype != ST_MAP) return; map = &s->s_map; if (!bitset(MF_VALID, map->map_mflags)) return; if (tTd(38, 2)) sm_dprintf("map_init(%s:%s, %s)\n", map->map_class->map_cname == NULL ? "NULL" : map->map_class->map_cname, map->map_mname == NULL ? "NULL" : map->map_mname, map->map_file == NULL ? "NULL" : map->map_file); if (!bitset(MF_ALIAS, map->map_mflags) || !bitset(MCF_REBUILDABLE, map->map_class->map_cflags)) { if (tTd(38, 3)) sm_dprintf("\tnot rebuildable\n"); return; } /* if already open, close it (for nested open) */ if (bitset(MF_OPEN, map->map_mflags)) { map->map_mflags |= MF_CLOSING; map->map_class->map_close(map); map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING); } (void) rebuildaliases(map, false); return; } /* ** OPENMAP -- open a map ** ** Parameters: ** map -- map to open (it must not be open). ** ** Returns: ** whether open succeeded. */ bool openmap(map) MAP *map; { bool restore = false; bool savehold = HoldErrs; bool savequick = QuickAbort; int saveerrors = Errors; if (!bitset(MF_VALID, map->map_mflags)) return false; /* better safe than sorry... */ if (bitset(MF_OPEN, map->map_mflags)) return true; /* Don't send a map open error out via SMTP */ if ((OnlyOneError || QuickAbort) && (OpMode == MD_SMTP || OpMode == MD_DAEMON)) { restore = true; HoldErrs = true; QuickAbort = false; } errno = 0; if (map->map_class->map_open(map, O_RDONLY)) { if (tTd(38, 4)) sm_dprintf("openmap()\t%s:%s %s: valid\n", map->map_class->map_cname == NULL ? "NULL" : map->map_class->map_cname, map->map_mname == NULL ? "NULL" : map->map_mname, map->map_file == NULL ? "NULL" : map->map_file); map->map_mflags |= MF_OPEN; map->map_pid = CurrentPid; } else { if (tTd(38, 4)) sm_dprintf("openmap()\t%s:%s %s: invalid%s%s\n", map->map_class->map_cname == NULL ? "NULL" : map->map_class->map_cname, map->map_mname == NULL ? "NULL" : map->map_mname, map->map_file == NULL ? "NULL" : map->map_file, errno == 0 ? "" : ": ", errno == 0 ? "" : sm_errstring(errno)); if (!bitset(MF_OPTIONAL, map->map_mflags)) { extern MAPCLASS BogusMapClass; map->map_orgclass = map->map_class; map->map_class = &BogusMapClass; map->map_mflags |= MF_OPEN|MF_OPENBOGUS; map->map_pid = CurrentPid; } else { /* don't try again */ map->map_mflags &= ~MF_VALID; } } if (restore) { Errors = saveerrors; HoldErrs = savehold; QuickAbort = savequick; } return bitset(MF_OPEN, map->map_mflags); } /* ** CLOSEMAPS -- close all open maps opened by the current pid. ** ** Parameters: ** bogus -- only close bogus maps. ** ** Returns: ** none. */ void closemaps(bogus) bool bogus; { stabapply(map_close, bogus); } /* ** MAP_CLOSE -- close a map opened by the current pid. ** ** Parameters: ** s -- STAB entry: if map: try to close ** bogus -- only close bogus maps or MCF_NOTPERSIST maps. ** ** Returns: ** none. */ /* ARGSUSED1 */ static void map_close(s, bogus) register STAB *s; int bogus; /* int because of stabapply(), used as bool */ { MAP *map; extern MAPCLASS BogusMapClass; if (s->s_symtype != ST_MAP) return; map = &s->s_map; /* ** close the map iff: ** it is valid and open and opened by this process ** and (!bogus or it's a bogus map or it is not persistent) ** negate this: return iff ** it is not valid or it is not open or not opened by this process ** or (bogus and it's not a bogus map and it's not not-persistent) */ if (!bitset(MF_VALID, map->map_mflags) || !bitset(MF_OPEN, map->map_mflags) || bitset(MF_CLOSING, map->map_mflags) || map->map_pid != CurrentPid || (bogus && map->map_class != &BogusMapClass && !bitset(MCF_NOTPERSIST, map->map_class->map_cflags))) return; if (map->map_class == &BogusMapClass && map->map_orgclass != NULL && map->map_orgclass != &BogusMapClass) map->map_class = map->map_orgclass; if (tTd(38, 5)) sm_dprintf("closemaps: closing %s (%s)\n", map->map_mname == NULL ? "NULL" : map->map_mname, map->map_file == NULL ? "NULL" : map->map_file); if (!bitset(MF_OPENBOGUS, map->map_mflags)) { map->map_mflags |= MF_CLOSING; map->map_class->map_close(map); } map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_OPENBOGUS|MF_CLOSING); } #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) extern int getdomainname(); /* this is mainly for backward compatibility in Sun environment */ static char * sun_init_domain() { /* ** Get the domain name from the kernel. ** If it does not start with a leading dot, then remove ** the first component. Since leading dots are funny Unix ** files, we treat a leading "+" the same as a leading dot. ** Finally, force there to be at least one dot in the domain name ** (i.e. top-level domains are not allowed, like "com", must be ** something like "sun.com"). */ char buf[MAXNAME]; char *period, *autodomain; if (getdomainname(buf, sizeof buf) < 0) return NULL; if (buf[0] == '\0') return NULL; if (tTd(0, 20)) printf("domainname = %s\n", buf); if (buf[0] == '+') buf[0] = '.'; period = strchr(buf, '.'); if (period == NULL) autodomain = buf; else autodomain = period + 1; if (strchr(autodomain, '.') == NULL) return newstr(buf); else return newstr(autodomain); } #endif /* SUN_EXTENSIONS && SUN_INIT_DOMAIN */ /* ** GETCANONNAME -- look up name using service switch ** ** Parameters: ** host -- the host name to look up. ** hbsize -- the size of the host buffer. ** trymx -- if set, try MX records. ** pttl -- pointer to return TTL (can be NULL). ** ** Returns: ** true -- if the host was found. ** false -- otherwise. */ bool getcanonname(host, hbsize, trymx, pttl) char *host; int hbsize; bool trymx; int *pttl; { int nmaps; int mapno; bool found = false; bool got_tempfail = false; auto int status = EX_UNAVAILABLE; char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) bool should_try_nis_domain = false; static char *nis_domain = NULL; #endif nmaps = switch_map_find("hosts", maptype, mapreturn); if (pttl != 0) *pttl = SM_DEFAULT_TTL; for (mapno = 0; mapno < nmaps; mapno++) { int i; if (tTd(38, 20)) sm_dprintf("getcanonname(%s), trying %s\n", host, maptype[mapno]); if (strcmp("files", maptype[mapno]) == 0) { found = text_getcanonname(host, hbsize, &status); } #if NIS else if (strcmp("nis", maptype[mapno]) == 0) { found = nis_getcanonname(host, hbsize, &status); # if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) if (nis_domain == NULL) nis_domain = sun_init_domain(); # endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */ } #endif /* NIS */ #if NISPLUS else if (strcmp("nisplus", maptype[mapno]) == 0) { found = nisplus_getcanonname(host, hbsize, &status); # if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) if (nis_domain == NULL) nis_domain = sun_init_domain(); # endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */ } #endif /* NISPLUS */ #if NAMED_BIND else if (strcmp("dns", maptype[mapno]) == 0) { found = dns_getcanonname(host, hbsize, trymx, &status, pttl); } #endif /* NAMED_BIND */ #if NETINFO else if (strcmp("netinfo", maptype[mapno]) == 0) { found = ni_getcanonname(host, hbsize, &status); } #endif /* NETINFO */ else { found = false; status = EX_UNAVAILABLE; } /* ** Heuristic: if $m is not set, we are running during system ** startup. In this case, when a name is apparently found ** but has no dot, treat is as not found. This avoids ** problems if /etc/hosts has no FQDN but is listed first ** in the service switch. */ if (found && (macvalue('m', CurEnv) != NULL || strchr(host, '.') != NULL)) break; #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) if (found) should_try_nis_domain = true; /* but don't break, as we need to try all methods first */ #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */ /* see if we should continue */ if (status == EX_TEMPFAIL) { i = MA_TRYAGAIN; got_tempfail = true; } else if (status == EX_NOTFOUND) i = MA_NOTFOUND; else i = MA_UNAVAIL; if (bitset(1 << mapno, mapreturn[i])) break; } if (found) { char *d; if (tTd(38, 20)) sm_dprintf("getcanonname(%s), found\n", host); /* ** If returned name is still single token, compensate ** by tagging on $m. This is because some sites set ** up their DNS or NIS databases wrong. */ if ((d = strchr(host, '.')) == NULL || d[1] == '\0') { d = macvalue('m', CurEnv); if (d != NULL && hbsize > (int) (strlen(host) + strlen(d) + 1)) { if (host[strlen(host) - 1] != '.') (void) sm_strlcat2(host, ".", d, hbsize); else (void) sm_strlcat(host, d, hbsize); } else { #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) if (VendorCode == VENDOR_SUN && should_try_nis_domain) { goto try_nis_domain; } #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */ return false; } } return true; } #if defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) if (VendorCode == VENDOR_SUN && should_try_nis_domain) { try_nis_domain: if (nis_domain != NULL && strlen(nis_domain) + strlen(host) + 1 < hbsize) { (void) sm_strlcat2(host, ".", nis_domain, hbsize); return true; } } #endif /* defined(SUN_EXTENSIONS) && defined(SUN_INIT_DOMAIN) */ if (tTd(38, 20)) sm_dprintf("getcanonname(%s), failed, status=%d\n", host, status); if (got_tempfail) SM_SET_H_ERRNO(TRY_AGAIN); else SM_SET_H_ERRNO(HOST_NOT_FOUND); return false; } /* ** EXTRACT_CANONNAME -- extract canonical name from /etc/hosts entry ** ** Parameters: ** name -- the name against which to match. ** dot -- where to reinsert '.' to get FQDN ** line -- the /etc/hosts line. ** cbuf -- the location to store the result. ** cbuflen -- the size of cbuf. ** ** Returns: ** true -- if the line matched the desired name. ** false -- otherwise. */ static bool extract_canonname(name, dot, line, cbuf, cbuflen) char *name; char *dot; char *line; char cbuf[]; int cbuflen; { int i; char *p; bool found = false; cbuf[0] = '\0'; if (line[0] == '#') return false; for (i = 1; ; i++) { char nbuf[MAXNAME + 1]; p = get_column(line, i, '\0', nbuf, sizeof(nbuf)); if (p == NULL) break; if (*p == '\0') continue; if (cbuf[0] == '\0' || (strchr(cbuf, '.') == NULL && strchr(p, '.') != NULL)) { (void) sm_strlcpy(cbuf, p, cbuflen); } if (sm_strcasecmp(name, p) == 0) found = true; else if (dot != NULL) { /* try looking for the FQDN as well */ *dot = '.'; if (sm_strcasecmp(name, p) == 0) found = true; *dot = '\0'; } } if (found && strchr(cbuf, '.') == NULL) { /* try to add a domain on the end of the name */ char *domain = macvalue('m', CurEnv); if (domain != NULL && strlen(domain) + (i = strlen(cbuf)) + 1 < (size_t) cbuflen) { p = &cbuf[i]; *p++ = '.'; (void) sm_strlcpy(p, domain, cbuflen - i - 1); } } return found; } /* ** DNS modules */ #if NAMED_BIND # if DNSMAP # include "sm_resolve.h" # if NETINET || NETINET6 # include # endif /* NETINET || NETINET6 */ /* ** DNS_MAP_OPEN -- stub to check proper value for dns map type */ bool dns_map_open(map, mode) MAP *map; int mode; { if (tTd(38,2)) sm_dprintf("dns_map_open(%s, %d)\n", map->map_mname, mode); mode &= O_ACCMODE; if (mode != O_RDONLY) { /* issue a pseudo-error message */ errno = SM_EMAPCANTWRITE; return false; } return true; } /* ** DNS_MAP_PARSEARGS -- parse dns map definition args. ** ** Parameters: ** map -- pointer to MAP ** args -- pointer to the args on the config line. ** ** Returns: ** true -- if everything parsed OK. ** false -- otherwise. */ #define map_sizelimit map_lockfd /* overload field */ struct dns_map { int dns_m_type; }; bool dns_map_parseargs(map,args) MAP *map; char *args; { register char *p = args; struct dns_map *map_p; map_p = (struct dns_map *) xalloc(sizeof(*map_p)); map_p->dns_m_type = -1; map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL; for (;;) { while (isascii(*p) && isspace(*p)) p++; if (*p != '-') break; switch (*++p) { case 'N': map->map_mflags |= MF_INCLNULL; map->map_mflags &= ~MF_TRY0NULL; break; case 'O': map->map_mflags &= ~MF_TRY1NULL; break; case 'o': map->map_mflags |= MF_OPTIONAL; break; case 'f': map->map_mflags |= MF_NOFOLDCASE; break; case 'm': map->map_mflags |= MF_MATCHONLY; break; case 'A': map->map_mflags |= MF_APPEND; break; case 'q': map->map_mflags |= MF_KEEPQUOTES; break; case 't': map->map_mflags |= MF_NODEFER; break; case 'a': map->map_app = ++p; break; case 'T': map->map_tapp = ++p; break; case 'd': { char *h; ++p; h = strchr(p, ' '); if (h != NULL) *h = '\0'; map->map_timeout = convtime(p, 's'); if (h != NULL) *h = ' '; } break; case 'r': while (isascii(*++p) && isspace(*p)) continue; map->map_retry = atoi(p); break; case 'z': if (*++p != '\\') map->map_coldelim = *p; else { switch (*++p) { case 'n': map->map_coldelim = '\n'; break; case 't': map->map_coldelim = '\t'; break; default: map->map_coldelim = '\\'; } } break; case 'Z': while (isascii(*++p) && isspace(*p)) continue; map->map_sizelimit = atoi(p); break; /* Start of dns_map specific args */ case 'R': /* search field */ { char *h; while (isascii(*++p) && isspace(*p)) continue; h = strchr(p, ' '); if (h != NULL) *h = '\0'; map_p->dns_m_type = dns_string_to_type(p); if (h != NULL) *h = ' '; if (map_p->dns_m_type < 0) syserr("dns map %s: wrong type %s", map->map_mname, p); } break; case 'B': /* base domain */ { char *h; while (isascii(*++p) && isspace(*p)) continue; h = strchr(p, ' '); if (h != NULL) *h = '\0'; /* ** slight abuse of map->map_file; it isn't ** used otherwise in this map type. */ map->map_file = newstr(p); if (h != NULL) *h = ' '; } break; } while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; } if (map_p->dns_m_type < 0) syserr("dns map %s: missing -R type", map->map_mname); if (map->map_app != NULL) map->map_app = newstr(map->map_app); if (map->map_tapp != NULL) map->map_tapp = newstr(map->map_tapp); /* ** Assumption: assert(sizeof(int) <= sizeof(ARBPTR_T)); ** Even if this assumption is wrong, we use only one byte, ** so it doesn't really matter. */ map->map_db1 = (ARBPTR_T) map_p; return true; } /* ** DNS_MAP_LOOKUP -- perform dns map lookup. ** ** Parameters: ** map -- pointer to MAP ** name -- name to lookup ** av -- arguments to interpolate into buf. ** statp -- pointer to status (EX_) ** ** Returns: ** result of lookup if succeeded. ** NULL -- otherwise. */ char * dns_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { int resnum = 0; char *vp = NULL, *result = NULL; size_t vsize; struct dns_map *map_p; RESOURCE_RECORD_T *rr = NULL; DNS_REPLY_T *r = NULL; # if NETINET6 static char buf6[INET6_ADDRSTRLEN]; # endif /* NETINET6 */ if (tTd(38, 20)) sm_dprintf("dns_map_lookup(%s, %s)\n", map->map_mname, name); map_p = (struct dns_map *)(map->map_db1); if (map->map_file != NULL && *map->map_file != '\0') { size_t len; char *appdomain; len = strlen(map->map_file) + strlen(name) + 2; appdomain = (char *) sm_malloc(len); if (appdomain == NULL) { *statp = EX_UNAVAILABLE; return NULL; } (void) sm_strlcpyn(appdomain, len, 3, name, ".", map->map_file); r = dns_lookup_int(appdomain, C_IN, map_p->dns_m_type, map->map_timeout, map->map_retry); sm_free(appdomain); } else { r = dns_lookup_int(name, C_IN, map_p->dns_m_type, map->map_timeout, map->map_retry); } if (r == NULL) { result = NULL; if (h_errno == TRY_AGAIN || transienterror(errno)) *statp = EX_TEMPFAIL; else *statp = EX_NOTFOUND; goto cleanup; } *statp = EX_OK; for (rr = r->dns_r_head; rr != NULL; rr = rr->rr_next) { char *type = NULL; char *value = NULL; switch (rr->rr_type) { case T_NS: type = "T_NS"; value = rr->rr_u.rr_txt; break; case T_CNAME: type = "T_CNAME"; value = rr->rr_u.rr_txt; break; case T_AFSDB: type = "T_AFSDB"; value = rr->rr_u.rr_mx->mx_r_domain; break; case T_SRV: type = "T_SRV"; value = rr->rr_u.rr_srv->srv_r_target; break; case T_PTR: type = "T_PTR"; value = rr->rr_u.rr_txt; break; case T_TXT: type = "T_TXT"; value = rr->rr_u.rr_txt; break; case T_MX: type = "T_MX"; value = rr->rr_u.rr_mx->mx_r_domain; break; # if NETINET case T_A: type = "T_A"; value = inet_ntoa(*(rr->rr_u.rr_a)); break; # endif /* NETINET */ # if NETINET6 case T_AAAA: type = "T_AAAA"; value = anynet_ntop(rr->rr_u.rr_aaaa, buf6, sizeof(buf6)); break; # endif /* NETINET6 */ } (void) strreplnonprt(value, 'X'); if (map_p->dns_m_type != rr->rr_type) { if (tTd(38, 40)) sm_dprintf("\tskipping type %s (%d) value %s\n", type != NULL ? type : "", rr->rr_type, value != NULL ? value : ""); continue; } # if NETINET6 if (rr->rr_type == T_AAAA && value == NULL) { result = NULL; *statp = EX_DATAERR; if (tTd(38, 40)) sm_dprintf("\tbad T_AAAA conversion\n"); goto cleanup; } # endif /* NETINET6 */ if (tTd(38, 40)) sm_dprintf("\tfound type %s (%d) value %s\n", type != NULL ? type : "", rr->rr_type, value != NULL ? value : ""); if (value != NULL && (map->map_coldelim == '\0' || map->map_sizelimit == 1 || bitset(MF_MATCHONLY, map->map_mflags))) { /* Only care about the first match */ vp = newstr(value); break; } else if (vp == NULL) { /* First result */ vp = newstr(value); } else { /* concatenate the results */ int sz; char *new; sz = strlen(vp) + strlen(value) + 2; new = xalloc(sz); (void) sm_snprintf(new, sz, "%s%c%s", vp, map->map_coldelim, value); sm_free(vp); vp = new; if (map->map_sizelimit > 0 && ++resnum >= map->map_sizelimit) break; } } if (vp == NULL) { result = NULL; *statp = EX_NOTFOUND; if (tTd(38, 40)) sm_dprintf("\tno match found\n"); goto cleanup; } /* Cleanly truncate for rulesets */ truncate_at_delim(vp, PSBUFSIZE / 2, map->map_coldelim); vsize = strlen(vp); if (LogLevel > 9) sm_syslog(LOG_INFO, CurEnv->e_id, "dns %.100s => %s", name, vp); if (bitset(MF_MATCHONLY, map->map_mflags)) result = map_rewrite(map, name, strlen(name), NULL); else result = map_rewrite(map, vp, vsize, av); cleanup: if (vp != NULL) sm_free(vp); if (r != NULL) dns_free_data(r); return result; } # endif /* DNSMAP */ #endif /* NAMED_BIND */ /* ** NDBM modules */ #if NDBM /* ** NDBM_MAP_OPEN -- DBM-style map open */ bool ndbm_map_open(map, mode) MAP *map; int mode; { register DBM *dbm; int save_errno; int dfd; int pfd; long sff; int ret; int smode = S_IREAD; char dirfile[MAXPATHLEN]; char pagfile[MAXPATHLEN]; struct stat st; struct stat std, stp; if (tTd(38, 2)) sm_dprintf("ndbm_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); map->map_lockfd = -1; mode &= O_ACCMODE; /* do initial file and directory checks */ if (sm_strlcpyn(dirfile, sizeof(dirfile), 2, map->map_file, ".dir") >= sizeof(dirfile) || sm_strlcpyn(pagfile, sizeof(pagfile), 2, map->map_file, ".pag") >= sizeof(pagfile)) { errno = 0; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("dbm map \"%s\": map file %s name too long", map->map_mname, map->map_file); return false; } sff = SFF_ROOTOK|SFF_REGONLY; if (mode == O_RDWR) { sff |= SFF_CREAT; if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail)) sff |= SFF_NOSLINK; if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail)) sff |= SFF_NOHLINK; smode = S_IWRITE; } else { if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; } if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_SAFEDIRPATH; ret = safefile(dirfile, RunAsUid, RunAsGid, RunAsUserName, sff, smode, &std); if (ret == 0) ret = safefile(pagfile, RunAsUid, RunAsGid, RunAsUserName, sff, smode, &stp); if (ret != 0) { char *prob = "unsafe"; /* cannot open this map */ if (ret == ENOENT) prob = "missing"; if (tTd(38, 2)) sm_dprintf("\t%s map file: %d\n", prob, ret); if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("dbm map \"%s\": %s map file %s", map->map_mname, prob, map->map_file); return false; } if (std.st_mode == ST_MODE_NOFILE) mode |= O_CREAT|O_EXCL; # if LOCK_ON_OPEN if (mode == O_RDONLY) mode |= O_SHLOCK; else mode |= O_TRUNC|O_EXLOCK; # else /* LOCK_ON_OPEN */ if ((mode & O_ACCMODE) == O_RDWR) { # if NOFTRUNCATE /* ** Warning: race condition. Try to lock the file as ** quickly as possible after opening it. ** This may also have security problems on some systems, ** but there isn't anything we can do about it. */ mode |= O_TRUNC; # else /* NOFTRUNCATE */ /* ** This ugly code opens the map without truncating it, ** locks the file, then truncates it. Necessary to ** avoid race conditions. */ int dirfd; int pagfd; long sff = SFF_CREAT|SFF_OPENASROOT; if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail)) sff |= SFF_NOSLINK; if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail)) sff |= SFF_NOHLINK; dirfd = safeopen(dirfile, mode, DBMMODE, sff); pagfd = safeopen(pagfile, mode, DBMMODE, sff); if (dirfd < 0 || pagfd < 0) { save_errno = errno; if (dirfd >= 0) (void) close(dirfd); if (pagfd >= 0) (void) close(pagfd); errno = save_errno; syserr("ndbm_map_open: cannot create database %s", map->map_file); return false; } if (ftruncate(dirfd, (off_t) 0) < 0 || ftruncate(pagfd, (off_t) 0) < 0) { save_errno = errno; (void) close(dirfd); (void) close(pagfd); errno = save_errno; syserr("ndbm_map_open: cannot truncate %s.{dir,pag}", map->map_file); return false; } /* if new file, get "before" bits for later filechanged check */ if (std.st_mode == ST_MODE_NOFILE && (fstat(dirfd, &std) < 0 || fstat(pagfd, &stp) < 0)) { save_errno = errno; (void) close(dirfd); (void) close(pagfd); errno = save_errno; syserr("ndbm_map_open(%s.{dir,pag}): cannot fstat pre-opened file", map->map_file); return false; } /* have to save the lock for the duration (bletch) */ map->map_lockfd = dirfd; (void) close(pagfd); /* twiddle bits for dbm_open */ mode &= ~(O_CREAT|O_EXCL); # endif /* NOFTRUNCATE */ } # endif /* LOCK_ON_OPEN */ /* open the database */ dbm = dbm_open(map->map_file, mode, DBMMODE); if (dbm == NULL) { save_errno = errno; if (bitset(MF_ALIAS, map->map_mflags) && aliaswait(map, ".pag", false)) return true; # if !LOCK_ON_OPEN && !NOFTRUNCATE if (map->map_lockfd >= 0) (void) close(map->map_lockfd); # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */ errno = save_errno; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("Cannot open DBM database %s", map->map_file); return false; } dfd = dbm_dirfno(dbm); pfd = dbm_pagfno(dbm); if (dfd == pfd) { /* heuristic: if files are linked, this is actually gdbm */ dbm_close(dbm); # if !LOCK_ON_OPEN && !NOFTRUNCATE if (map->map_lockfd >= 0) (void) close(map->map_lockfd); # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */ errno = 0; syserr("dbm map \"%s\": cannot support GDBM", map->map_mname); return false; } if (filechanged(dirfile, dfd, &std) || filechanged(pagfile, pfd, &stp)) { save_errno = errno; dbm_close(dbm); # if !LOCK_ON_OPEN && !NOFTRUNCATE if (map->map_lockfd >= 0) (void) close(map->map_lockfd); # endif /* !LOCK_ON_OPEN && !NOFTRUNCATE */ errno = save_errno; syserr("ndbm_map_open(%s): file changed after open", map->map_file); return false; } map->map_db1 = (ARBPTR_T) dbm; /* ** Need to set map_mtime before the call to aliaswait() ** as aliaswait() will call map_lookup() which requires ** map_mtime to be set */ if (fstat(pfd, &st) >= 0) map->map_mtime = st.st_mtime; if (mode == O_RDONLY) { # if LOCK_ON_OPEN if (dfd >= 0) (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN); if (pfd >= 0) (void) lockfile(pfd, map->map_file, ".pag", LOCK_UN); # endif /* LOCK_ON_OPEN */ if (bitset(MF_ALIAS, map->map_mflags) && !aliaswait(map, ".pag", true)) return false; } else { map->map_mflags |= MF_LOCKED; if (geteuid() == 0 && TrustedUid != 0) { # if HASFCHOWN if (fchown(dfd, TrustedUid, -1) < 0 || fchown(pfd, TrustedUid, -1) < 0) { int err = errno; sm_syslog(LOG_ALERT, NOQID, "ownership change on %s failed: %s", map->map_file, sm_errstring(err)); message("050 ownership change on %s failed: %s", map->map_file, sm_errstring(err)); } # else /* HASFCHOWN */ sm_syslog(LOG_ALERT, NOQID, "no fchown(): cannot change ownership on %s", map->map_file); message("050 no fchown(): cannot change ownership on %s", map->map_file); # endif /* HASFCHOWN */ } } return true; } /* ** NDBM_MAP_LOOKUP -- look up a datum in a DBM-type map */ char * ndbm_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { datum key, val; int dfd, pfd; char keybuf[MAXNAME + 1]; struct stat stbuf; if (tTd(38, 20)) sm_dprintf("ndbm_map_lookup(%s, %s)\n", map->map_mname, name); key.dptr = name; key.dsize = strlen(name); if (!bitset(MF_NOFOLDCASE, map->map_mflags)) { if (key.dsize > sizeof(keybuf) - 1) key.dsize = sizeof(keybuf) - 1; memmove(keybuf, key.dptr, key.dsize); keybuf[key.dsize] = '\0'; makelower(keybuf); key.dptr = keybuf; } lockdbm: dfd = dbm_dirfno((DBM *) map->map_db1); if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags)) (void) lockfile(dfd, map->map_file, ".dir", LOCK_SH); pfd = dbm_pagfno((DBM *) map->map_db1); if (pfd < 0 || fstat(pfd, &stbuf) < 0 || stbuf.st_mtime > map->map_mtime) { /* Reopen the database to sync the cache */ int omode = bitset(map->map_mflags, MF_WRITABLE) ? O_RDWR : O_RDONLY; if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags)) (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN); map->map_mflags |= MF_CLOSING; map->map_class->map_close(map); map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING); if (map->map_class->map_open(map, omode)) { map->map_mflags |= MF_OPEN; map->map_pid = CurrentPid; if ((omode & O_ACCMODE) == O_RDWR) map->map_mflags |= MF_WRITABLE; goto lockdbm; } else { if (!bitset(MF_OPTIONAL, map->map_mflags)) { extern MAPCLASS BogusMapClass; *statp = EX_TEMPFAIL; map->map_orgclass = map->map_class; map->map_class = &BogusMapClass; map->map_mflags |= MF_OPEN; map->map_pid = CurrentPid; syserr("Cannot reopen NDBM database %s", map->map_file); } return NULL; } } val.dptr = NULL; if (bitset(MF_TRY0NULL, map->map_mflags)) { val = dbm_fetch((DBM *) map->map_db1, key); if (val.dptr != NULL) map->map_mflags &= ~MF_TRY1NULL; } if (val.dptr == NULL && bitset(MF_TRY1NULL, map->map_mflags)) { key.dsize++; val = dbm_fetch((DBM *) map->map_db1, key); if (val.dptr != NULL) map->map_mflags &= ~MF_TRY0NULL; } if (dfd >= 0 && !bitset(MF_LOCKED, map->map_mflags)) (void) lockfile(dfd, map->map_file, ".dir", LOCK_UN); if (val.dptr == NULL) return NULL; if (bitset(MF_MATCHONLY, map->map_mflags)) return map_rewrite(map, name, strlen(name), NULL); else return map_rewrite(map, val.dptr, val.dsize, av); } /* ** NDBM_MAP_STORE -- store a datum in the database */ void ndbm_map_store(map, lhs, rhs) register MAP *map; char *lhs; char *rhs; { datum key; datum data; int status; char keybuf[MAXNAME + 1]; if (tTd(38, 12)) sm_dprintf("ndbm_map_store(%s, %s, %s)\n", map->map_mname, lhs, rhs); key.dsize = strlen(lhs); key.dptr = lhs; if (!bitset(MF_NOFOLDCASE, map->map_mflags)) { if (key.dsize > sizeof(keybuf) - 1) key.dsize = sizeof(keybuf) - 1; memmove(keybuf, key.dptr, key.dsize); keybuf[key.dsize] = '\0'; makelower(keybuf); key.dptr = keybuf; } data.dsize = strlen(rhs); data.dptr = rhs; if (bitset(MF_INCLNULL, map->map_mflags)) { key.dsize++; data.dsize++; } status = dbm_store((DBM *) map->map_db1, key, data, DBM_INSERT); if (status > 0) { if (!bitset(MF_APPEND, map->map_mflags)) message("050 Warning: duplicate alias name %s", lhs); else { static char *buf = NULL; static int bufsiz = 0; auto int xstat; datum old; old.dptr = ndbm_map_lookup(map, key.dptr, (char **) NULL, &xstat); if (old.dptr != NULL && *(char *) old.dptr != '\0') { old.dsize = strlen(old.dptr); if (data.dsize + old.dsize + 2 > bufsiz) { if (buf != NULL) (void) sm_free(buf); bufsiz = data.dsize + old.dsize + 2; buf = sm_pmalloc_x(bufsiz); } (void) sm_strlcpyn(buf, bufsiz, 3, data.dptr, ",", old.dptr); data.dsize = data.dsize + old.dsize + 1; data.dptr = buf; if (tTd(38, 9)) sm_dprintf("ndbm_map_store append=%s\n", data.dptr); } } status = dbm_store((DBM *) map->map_db1, key, data, DBM_REPLACE); } if (status != 0) syserr("readaliases: dbm put (%s): %d", lhs, status); } /* ** NDBM_MAP_CLOSE -- close the database */ void ndbm_map_close(map) register MAP *map; { if (tTd(38, 9)) sm_dprintf("ndbm_map_close(%s, %s, %lx)\n", map->map_mname, map->map_file, map->map_mflags); if (bitset(MF_WRITABLE, map->map_mflags)) { # ifdef NDBM_YP_COMPAT bool inclnull; char buf[MAXHOSTNAMELEN]; inclnull = bitset(MF_INCLNULL, map->map_mflags); map->map_mflags &= ~MF_INCLNULL; if (strstr(map->map_file, "/yp/") != NULL) { long save_mflags = map->map_mflags; map->map_mflags |= MF_NOFOLDCASE; (void) sm_snprintf(buf, sizeof(buf), "%010ld", curtime()); ndbm_map_store(map, "YP_LAST_MODIFIED", buf); (void) gethostname(buf, sizeof(buf)); ndbm_map_store(map, "YP_MASTER_NAME", buf); map->map_mflags = save_mflags; } if (inclnull) map->map_mflags |= MF_INCLNULL; # endif /* NDBM_YP_COMPAT */ /* write out the distinguished alias */ ndbm_map_store(map, "@", "@"); } dbm_close((DBM *) map->map_db1); /* release lock (if needed) */ # if !LOCK_ON_OPEN if (map->map_lockfd >= 0) (void) close(map->map_lockfd); # endif /* !LOCK_ON_OPEN */ } #endif /* NDBM */ /* ** NEWDB (Hash and BTree) Modules */ #if NEWDB /* ** BT_MAP_OPEN, HASH_MAP_OPEN -- database open primitives. ** ** These do rather bizarre locking. If you can lock on open, ** do that to avoid the condition of opening a database that ** is being rebuilt. If you don't, we'll try to fake it, but ** there will be a race condition. If opening for read-only, ** we immediately release the lock to avoid freezing things up. ** We really ought to hold the lock, but guarantee that we won't ** be pokey about it. That's hard to do. */ /* these should be K line arguments */ # if DB_VERSION_MAJOR < 2 # define db_cachesize cachesize # define h_nelem nelem # ifndef DB_CACHE_SIZE # define DB_CACHE_SIZE (1024 * 1024) /* database memory cache size */ # endif /* ! DB_CACHE_SIZE */ # ifndef DB_HASH_NELEM # define DB_HASH_NELEM 4096 /* (starting) size of hash table */ # endif /* ! DB_HASH_NELEM */ # endif /* DB_VERSION_MAJOR < 2 */ bool bt_map_open(map, mode) MAP *map; int mode; { # if DB_VERSION_MAJOR < 2 BTREEINFO btinfo; # endif /* DB_VERSION_MAJOR < 2 */ # if DB_VERSION_MAJOR == 2 DB_INFO btinfo; # endif /* DB_VERSION_MAJOR == 2 */ # if DB_VERSION_MAJOR > 2 void *btinfo = NULL; # endif /* DB_VERSION_MAJOR > 2 */ if (tTd(38, 2)) sm_dprintf("bt_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); # if DB_VERSION_MAJOR < 3 memset(&btinfo, '\0', sizeof(btinfo)); # ifdef DB_CACHE_SIZE btinfo.db_cachesize = DB_CACHE_SIZE; # endif /* DB_CACHE_SIZE */ # endif /* DB_VERSION_MAJOR < 3 */ return db_map_open(map, mode, "btree", DB_BTREE, &btinfo); } bool hash_map_open(map, mode) MAP *map; int mode; { # if DB_VERSION_MAJOR < 2 HASHINFO hinfo; # endif /* DB_VERSION_MAJOR < 2 */ # if DB_VERSION_MAJOR == 2 DB_INFO hinfo; # endif /* DB_VERSION_MAJOR == 2 */ # if DB_VERSION_MAJOR > 2 void *hinfo = NULL; # endif /* DB_VERSION_MAJOR > 2 */ if (tTd(38, 2)) sm_dprintf("hash_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); # if DB_VERSION_MAJOR < 3 memset(&hinfo, '\0', sizeof(hinfo)); # ifdef DB_HASH_NELEM hinfo.h_nelem = DB_HASH_NELEM; # endif /* DB_HASH_NELEM */ # ifdef DB_CACHE_SIZE hinfo.db_cachesize = DB_CACHE_SIZE; # endif /* DB_CACHE_SIZE */ # endif /* DB_VERSION_MAJOR < 3 */ return db_map_open(map, mode, "hash", DB_HASH, &hinfo); } static bool db_map_open(map, mode, mapclassname, dbtype, openinfo) MAP *map; int mode; char *mapclassname; DBTYPE dbtype; # if DB_VERSION_MAJOR < 2 const void *openinfo; # endif /* DB_VERSION_MAJOR < 2 */ # if DB_VERSION_MAJOR == 2 DB_INFO *openinfo; # endif /* DB_VERSION_MAJOR == 2 */ # if DB_VERSION_MAJOR > 2 void **openinfo; # endif /* DB_VERSION_MAJOR > 2 */ { DB *db = NULL; int i; int omode; int smode = S_IREAD; int fd; long sff; int save_errno; struct stat st; char buf[MAXPATHLEN]; /* do initial file and directory checks */ if (sm_strlcpy(buf, map->map_file, sizeof(buf)) >= sizeof(buf)) { errno = 0; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("map \"%s\": map file %s name too long", map->map_mname, map->map_file); return false; } i = strlen(buf); if (i < 3 || strcmp(&buf[i - 3], ".db") != 0) { if (sm_strlcat(buf, ".db", sizeof(buf)) >= sizeof(buf)) { errno = 0; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("map \"%s\": map file %s name too long", map->map_mname, map->map_file); return false; } } mode &= O_ACCMODE; omode = mode; sff = SFF_ROOTOK|SFF_REGONLY; if (mode == O_RDWR) { sff |= SFF_CREAT; if (!bitnset(DBS_WRITEMAPTOSYMLINK, DontBlameSendmail)) sff |= SFF_NOSLINK; if (!bitnset(DBS_WRITEMAPTOHARDLINK, DontBlameSendmail)) sff |= SFF_NOHLINK; smode = S_IWRITE; } else { if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; } if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_SAFEDIRPATH; i = safefile(buf, RunAsUid, RunAsGid, RunAsUserName, sff, smode, &st); if (i != 0) { char *prob = "unsafe"; /* cannot open this map */ if (i == ENOENT) prob = "missing"; if (tTd(38, 2)) sm_dprintf("\t%s map file: %s\n", prob, sm_errstring(i)); errno = i; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("%s map \"%s\": %s map file %s", mapclassname, map->map_mname, prob, buf); return false; } if (st.st_mode == ST_MODE_NOFILE) omode |= O_CREAT|O_EXCL; map->map_lockfd = -1; # if LOCK_ON_OPEN if (mode == O_RDWR) omode |= O_TRUNC|O_EXLOCK; else omode |= O_SHLOCK; # else /* LOCK_ON_OPEN */ /* ** Pre-lock the file to avoid race conditions. In particular, ** since dbopen returns NULL if the file is zero length, we ** must have a locked instance around the dbopen. */ fd = open(buf, omode, DBMMODE); if (fd < 0) { if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("db_map_open: cannot pre-open database %s", buf); return false; } /* make sure no baddies slipped in just before the open... */ if (filechanged(buf, fd, &st)) { save_errno = errno; (void) close(fd); errno = save_errno; syserr("db_map_open(%s): file changed after pre-open", buf); return false; } /* if new file, get the "before" bits for later filechanged check */ if (st.st_mode == ST_MODE_NOFILE && fstat(fd, &st) < 0) { save_errno = errno; (void) close(fd); errno = save_errno; syserr("db_map_open(%s): cannot fstat pre-opened file", buf); return false; } /* actually lock the pre-opened file */ if (!lockfile(fd, buf, NULL, mode == O_RDONLY ? LOCK_SH : LOCK_EX)) syserr("db_map_open: cannot lock %s", buf); /* set up mode bits for dbopen */ if (mode == O_RDWR) omode |= O_TRUNC; omode &= ~(O_EXCL|O_CREAT); # endif /* LOCK_ON_OPEN */ # if DB_VERSION_MAJOR < 2 db = dbopen(buf, omode, DBMMODE, dbtype, openinfo); # else /* DB_VERSION_MAJOR < 2 */ { int flags = 0; # if DB_VERSION_MAJOR > 2 int ret; # endif /* DB_VERSION_MAJOR > 2 */ if (mode == O_RDONLY) flags |= DB_RDONLY; if (bitset(O_CREAT, omode)) flags |= DB_CREATE; if (bitset(O_TRUNC, omode)) flags |= DB_TRUNCATE; SM_DB_FLAG_ADD(flags); # if DB_VERSION_MAJOR > 2 ret = db_create(&db, NULL, 0); # ifdef DB_CACHE_SIZE if (ret == 0 && db != NULL) { ret = db->set_cachesize(db, 0, DB_CACHE_SIZE, 0); if (ret != 0) { (void) db->close(db, 0); db = NULL; } } # endif /* DB_CACHE_SIZE */ # ifdef DB_HASH_NELEM if (dbtype == DB_HASH && ret == 0 && db != NULL) { ret = db->set_h_nelem(db, DB_HASH_NELEM); if (ret != 0) { (void) db->close(db, 0); db = NULL; } } # endif /* DB_HASH_NELEM */ if (ret == 0 && db != NULL) { ret = db->open(db, DBTXN /* transaction for DB 4.1 */ buf, NULL, dbtype, flags, DBMMODE); if (ret != 0) { #ifdef DB_OLD_VERSION if (ret == DB_OLD_VERSION) ret = EINVAL; #endif /* DB_OLD_VERSION */ (void) db->close(db, 0); db = NULL; } } errno = ret; # else /* DB_VERSION_MAJOR > 2 */ errno = db_open(buf, dbtype, flags, DBMMODE, NULL, openinfo, &db); # endif /* DB_VERSION_MAJOR > 2 */ } # endif /* DB_VERSION_MAJOR < 2 */ save_errno = errno; # if !LOCK_ON_OPEN if (mode == O_RDWR) map->map_lockfd = fd; else (void) close(fd); # endif /* !LOCK_ON_OPEN */ if (db == NULL) { if (mode == O_RDONLY && bitset(MF_ALIAS, map->map_mflags) && aliaswait(map, ".db", false)) return true; # if !LOCK_ON_OPEN if (map->map_lockfd >= 0) (void) close(map->map_lockfd); # endif /* !LOCK_ON_OPEN */ errno = save_errno; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("Cannot open %s database %s", mapclassname, buf); return false; } # if DB_VERSION_MAJOR < 2 fd = db->fd(db); # else /* DB_VERSION_MAJOR < 2 */ fd = -1; errno = db->fd(db, &fd); # endif /* DB_VERSION_MAJOR < 2 */ if (filechanged(buf, fd, &st)) { save_errno = errno; # if DB_VERSION_MAJOR < 2 (void) db->close(db); # else /* DB_VERSION_MAJOR < 2 */ errno = db->close(db, 0); # endif /* DB_VERSION_MAJOR < 2 */ # if !LOCK_ON_OPEN if (map->map_lockfd >= 0) (void) close(map->map_lockfd); # endif /* !LOCK_ON_OPEN */ errno = save_errno; syserr("db_map_open(%s): file changed after open", buf); return false; } if (mode == O_RDWR) map->map_mflags |= MF_LOCKED; # if LOCK_ON_OPEN if (fd >= 0 && mode == O_RDONLY) { (void) lockfile(fd, buf, NULL, LOCK_UN); } # endif /* LOCK_ON_OPEN */ /* try to make sure that at least the database header is on disk */ if (mode == O_RDWR) { (void) db->sync(db, 0); if (geteuid() == 0 && TrustedUid != 0) { # if HASFCHOWN if (fchown(fd, TrustedUid, -1) < 0) { int err = errno; sm_syslog(LOG_ALERT, NOQID, "ownership change on %s failed: %s", buf, sm_errstring(err)); message("050 ownership change on %s failed: %s", buf, sm_errstring(err)); } # else /* HASFCHOWN */ sm_syslog(LOG_ALERT, NOQID, "no fchown(): cannot change ownership on %s", map->map_file); message("050 no fchown(): cannot change ownership on %s", map->map_file); # endif /* HASFCHOWN */ } } map->map_db2 = (ARBPTR_T) db; /* ** Need to set map_mtime before the call to aliaswait() ** as aliaswait() will call map_lookup() which requires ** map_mtime to be set */ if (fd >= 0 && fstat(fd, &st) >= 0) map->map_mtime = st.st_mtime; if (mode == O_RDONLY && bitset(MF_ALIAS, map->map_mflags) && !aliaswait(map, ".db", true)) return false; return true; } /* ** DB_MAP_LOOKUP -- look up a datum in a BTREE- or HASH-type map */ char * db_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { DBT key, val; register DB *db = (DB *) map->map_db2; int i; int st; int save_errno; int fd; struct stat stbuf; char keybuf[MAXNAME + 1]; char buf[MAXPATHLEN]; memset(&key, '\0', sizeof(key)); memset(&val, '\0', sizeof(val)); if (tTd(38, 20)) sm_dprintf("db_map_lookup(%s, %s)\n", map->map_mname, name); if (sm_strlcpy(buf, map->map_file, sizeof(buf)) >= sizeof(buf)) { errno = 0; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("map \"%s\": map file %s name too long", map->map_mname, map->map_file); return NULL; } i = strlen(buf); if (i > 3 && strcmp(&buf[i - 3], ".db") == 0) buf[i - 3] = '\0'; key.size = strlen(name); if (key.size > sizeof(keybuf) - 1) key.size = sizeof(keybuf) - 1; key.data = keybuf; memmove(keybuf, name, key.size); keybuf[key.size] = '\0'; if (!bitset(MF_NOFOLDCASE, map->map_mflags)) makelower(keybuf); lockdb: # if DB_VERSION_MAJOR < 2 fd = db->fd(db); # else /* DB_VERSION_MAJOR < 2 */ fd = -1; errno = db->fd(db, &fd); # endif /* DB_VERSION_MAJOR < 2 */ if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags)) (void) lockfile(fd, buf, ".db", LOCK_SH); if (fd < 0 || fstat(fd, &stbuf) < 0 || stbuf.st_mtime > map->map_mtime) { /* Reopen the database to sync the cache */ int omode = bitset(map->map_mflags, MF_WRITABLE) ? O_RDWR : O_RDONLY; if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags)) (void) lockfile(fd, buf, ".db", LOCK_UN); map->map_mflags |= MF_CLOSING; map->map_class->map_close(map); map->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING); if (map->map_class->map_open(map, omode)) { map->map_mflags |= MF_OPEN; map->map_pid = CurrentPid; if ((omode & O_ACCMODE) == O_RDWR) map->map_mflags |= MF_WRITABLE; db = (DB *) map->map_db2; goto lockdb; } else { if (!bitset(MF_OPTIONAL, map->map_mflags)) { extern MAPCLASS BogusMapClass; *statp = EX_TEMPFAIL; map->map_orgclass = map->map_class; map->map_class = &BogusMapClass; map->map_mflags |= MF_OPEN; map->map_pid = CurrentPid; syserr("Cannot reopen DB database %s", map->map_file); } return NULL; } } st = 1; if (bitset(MF_TRY0NULL, map->map_mflags)) { # if DB_VERSION_MAJOR < 2 st = db->get(db, &key, &val, 0); # else /* DB_VERSION_MAJOR < 2 */ errno = db->get(db, NULL, &key, &val, 0); switch (errno) { case DB_NOTFOUND: case DB_KEYEMPTY: st = 1; break; case 0: st = 0; break; default: st = -1; break; } # endif /* DB_VERSION_MAJOR < 2 */ if (st == 0) map->map_mflags &= ~MF_TRY1NULL; } if (st != 0 && bitset(MF_TRY1NULL, map->map_mflags)) { key.size++; # if DB_VERSION_MAJOR < 2 st = db->get(db, &key, &val, 0); # else /* DB_VERSION_MAJOR < 2 */ errno = db->get(db, NULL, &key, &val, 0); switch (errno) { case DB_NOTFOUND: case DB_KEYEMPTY: st = 1; break; case 0: st = 0; break; default: st = -1; break; } # endif /* DB_VERSION_MAJOR < 2 */ if (st == 0) map->map_mflags &= ~MF_TRY0NULL; } save_errno = errno; if (fd >= 0 && !bitset(MF_LOCKED, map->map_mflags)) (void) lockfile(fd, buf, ".db", LOCK_UN); if (st != 0) { errno = save_errno; if (st < 0) syserr("db_map_lookup: get (%s)", name); return NULL; } if (bitset(MF_MATCHONLY, map->map_mflags)) return map_rewrite(map, name, strlen(name), NULL); else return map_rewrite(map, val.data, val.size, av); } /* ** DB_MAP_STORE -- store a datum in the NEWDB database */ void db_map_store(map, lhs, rhs) register MAP *map; char *lhs; char *rhs; { int status; DBT key; DBT data; register DB *db = map->map_db2; char keybuf[MAXNAME + 1]; memset(&key, '\0', sizeof(key)); memset(&data, '\0', sizeof(data)); if (tTd(38, 12)) sm_dprintf("db_map_store(%s, %s, %s)\n", map->map_mname, lhs, rhs); key.size = strlen(lhs); key.data = lhs; if (!bitset(MF_NOFOLDCASE, map->map_mflags)) { if (key.size > sizeof(keybuf) - 1) key.size = sizeof(keybuf) - 1; memmove(keybuf, key.data, key.size); keybuf[key.size] = '\0'; makelower(keybuf); key.data = keybuf; } data.size = strlen(rhs); data.data = rhs; if (bitset(MF_INCLNULL, map->map_mflags)) { key.size++; data.size++; } # if DB_VERSION_MAJOR < 2 status = db->put(db, &key, &data, R_NOOVERWRITE); # else /* DB_VERSION_MAJOR < 2 */ errno = db->put(db, NULL, &key, &data, DB_NOOVERWRITE); switch (errno) { case DB_KEYEXIST: status = 1; break; case 0: status = 0; break; default: status = -1; break; } # endif /* DB_VERSION_MAJOR < 2 */ if (status > 0) { if (!bitset(MF_APPEND, map->map_mflags)) message("050 Warning: duplicate alias name %s", lhs); else { static char *buf = NULL; static int bufsiz = 0; DBT old; memset(&old, '\0', sizeof(old)); old.data = db_map_lookup(map, key.data, (char **) NULL, &status); if (old.data != NULL) { old.size = strlen(old.data); if (data.size + old.size + 2 > (size_t) bufsiz) { if (buf != NULL) sm_free(buf); bufsiz = data.size + old.size + 2; buf = sm_pmalloc_x(bufsiz); } (void) sm_strlcpyn(buf, bufsiz, 3, (char *) data.data, ",", (char *) old.data); data.size = data.size + old.size + 1; data.data = buf; if (tTd(38, 9)) sm_dprintf("db_map_store append=%s\n", (char *) data.data); } } # if DB_VERSION_MAJOR < 2 status = db->put(db, &key, &data, 0); # else /* DB_VERSION_MAJOR < 2 */ status = errno = db->put(db, NULL, &key, &data, 0); # endif /* DB_VERSION_MAJOR < 2 */ } if (status != 0) syserr("readaliases: db put (%s)", lhs); } /* ** DB_MAP_CLOSE -- add distinguished entries and close the database */ void db_map_close(map) MAP *map; { register DB *db = map->map_db2; if (tTd(38, 9)) sm_dprintf("db_map_close(%s, %s, %lx)\n", map->map_mname, map->map_file, map->map_mflags); if (bitset(MF_WRITABLE, map->map_mflags)) { /* write out the distinguished alias */ db_map_store(map, "@", "@"); } (void) db->sync(db, 0); # if !LOCK_ON_OPEN if (map->map_lockfd >= 0) (void) close(map->map_lockfd); # endif /* !LOCK_ON_OPEN */ # if DB_VERSION_MAJOR < 2 if (db->close(db) != 0) # else /* DB_VERSION_MAJOR < 2 */ /* ** Berkeley DB can use internal shared memory ** locking for its memory pool. Closing a map ** opened by another process will interfere ** with the shared memory and locks of the parent ** process leaving things in a bad state. */ /* ** If this map was not opened by the current ** process, do not close the map but recover ** the file descriptor. */ if (map->map_pid != CurrentPid) { int fd = -1; errno = db->fd(db, &fd); if (fd >= 0) (void) close(fd); return; } if ((errno = db->close(db, 0)) != 0) # endif /* DB_VERSION_MAJOR < 2 */ syserr("db_map_close(%s, %s, %lx): db close failure", map->map_mname, map->map_file, map->map_mflags); } #endif /* NEWDB */ /* ** NIS Modules */ #if NIS # ifndef YPERR_BUSY # define YPERR_BUSY 16 # endif /* ! YPERR_BUSY */ /* ** NIS_MAP_OPEN -- open DBM map */ bool nis_map_open(map, mode) MAP *map; int mode; { int yperr; register char *p; auto char *vp; auto int vsize; if (tTd(38, 2)) sm_dprintf("nis_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); mode &= O_ACCMODE; if (mode != O_RDONLY) { /* issue a pseudo-error message */ errno = SM_EMAPCANTWRITE; return false; } p = strchr(map->map_file, '@'); if (p != NULL) { *p++ = '\0'; if (*p != '\0') map->map_domain = p; } if (*map->map_file == '\0') map->map_file = "mail.aliases"; if (map->map_domain == NULL) { yperr = yp_get_default_domain(&map->map_domain); if (yperr != 0) { if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("451 4.3.5 NIS map %s specified, but NIS not running", map->map_file); return false; } } /* check to see if this map actually exists */ vp = NULL; yperr = yp_match(map->map_domain, map->map_file, "@", 1, &vp, &vsize); if (tTd(38, 10)) sm_dprintf("nis_map_open: yp_match(@, %s, %s) => %s\n", map->map_domain, map->map_file, yperr_string(yperr)); if (vp != NULL) sm_free(vp); if (yperr == 0 || yperr == YPERR_KEY || yperr == YPERR_BUSY) { /* ** We ought to be calling aliaswait() here if this is an ** alias file, but powerful HP-UX NIS servers apparently ** don't insert the @:@ token into the alias map when it ** is rebuilt, so aliaswait() just hangs. I hate HP-UX. */ # if 0 if (!bitset(MF_ALIAS, map->map_mflags) || aliaswait(map, NULL, true)) # endif /* 0 */ return true; } if (!bitset(MF_OPTIONAL, map->map_mflags)) { syserr("451 4.3.5 Cannot bind to map %s in domain %s: %s", map->map_file, map->map_domain, yperr_string(yperr)); } return false; } /* ** NIS_MAP_LOOKUP -- look up a datum in a NIS map */ /* ARGSUSED3 */ char * nis_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { char *vp; auto int vsize; int buflen; int yperr; char keybuf[MAXNAME + 1]; char *SM_NONVOLATILE result = NULL; if (tTd(38, 20)) sm_dprintf("nis_map_lookup(%s, %s)\n", map->map_mname, name); buflen = strlen(name); if (buflen > sizeof(keybuf) - 1) buflen = sizeof(keybuf) - 1; memmove(keybuf, name, buflen); keybuf[buflen] = '\0'; if (!bitset(MF_NOFOLDCASE, map->map_mflags)) makelower(keybuf); yperr = YPERR_KEY; vp = NULL; if (bitset(MF_TRY0NULL, map->map_mflags)) { yperr = yp_match(map->map_domain, map->map_file, keybuf, buflen, &vp, &vsize); if (yperr == 0) map->map_mflags &= ~MF_TRY1NULL; } if (yperr == YPERR_KEY && bitset(MF_TRY1NULL, map->map_mflags)) { SM_FREE_CLR(vp); buflen++; yperr = yp_match(map->map_domain, map->map_file, keybuf, buflen, &vp, &vsize); if (yperr == 0) map->map_mflags &= ~MF_TRY0NULL; } if (yperr != 0) { if (yperr != YPERR_KEY && yperr != YPERR_BUSY) map->map_mflags &= ~(MF_VALID|MF_OPEN); if (vp != NULL) sm_free(vp); return NULL; } SM_TRY if (bitset(MF_MATCHONLY, map->map_mflags)) result = map_rewrite(map, name, strlen(name), NULL); else result = map_rewrite(map, vp, vsize, av); SM_FINALLY if (vp != NULL) sm_free(vp); SM_END_TRY return result; } /* ** NIS_GETCANONNAME -- look up canonical name in NIS */ static bool nis_getcanonname(name, hbsize, statp) char *name; int hbsize; int *statp; { char *vp; auto int vsize; int keylen; int yperr; static bool try0null = true; static bool try1null = true; static char *yp_domain = NULL; char host_record[MAXLINE]; char cbuf[MAXNAME]; char nbuf[MAXNAME + 1]; if (tTd(38, 20)) sm_dprintf("nis_getcanonname(%s)\n", name); if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf)) { *statp = EX_UNAVAILABLE; return false; } (void) shorten_hostname(nbuf); keylen = strlen(nbuf); if (yp_domain == NULL) (void) yp_get_default_domain(&yp_domain); makelower(nbuf); yperr = YPERR_KEY; vp = NULL; if (try0null) { yperr = yp_match(yp_domain, "hosts.byname", nbuf, keylen, &vp, &vsize); if (yperr == 0) try1null = false; } if (yperr == YPERR_KEY && try1null) { SM_FREE_CLR(vp); keylen++; yperr = yp_match(yp_domain, "hosts.byname", nbuf, keylen, &vp, &vsize); if (yperr == 0) try0null = false; } if (yperr != 0) { if (yperr == YPERR_KEY) *statp = EX_NOHOST; else if (yperr == YPERR_BUSY) *statp = EX_TEMPFAIL; else *statp = EX_UNAVAILABLE; if (vp != NULL) sm_free(vp); return false; } (void) sm_strlcpy(host_record, vp, sizeof(host_record)); sm_free(vp); if (tTd(38, 44)) sm_dprintf("got record `%s'\n", host_record); vp = strpbrk(host_record, "#\n"); if (vp != NULL) *vp = '\0'; if (!extract_canonname(nbuf, NULL, host_record, cbuf, sizeof(cbuf))) { /* this should not happen, but.... */ *statp = EX_NOHOST; return false; } if (sm_strlcpy(name, cbuf, hbsize) >= hbsize) { *statp = EX_UNAVAILABLE; return false; } *statp = EX_OK; return true; } #endif /* NIS */ /* ** NISPLUS Modules ** ** This code donated by Sun Microsystems. */ #if NISPLUS # undef NIS /* symbol conflict in nis.h */ # undef T_UNSPEC /* symbol conflict in nis.h -> ... -> sys/tiuser.h */ # include # include +# ifndef NIS_TABLE_OBJ +# define NIS_TABLE_OBJ TABLE_OBJ +# endif /* NIS_TABLE_OBJ */ # define EN_col(col) zo_data.objdata_u.en_data.en_cols.en_cols_val[(col)].ec_value.ec_value_val # define COL_NAME(res,i) ((res->objects.objects_val)->TA_data.ta_cols.ta_cols_val)[i].tc_name # define COL_MAX(res) ((res->objects.objects_val)->TA_data.ta_cols.ta_cols_len) # define PARTIAL_NAME(x) ((x)[strlen(x) - 1] != '.') /* ** NISPLUS_MAP_OPEN -- open nisplus table */ bool nisplus_map_open(map, mode) MAP *map; int mode; { nis_result *res = NULL; int retry_cnt, max_col, i; char qbuf[MAXLINE + NIS_MAXNAMELEN]; if (tTd(38, 2)) sm_dprintf("nisplus_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); mode &= O_ACCMODE; if (mode != O_RDONLY) { errno = EPERM; return false; } if (*map->map_file == '\0') map->map_file = "mail_aliases.org_dir"; if (PARTIAL_NAME(map->map_file) && map->map_domain == NULL) { /* set default NISPLUS Domain to $m */ map->map_domain = newstr(nisplus_default_domain()); if (tTd(38, 2)) sm_dprintf("nisplus_map_open(%s): using domain %s\n", map->map_file, map->map_domain); } if (!PARTIAL_NAME(map->map_file)) { map->map_domain = newstr(""); (void) sm_strlcpy(qbuf, map->map_file, sizeof(qbuf)); } else { /* check to see if this map actually exists */ (void) sm_strlcpyn(qbuf, sizeof(qbuf), 3, map->map_file, ".", map->map_domain); } retry_cnt = 0; while (res == NULL || res->status != NIS_SUCCESS) { res = nis_lookup(qbuf, FOLLOW_LINKS); switch (res->status) { case NIS_SUCCESS: break; case NIS_TRYAGAIN: case NIS_RPCERROR: case NIS_NAMEUNREACHABLE: if (retry_cnt++ > 4) { errno = EAGAIN; return false; } /* try not to overwhelm hosed server */ sleep(2); break; default: /* all other nisplus errors */ # if 0 if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("451 4.3.5 Cannot find table %s.%s: %s", map->map_file, map->map_domain, nis_sperrno(res->status)); # endif /* 0 */ errno = EAGAIN; return false; } } if (NIS_RES_NUMOBJ(res) != 1 || - (NIS_RES_OBJECT(res)->zo_data.zo_type != TABLE_OBJ)) + (NIS_RES_OBJECT(res)->zo_data.zo_type != NIS_TABLE_OBJ)) { if (tTd(38, 10)) sm_dprintf("nisplus_map_open: %s is not a table\n", qbuf); # if 0 if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("451 4.3.5 %s.%s: %s is not a table", map->map_file, map->map_domain, nis_sperrno(res->status)); # endif /* 0 */ errno = EBADF; return false; } /* default key column is column 0 */ if (map->map_keycolnm == NULL) map->map_keycolnm = newstr(COL_NAME(res,0)); max_col = COL_MAX(res); /* verify the key column exist */ for (i = 0; i < max_col; i++) { if (strcmp(map->map_keycolnm, COL_NAME(res,i)) == 0) break; } if (i == max_col) { if (tTd(38, 2)) sm_dprintf("nisplus_map_open(%s): can not find key column %s\n", map->map_file, map->map_keycolnm); errno = ENOENT; return false; } /* default value column is the last column */ if (map->map_valcolnm == NULL) { map->map_valcolno = max_col - 1; return true; } for (i = 0; i< max_col; i++) { if (strcmp(map->map_valcolnm, COL_NAME(res,i)) == 0) { map->map_valcolno = i; return true; } } if (tTd(38, 2)) sm_dprintf("nisplus_map_open(%s): can not find column %s\n", map->map_file, map->map_keycolnm); errno = ENOENT; return false; } /* ** NISPLUS_MAP_LOOKUP -- look up a datum in a NISPLUS table */ char * nisplus_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { char *p; auto int vsize; char *skp; int skleft; char search_key[MAXNAME + 4]; char qbuf[MAXLINE + NIS_MAXNAMELEN]; nis_result *result; if (tTd(38, 20)) sm_dprintf("nisplus_map_lookup(%s, %s)\n", map->map_mname, name); if (!bitset(MF_OPEN, map->map_mflags)) { if (nisplus_map_open(map, O_RDONLY)) { map->map_mflags |= MF_OPEN; map->map_pid = CurrentPid; } else { *statp = EX_UNAVAILABLE; return NULL; } } /* ** Copy the name to the key buffer, escaping double quote characters ** by doubling them and quoting "]" and "," to avoid having the ** NIS+ parser choke on them. */ skleft = sizeof(search_key) - 4; skp = search_key; for (p = name; *p != '\0' && skleft > 0; p++) { switch (*p) { case ']': case ',': /* quote the character */ *skp++ = '"'; *skp++ = *p; *skp++ = '"'; skleft -= 3; break; case '"': /* double the quote */ *skp++ = '"'; skleft--; /* FALLTHROUGH */ default: *skp++ = *p; skleft--; break; } } *skp = '\0'; if (!bitset(MF_NOFOLDCASE, map->map_mflags)) makelower(search_key); /* construct the query */ if (PARTIAL_NAME(map->map_file)) (void) sm_snprintf(qbuf, sizeof(qbuf), "[%s=%s],%s.%s", map->map_keycolnm, search_key, map->map_file, map->map_domain); else (void) sm_snprintf(qbuf, sizeof(qbuf), "[%s=%s],%s", map->map_keycolnm, search_key, map->map_file); if (tTd(38, 20)) sm_dprintf("qbuf=%s\n", qbuf); result = nis_list(qbuf, FOLLOW_LINKS | FOLLOW_PATH, NULL, NULL); if (result->status == NIS_SUCCESS) { int count; char *str; if ((count = NIS_RES_NUMOBJ(result)) != 1) { if (LogLevel > 10) sm_syslog(LOG_WARNING, CurEnv->e_id, "%s: lookup error, expected 1 entry, got %d", map->map_file, count); /* ignore second entry */ if (tTd(38, 20)) sm_dprintf("nisplus_map_lookup(%s), got %d entries, additional entries ignored\n", name, count); } p = ((NIS_RES_OBJECT(result))->EN_col(map->map_valcolno)); /* set the length of the result */ if (p == NULL) p = ""; vsize = strlen(p); if (tTd(38, 20)) sm_dprintf("nisplus_map_lookup(%s), found %s\n", name, p); if (bitset(MF_MATCHONLY, map->map_mflags)) str = map_rewrite(map, name, strlen(name), NULL); else str = map_rewrite(map, p, vsize, av); nis_freeresult(result); *statp = EX_OK; return str; } else { if (result->status == NIS_NOTFOUND) *statp = EX_NOTFOUND; else if (result->status == NIS_TRYAGAIN) *statp = EX_TEMPFAIL; else { *statp = EX_UNAVAILABLE; map->map_mflags &= ~(MF_VALID|MF_OPEN); } } if (tTd(38, 20)) sm_dprintf("nisplus_map_lookup(%s), failed\n", name); nis_freeresult(result); return NULL; } /* ** NISPLUS_GETCANONNAME -- look up canonical name in NIS+ */ static bool nisplus_getcanonname(name, hbsize, statp) char *name; int hbsize; int *statp; { char *vp; auto int vsize; nis_result *result; char *p; char nbuf[MAXNAME + 1]; char qbuf[MAXLINE + NIS_MAXNAMELEN]; if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf)) { *statp = EX_UNAVAILABLE; return false; } (void) shorten_hostname(nbuf); p = strchr(nbuf, '.'); if (p == NULL) { /* single token */ (void) sm_snprintf(qbuf, sizeof(qbuf), "[name=%s],hosts.org_dir", nbuf); } else if (p[1] != '\0') { /* multi token -- take only first token in nbuf */ *p = '\0'; (void) sm_snprintf(qbuf, sizeof(qbuf), "[name=%s],hosts.org_dir.%s", nbuf, &p[1]); } else { *statp = EX_NOHOST; return false; } if (tTd(38, 20)) sm_dprintf("\nnisplus_getcanonname(%s), qbuf=%s\n", name, qbuf); result = nis_list(qbuf, EXPAND_NAME|FOLLOW_LINKS|FOLLOW_PATH, NULL, NULL); if (result->status == NIS_SUCCESS) { int count; char *domain; if ((count = NIS_RES_NUMOBJ(result)) != 1) { if (LogLevel > 10) sm_syslog(LOG_WARNING, CurEnv->e_id, "nisplus_getcanonname: lookup error, expected 1 entry, got %d", count); /* ignore second entry */ if (tTd(38, 20)) sm_dprintf("nisplus_getcanonname(%s), got %d entries, all but first ignored\n", name, count); } if (tTd(38, 20)) sm_dprintf("nisplus_getcanonname(%s), found in directory \"%s\"\n", name, (NIS_RES_OBJECT(result))->zo_domain); vp = ((NIS_RES_OBJECT(result))->EN_col(0)); vsize = strlen(vp); if (tTd(38, 20)) sm_dprintf("nisplus_getcanonname(%s), found %s\n", name, vp); if (strchr(vp, '.') != NULL) { domain = ""; } else { domain = macvalue('m', CurEnv); if (domain == NULL) domain = ""; } if (hbsize > vsize + (int) strlen(domain) + 1) { if (domain[0] == '\0') (void) sm_strlcpy(name, vp, hbsize); else (void) sm_snprintf(name, hbsize, "%s.%s", vp, domain); *statp = EX_OK; } else *statp = EX_NOHOST; nis_freeresult(result); return true; } else { if (result->status == NIS_NOTFOUND) *statp = EX_NOHOST; else if (result->status == NIS_TRYAGAIN) *statp = EX_TEMPFAIL; else *statp = EX_UNAVAILABLE; } if (tTd(38, 20)) sm_dprintf("nisplus_getcanonname(%s), failed, status=%d, nsw_stat=%d\n", name, result->status, *statp); nis_freeresult(result); return false; } char * nisplus_default_domain() { static char default_domain[MAXNAME + 1] = ""; char *p; if (default_domain[0] != '\0') return default_domain; p = nis_local_directory(); (void) sm_strlcpy(default_domain, p, sizeof(default_domain)); return default_domain; } #endif /* NISPLUS */ /* ** LDAP Modules */ /* ** LDAPMAP_DEQUOTE - helper routine for ldapmap_parseargs */ #if defined(LDAPMAP) || defined(PH_MAP) # if PH_MAP # define ph_map_dequote ldapmap_dequote # endif /* PH_MAP */ static char *ldapmap_dequote __P((char *)); static char * ldapmap_dequote(str) char *str; { char *p; char *start; if (str == NULL) return NULL; p = str; if (*p == '"') { /* Should probably swallow initial whitespace here */ start = ++p; } else return str; while (*p != '"' && *p != '\0') p++; if (*p != '\0') *p = '\0'; return start; } #endif /* defined(LDAPMAP) || defined(PH_MAP) */ #if LDAPMAP static SM_LDAP_STRUCT *LDAPDefaults = NULL; /* ** LDAPMAP_OPEN -- open LDAP map ** ** Connect to the LDAP server. Re-use existing connections since a ** single server connection to a host (with the same host, port, ** bind DN, and secret) can answer queries for multiple maps. */ bool ldapmap_open(map, mode) MAP *map; int mode; { SM_LDAP_STRUCT *lmap; STAB *s; char *id; if (tTd(38, 2)) sm_dprintf("ldapmap_open(%s, %d): ", map->map_mname, mode); #if defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && \ HASLDAPGETALIASBYNAME if (VendorCode == VENDOR_SUN && strcmp(map->map_mname, "aliases.ldap") == 0) { return true; } #endif /* defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && ... */ mode &= O_ACCMODE; /* sendmail doesn't have the ability to write to LDAP (yet) */ if (mode != O_RDONLY) { /* issue a pseudo-error message */ errno = SM_EMAPCANTWRITE; return false; } lmap = (SM_LDAP_STRUCT *) map->map_db1; s = ldapmap_findconn(lmap); if (s->s_lmap != NULL) { /* Already have a connection open to this LDAP server */ lmap->ldap_ld = ((SM_LDAP_STRUCT *)s->s_lmap->map_db1)->ldap_ld; lmap->ldap_pid = ((SM_LDAP_STRUCT *)s->s_lmap->map_db1)->ldap_pid; /* Add this map as head of linked list */ lmap->ldap_next = s->s_lmap; s->s_lmap = map; if (tTd(38, 2)) sm_dprintf("using cached connection\n"); return true; } if (tTd(38, 2)) sm_dprintf("opening new connection\n"); if (lmap->ldap_host != NULL) id = lmap->ldap_host; else if (lmap->ldap_uri != NULL) id = lmap->ldap_uri; else id = "localhost"; if (tTd(74, 104)) { extern MAPCLASS NullMapClass; /* debug mode: don't actually open an LDAP connection */ map->map_orgclass = map->map_class; map->map_class = &NullMapClass; map->map_mflags |= MF_OPEN; map->map_pid = CurrentPid; return true; } /* No connection yet, connect */ if (!sm_ldap_start(map->map_mname, lmap)) { if (errno == ETIMEDOUT) { if (LogLevel > 1) sm_syslog(LOG_NOTICE, CurEnv->e_id, "timeout connecting to LDAP server %.100s", id); } if (!bitset(MF_OPTIONAL, map->map_mflags)) { if (bitset(MF_NODEFER, map->map_mflags)) { syserr("%s failed to %s in map %s", # if USE_LDAP_INIT "ldap_init/ldap_bind", # else /* USE_LDAP_INIT */ "ldap_open", # endif /* USE_LDAP_INIT */ id, map->map_mname); } else { syserr("451 4.3.5 %s failed to %s in map %s", # if USE_LDAP_INIT "ldap_init/ldap_bind", # else /* USE_LDAP_INIT */ "ldap_open", # endif /* USE_LDAP_INIT */ id, map->map_mname); } } return false; } /* Save connection for reuse */ s->s_lmap = map; return true; } /* ** LDAPMAP_CLOSE -- close ldap map */ void ldapmap_close(map) MAP *map; { SM_LDAP_STRUCT *lmap; STAB *s; if (tTd(38, 2)) sm_dprintf("ldapmap_close(%s)\n", map->map_mname); lmap = (SM_LDAP_STRUCT *) map->map_db1; /* Check if already closed */ if (lmap->ldap_ld == NULL) return; /* Close the LDAP connection */ sm_ldap_close(lmap); /* Mark all the maps that share the connection as closed */ s = ldapmap_findconn(lmap); while (s->s_lmap != NULL) { MAP *smap = s->s_lmap; if (tTd(38, 2) && smap != map) sm_dprintf("ldapmap_close(%s): closed %s (shared LDAP connection)\n", map->map_mname, smap->map_mname); smap->map_mflags &= ~(MF_OPEN|MF_WRITABLE); lmap = (SM_LDAP_STRUCT *) smap->map_db1; lmap->ldap_ld = NULL; s->s_lmap = lmap->ldap_next; lmap->ldap_next = NULL; } } # ifdef SUNET_ID /* ** SUNET_ID_HASH -- Convert a string to its Sunet_id canonical form ** This only makes sense at Stanford University. */ static char * sunet_id_hash(str) char *str; { char *p, *p_last; p = str; p_last = p; while (*p != '\0') { if (isascii(*p) && (islower(*p) || isdigit(*p))) { *p_last = *p; p_last++; } else if (isascii(*p) && isupper(*p)) { *p_last = tolower(*p); p_last++; } ++p; } if (*p_last != '\0') *p_last = '\0'; return str; } # define SM_CONVERT_ID(str) sunet_id_hash(str) # else /* SUNET_ID */ # define SM_CONVERT_ID(str) makelower(str) # endif /* SUNET_ID */ /* ** LDAPMAP_LOOKUP -- look up a datum in a LDAP map */ char * ldapmap_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { int flags; int i; int plen = 0; int psize = 0; int msgid; int save_errno; char *vp, *p; char *result = NULL; SM_RPOOL_T *rpool; SM_LDAP_STRUCT *lmap = NULL; char *argv[SM_LDAP_ARGS]; char keybuf[MAXKEY]; #if SM_LDAP_ARGS != MAX_MAP_ARGS # ERROR _SM_LDAP_ARGS must be the same as _MAX_MAP_ARGS #endif /* SM_LDAP_ARGS != MAX_MAP_ARGS */ #if defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && \ HASLDAPGETALIASBYNAME if (VendorCode == VENDOR_SUN && strcmp(map->map_mname, "aliases.ldap") == 0) { int rc; #if defined(GETLDAPALIASBYNAME_VERSION) && (GETLDAPALIASBYNAME_VERSION >= 2) extern char *__getldapaliasbyname(); char *answer; answer = __getldapaliasbyname(name, &rc); #else char answer[MAXNAME + 1]; rc = __getldapaliasbyname(name, answer, sizeof(answer)); #endif if (rc != 0) { if (tTd(38, 20)) sm_dprintf("getldapaliasbyname(%.100s) failed, errno=%d\n", name, errno); *statp = EX_NOTFOUND; return NULL; } *statp = EX_OK; if (tTd(38, 20)) sm_dprintf("getldapaliasbyname(%.100s) => %s\n", name, answer); if (bitset(MF_MATCHONLY, map->map_mflags)) result = map_rewrite(map, name, strlen(name), NULL); else result = map_rewrite(map, answer, strlen(answer), av); #if defined(GETLDAPALIASBYNAME_VERSION) && (GETLDAPALIASBYNAME_VERSION >= 2) free(answer); #endif return result; } #endif /* defined(SUN_EXTENSIONS) && defined(SUN_SIMPLIFIED_LDAP) && ... */ /* Get ldap struct pointer from map */ lmap = (SM_LDAP_STRUCT *) map->map_db1; sm_ldap_setopts(lmap->ldap_ld, lmap); if (lmap->ldap_multi_args) { SM_REQUIRE(av != NULL); memset(argv, '\0', sizeof(argv)); for (i = 0; i < SM_LDAP_ARGS && av[i] != NULL; i++) { argv[i] = sm_strdup(av[i]); if (argv[i] == NULL) { int save_errno, j; save_errno = errno; for (j = 0; j < i && argv[j] != NULL; j++) SM_FREE(argv[j]); *statp = EX_TEMPFAIL; errno = save_errno; return NULL; } if (!bitset(MF_NOFOLDCASE, map->map_mflags)) SM_CONVERT_ID(av[i]); } } else { (void) sm_strlcpy(keybuf, name, sizeof(keybuf)); if (!bitset(MF_NOFOLDCASE, map->map_mflags)) SM_CONVERT_ID(keybuf); } if (tTd(38, 20)) { if (lmap->ldap_multi_args) { sm_dprintf("ldapmap_lookup(%s, argv)\n", map->map_mname); for (i = 0; i < SM_LDAP_ARGS; i++) { sm_dprintf(" argv[%d] = %s\n", i, argv[i] == NULL ? "NULL" : argv[i]); } } else { sm_dprintf("ldapmap_lookup(%s, %s)\n", map->map_mname, name); } } if (lmap->ldap_multi_args) { msgid = sm_ldap_search_m(lmap, argv); /* free the argv array and its content, no longer needed */ for (i = 0; i < SM_LDAP_ARGS && argv[i] != NULL; i++) SM_FREE(argv[i]); } else msgid = sm_ldap_search(lmap, keybuf); if (msgid == SM_LDAP_ERR) { errno = sm_ldap_geterrno(lmap->ldap_ld) + E_LDAPBASE; save_errno = errno; if (!bitset(MF_OPTIONAL, map->map_mflags)) { /* ** Do not include keybuf as this error may be shown ** to outsiders. */ if (bitset(MF_NODEFER, map->map_mflags)) syserr("Error in ldap_search in map %s", map->map_mname); else syserr("451 4.3.5 Error in ldap_search in map %s", map->map_mname); } *statp = EX_TEMPFAIL; switch (save_errno - E_LDAPBASE) { # ifdef LDAP_SERVER_DOWN case LDAP_SERVER_DOWN: # endif /* LDAP_SERVER_DOWN */ case LDAP_TIMEOUT: case LDAP_UNAVAILABLE: /* server disappeared, try reopen on next search */ ldapmap_close(map); break; } errno = save_errno; return NULL; } #if SM_LDAP_ERROR_ON_MISSING_ARGS else if (msgid == SM_LDAP_ERR_ARG_MISS) { if (bitset(MF_NODEFER, map->map_mflags)) syserr("Error in ldap_search in map %s, too few arguments", map->map_mname); else syserr("554 5.3.5 Error in ldap_search in map %s, too few arguments", map->map_mname); *statp = EX_CONFIG; return NULL; } #endif /* SM_LDAP_ERROR_ON_MISSING_ARGS */ *statp = EX_NOTFOUND; vp = NULL; flags = 0; if (bitset(MF_SINGLEMATCH, map->map_mflags)) flags |= SM_LDAP_SINGLEMATCH; if (bitset(MF_MATCHONLY, map->map_mflags)) flags |= SM_LDAP_MATCHONLY; # if _FFR_LDAP_SINGLEDN if (bitset(MF_SINGLEDN, map->map_mflags)) flags |= SM_LDAP_SINGLEDN; # endif /* _FFR_LDAP_SINGLEDN */ /* Create an rpool for search related memory usage */ rpool = sm_rpool_new_x(NULL); p = NULL; *statp = sm_ldap_results(lmap, msgid, flags, map->map_coldelim, rpool, &p, &plen, &psize, NULL); save_errno = errno; /* Copy result so rpool can be freed */ if (*statp == EX_OK && p != NULL) vp = newstr(p); sm_rpool_free(rpool); /* need to restart LDAP connection? */ if (*statp == EX_RESTART) { *statp = EX_TEMPFAIL; ldapmap_close(map); } errno = save_errno; if (*statp != EX_OK && *statp != EX_NOTFOUND) { if (!bitset(MF_OPTIONAL, map->map_mflags)) { if (bitset(MF_NODEFER, map->map_mflags)) syserr("Error getting LDAP results, map=%s, name=%s", map->map_mname, name); else syserr("451 4.3.5 Error getting LDAP results, map=%s, name=%s", map->map_mname, name); } errno = save_errno; return NULL; } /* Did we match anything? */ if (vp == NULL && !bitset(MF_MATCHONLY, map->map_mflags)) return NULL; if (*statp == EX_OK) { if (LogLevel > 9) sm_syslog(LOG_INFO, CurEnv->e_id, "ldap=%s, %.100s=>%s", map->map_mname, name, vp == NULL ? "" : vp); if (bitset(MF_MATCHONLY, map->map_mflags)) result = map_rewrite(map, name, strlen(name), NULL); else { /* vp != NULL according to test above */ result = map_rewrite(map, vp, strlen(vp), av); } if (vp != NULL) sm_free(vp); /* XXX */ } return result; } /* ** LDAPMAP_FINDCONN -- find an LDAP connection to the server ** ** Cache LDAP connections based on the host, port, bind DN, ** secret, and PID so we don't have multiple connections open to ** the same server for different maps. Need a separate connection ** per PID since a parent process may close the map before the ** child is done with it. ** ** Parameters: ** lmap -- LDAP map information ** ** Returns: ** Symbol table entry for the LDAP connection. */ static STAB * ldapmap_findconn(lmap) SM_LDAP_STRUCT *lmap; { char *format; char *nbuf; char *id; STAB *SM_NONVOLATILE s = NULL; if (lmap->ldap_host != NULL) id = lmap->ldap_host; else if (lmap->ldap_uri != NULL) id = lmap->ldap_uri; else id = "localhost"; format = "%s%c%d%c%d%c%s%c%s%d"; nbuf = sm_stringf_x(format, id, CONDELSE, lmap->ldap_port, CONDELSE, lmap->ldap_version, CONDELSE, (lmap->ldap_binddn == NULL ? "" : lmap->ldap_binddn), CONDELSE, (lmap->ldap_secret == NULL ? "" : lmap->ldap_secret), (int) CurrentPid); SM_TRY s = stab(nbuf, ST_LMAP, ST_ENTER); SM_FINALLY sm_free(nbuf); SM_END_TRY return s; } /* ** LDAPMAP_PARSEARGS -- parse ldap map definition args. */ static struct lamvalues LDAPAuthMethods[] = { { "none", LDAP_AUTH_NONE }, { "simple", LDAP_AUTH_SIMPLE }, # ifdef LDAP_AUTH_KRBV4 { "krbv4", LDAP_AUTH_KRBV4 }, # endif /* LDAP_AUTH_KRBV4 */ { NULL, 0 } }; static struct ladvalues LDAPAliasDereference[] = { { "never", LDAP_DEREF_NEVER }, { "always", LDAP_DEREF_ALWAYS }, { "search", LDAP_DEREF_SEARCHING }, { "find", LDAP_DEREF_FINDING }, { NULL, 0 } }; static struct lssvalues LDAPSearchScope[] = { { "base", LDAP_SCOPE_BASE }, { "one", LDAP_SCOPE_ONELEVEL }, { "sub", LDAP_SCOPE_SUBTREE }, { NULL, 0 } }; bool ldapmap_parseargs(map, args) MAP *map; char *args; { bool secretread = true; bool attrssetup = false; int i; register char *p = args; SM_LDAP_STRUCT *lmap; struct lamvalues *lam; struct ladvalues *lad; struct lssvalues *lss; char ldapfilt[MAXLINE]; char m_tmp[MAXPATHLEN + LDAPMAP_MAX_PASSWD]; /* Get ldap struct pointer from map */ lmap = (SM_LDAP_STRUCT *) map->map_db1; /* Check if setting the initial LDAP defaults */ if (lmap == NULL || lmap != LDAPDefaults) { /* We need to alloc an SM_LDAP_STRUCT struct */ lmap = (SM_LDAP_STRUCT *) xalloc(sizeof(*lmap)); if (LDAPDefaults == NULL) sm_ldap_clear(lmap); else STRUCTCOPY(*LDAPDefaults, *lmap); } /* there is no check whether there is really an argument */ map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL; map->map_spacesub = SpaceSub; /* default value */ /* Check if setting up an alias or file class LDAP map */ if (bitset(MF_ALIAS, map->map_mflags)) { /* Comma separate if used as an alias file */ map->map_coldelim = ','; if (*args == '\0') { int n; char *lc; char jbuf[MAXHOSTNAMELEN]; char lcbuf[MAXLINE]; /* Get $j */ expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope); if (jbuf[0] == '\0') { (void) sm_strlcpy(jbuf, "localhost", sizeof(jbuf)); } lc = macvalue(macid("{sendmailMTACluster}"), CurEnv); if (lc == NULL) lc = ""; else { expand(lc, lcbuf, sizeof(lcbuf), CurEnv); lc = lcbuf; } n = sm_snprintf(ldapfilt, sizeof(ldapfilt), "(&(objectClass=sendmailMTAAliasObject)(sendmailMTAAliasGrouping=aliases)(|(sendmailMTACluster=%s)(sendmailMTAHost=%s))(sendmailMTAKey=%%0))", lc, jbuf); if (n >= sizeof(ldapfilt)) { syserr("%s: Default LDAP string too long", map->map_mname); return false; } /* default args for an alias LDAP entry */ lmap->ldap_filter = ldapfilt; lmap->ldap_attr[0] = "objectClass"; lmap->ldap_attr_type[0] = SM_LDAP_ATTR_OBJCLASS; lmap->ldap_attr_needobjclass[0] = NULL; lmap->ldap_attr[1] = "sendmailMTAAliasValue"; lmap->ldap_attr_type[1] = SM_LDAP_ATTR_NORMAL; lmap->ldap_attr_needobjclass[1] = NULL; lmap->ldap_attr[2] = "sendmailMTAAliasSearch"; lmap->ldap_attr_type[2] = SM_LDAP_ATTR_FILTER; lmap->ldap_attr_needobjclass[2] = "sendmailMTAMapObject"; lmap->ldap_attr[3] = "sendmailMTAAliasURL"; lmap->ldap_attr_type[3] = SM_LDAP_ATTR_URL; lmap->ldap_attr_needobjclass[3] = "sendmailMTAMapObject"; lmap->ldap_attr[4] = NULL; lmap->ldap_attr_type[4] = SM_LDAP_ATTR_NONE; lmap->ldap_attr_needobjclass[4] = NULL; attrssetup = true; } } else if (bitset(MF_FILECLASS, map->map_mflags)) { /* Space separate if used as a file class file */ map->map_coldelim = ' '; } # if _FFR_LDAP_NETWORK_TIMEOUT lmap->ldap_networktmo = 120; # endif /* _FFR_LDAP_NETWORK_TIMEOUT */ for (;;) { while (isascii(*p) && isspace(*p)) p++; if (*p != '-') break; switch (*++p) { case 'A': map->map_mflags |= MF_APPEND; break; case 'a': map->map_app = ++p; break; case 'D': map->map_mflags |= MF_DEFER; break; case 'f': map->map_mflags |= MF_NOFOLDCASE; break; case 'm': map->map_mflags |= MF_MATCHONLY; break; case 'N': map->map_mflags |= MF_INCLNULL; map->map_mflags &= ~MF_TRY0NULL; break; case 'O': map->map_mflags &= ~MF_TRY1NULL; break; case 'o': map->map_mflags |= MF_OPTIONAL; break; case 'q': map->map_mflags |= MF_KEEPQUOTES; break; case 'S': map->map_spacesub = *++p; break; case 'T': map->map_tapp = ++p; break; case 't': map->map_mflags |= MF_NODEFER; break; case 'z': if (*++p != '\\') map->map_coldelim = *p; else { switch (*++p) { case 'n': map->map_coldelim = '\n'; break; case 't': map->map_coldelim = '\t'; break; default: map->map_coldelim = '\\'; } } break; /* Start of ldapmap specific args */ case '1': map->map_mflags |= MF_SINGLEMATCH; break; # if _FFR_LDAP_SINGLEDN case '2': map->map_mflags |= MF_SINGLEDN; break; # endif /* _FFR_LDAP_SINGLEDN */ case 'b': /* search base */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_base = p; break; # if _FFR_LDAP_NETWORK_TIMEOUT case 'c': /* network (connect) timeout */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_networktmo = atoi(p); break; # endif /* _FFR_LDAP_NETWORK_TIMEOUT */ case 'd': /* Dn to bind to server as */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_binddn = p; break; case 'H': /* Use LDAP URI */ # if !USE_LDAP_INIT syserr("Must compile with -DUSE_LDAP_INIT to use LDAP URIs (-H) in map %s", map->map_mname); return false; # else /* !USE_LDAP_INIT */ if (lmap->ldap_host != NULL) { syserr("Can not specify both an LDAP host and an LDAP URI in map %s", map->map_mname); return false; } while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_uri = p; break; # endif /* !USE_LDAP_INIT */ case 'h': /* ldap host */ while (isascii(*++p) && isspace(*p)) continue; if (lmap->ldap_uri != NULL) { syserr("Can not specify both an LDAP host and an LDAP URI in map %s", map->map_mname); return false; } lmap->ldap_host = p; break; case 'K': lmap->ldap_multi_args = true; break; case 'k': /* search field */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_filter = p; break; case 'l': /* time limit */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_timelimit = atoi(p); lmap->ldap_timeout.tv_sec = lmap->ldap_timelimit; break; case 'M': /* Method for binding */ while (isascii(*++p) && isspace(*p)) continue; if (sm_strncasecmp(p, "LDAP_AUTH_", 10) == 0) p += 10; for (lam = LDAPAuthMethods; lam != NULL && lam->lam_name != NULL; lam++) { if (sm_strncasecmp(p, lam->lam_name, strlen(lam->lam_name)) == 0) break; } if (lam->lam_name != NULL) lmap->ldap_method = lam->lam_code; else { /* bad config line */ if (!bitset(MCF_OPTFILE, map->map_class->map_cflags)) { char *ptr; if ((ptr = strchr(p, ' ')) != NULL) *ptr = '\0'; syserr("Method for binding must be [none|simple|krbv4] (not %s) in map %s", p, map->map_mname); if (ptr != NULL) *ptr = ' '; return false; } } break; case 'n': /* retrieve attribute names only */ lmap->ldap_attrsonly = LDAPMAP_TRUE; break; /* ** This is a string that is dependent on the ** method used defined by 'M'. */ case 'P': /* Secret password for binding */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_secret = p; secretread = false; break; case 'p': /* ldap port */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_port = atoi(p); break; /* args stolen from ldapsearch.c */ case 'R': /* don't auto chase referrals */ # ifdef LDAP_REFERRALS lmap->ldap_options &= ~LDAP_OPT_REFERRALS; # else /* LDAP_REFERRALS */ syserr("compile with -DLDAP_REFERRALS for referral support"); # endif /* LDAP_REFERRALS */ break; case 'r': /* alias dereferencing */ while (isascii(*++p) && isspace(*p)) continue; if (sm_strncasecmp(p, "LDAP_DEREF_", 11) == 0) p += 11; for (lad = LDAPAliasDereference; lad != NULL && lad->lad_name != NULL; lad++) { if (sm_strncasecmp(p, lad->lad_name, strlen(lad->lad_name)) == 0) break; } if (lad->lad_name != NULL) lmap->ldap_deref = lad->lad_code; else { /* bad config line */ if (!bitset(MCF_OPTFILE, map->map_class->map_cflags)) { char *ptr; if ((ptr = strchr(p, ' ')) != NULL) *ptr = '\0'; syserr("Deref must be [never|always|search|find] (not %s) in map %s", p, map->map_mname); if (ptr != NULL) *ptr = ' '; return false; } } break; case 's': /* search scope */ while (isascii(*++p) && isspace(*p)) continue; if (sm_strncasecmp(p, "LDAP_SCOPE_", 11) == 0) p += 11; for (lss = LDAPSearchScope; lss != NULL && lss->lss_name != NULL; lss++) { if (sm_strncasecmp(p, lss->lss_name, strlen(lss->lss_name)) == 0) break; } if (lss->lss_name != NULL) lmap->ldap_scope = lss->lss_code; else { /* bad config line */ if (!bitset(MCF_OPTFILE, map->map_class->map_cflags)) { char *ptr; if ((ptr = strchr(p, ' ')) != NULL) *ptr = '\0'; syserr("Scope must be [base|one|sub] (not %s) in map %s", p, map->map_mname); if (ptr != NULL) *ptr = ' '; return false; } } break; case 'V': if (*++p != '\\') lmap->ldap_attrsep = *p; else { switch (*++p) { case 'n': lmap->ldap_attrsep = '\n'; break; case 't': lmap->ldap_attrsep = '\t'; break; default: lmap->ldap_attrsep = '\\'; } } break; case 'v': /* attr to return */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_attr[0] = p; lmap->ldap_attr[1] = NULL; break; case 'w': /* -w should be for passwd, -P should be for version */ while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_version = atoi(p); # ifdef LDAP_VERSION_MAX if (lmap->ldap_version > LDAP_VERSION_MAX) { syserr("LDAP version %d exceeds max of %d in map %s", lmap->ldap_version, LDAP_VERSION_MAX, map->map_mname); return false; } # endif /* LDAP_VERSION_MAX */ # ifdef LDAP_VERSION_MIN if (lmap->ldap_version < LDAP_VERSION_MIN) { syserr("LDAP version %d is lower than min of %d in map %s", lmap->ldap_version, LDAP_VERSION_MIN, map->map_mname); return false; } # endif /* LDAP_VERSION_MIN */ break; case 'Z': while (isascii(*++p) && isspace(*p)) continue; lmap->ldap_sizelimit = atoi(p); break; default: syserr("Illegal option %c map %s", *p, map->map_mname); break; } /* need to account for quoted strings here */ while (*p != '\0' && !(isascii(*p) && isspace(*p))) { if (*p == '"') { while (*++p != '"' && *p != '\0') continue; if (*p != '\0') p++; } else p++; } if (*p != '\0') *p++ = '\0'; } if (map->map_app != NULL) map->map_app = newstr(ldapmap_dequote(map->map_app)); if (map->map_tapp != NULL) map->map_tapp = newstr(ldapmap_dequote(map->map_tapp)); /* ** We need to swallow up all the stuff into a struct ** and dump it into map->map_dbptr1 */ if (lmap->ldap_host != NULL && (LDAPDefaults == NULL || LDAPDefaults == lmap || LDAPDefaults->ldap_host != lmap->ldap_host)) lmap->ldap_host = newstr(ldapmap_dequote(lmap->ldap_host)); map->map_domain = lmap->ldap_host; if (lmap->ldap_uri != NULL && (LDAPDefaults == NULL || LDAPDefaults == lmap || LDAPDefaults->ldap_uri != lmap->ldap_uri)) lmap->ldap_uri = newstr(ldapmap_dequote(lmap->ldap_uri)); map->map_domain = lmap->ldap_uri; if (lmap->ldap_binddn != NULL && (LDAPDefaults == NULL || LDAPDefaults == lmap || LDAPDefaults->ldap_binddn != lmap->ldap_binddn)) lmap->ldap_binddn = newstr(ldapmap_dequote(lmap->ldap_binddn)); if (lmap->ldap_secret != NULL && (LDAPDefaults == NULL || LDAPDefaults == lmap || LDAPDefaults->ldap_secret != lmap->ldap_secret)) { SM_FILE_T *sfd; long sff = SFF_OPENASROOT|SFF_ROOTOK|SFF_NOWLINK|SFF_NOWWFILES|SFF_NOGWFILES; if (DontLockReadFiles) sff |= SFF_NOLOCK; /* need to use method to map secret to passwd string */ switch (lmap->ldap_method) { case LDAP_AUTH_NONE: /* Do nothing */ break; case LDAP_AUTH_SIMPLE: /* ** Secret is the name of a file with ** the first line as the password. */ /* Already read in the secret? */ if (secretread) break; sfd = safefopen(ldapmap_dequote(lmap->ldap_secret), O_RDONLY, 0, sff); if (sfd == NULL) { syserr("LDAP map: cannot open secret %s", ldapmap_dequote(lmap->ldap_secret)); return false; } lmap->ldap_secret = sfgets(m_tmp, sizeof(m_tmp), sfd, TimeOuts.to_fileopen, "ldapmap_parseargs"); (void) sm_io_close(sfd, SM_TIME_DEFAULT); if (strlen(m_tmp) > LDAPMAP_MAX_PASSWD) { syserr("LDAP map: secret in %s too long", ldapmap_dequote(lmap->ldap_secret)); return false; } if (lmap->ldap_secret != NULL && strlen(m_tmp) > 0) { /* chomp newline */ if (m_tmp[strlen(m_tmp) - 1] == '\n') m_tmp[strlen(m_tmp) - 1] = '\0'; lmap->ldap_secret = m_tmp; } break; # ifdef LDAP_AUTH_KRBV4 case LDAP_AUTH_KRBV4: /* ** Secret is where the ticket file is ** stashed */ (void) sm_snprintf(m_tmp, sizeof(m_tmp), "KRBTKFILE=%s", ldapmap_dequote(lmap->ldap_secret)); lmap->ldap_secret = m_tmp; break; # endif /* LDAP_AUTH_KRBV4 */ default: /* Should NEVER get here */ syserr("LDAP map: Illegal value in lmap method"); return false; /* NOTREACHED */ break; } } if (lmap->ldap_secret != NULL && (LDAPDefaults == NULL || LDAPDefaults == lmap || LDAPDefaults->ldap_secret != lmap->ldap_secret)) lmap->ldap_secret = newstr(ldapmap_dequote(lmap->ldap_secret)); if (lmap->ldap_base != NULL && (LDAPDefaults == NULL || LDAPDefaults == lmap || LDAPDefaults->ldap_base != lmap->ldap_base)) lmap->ldap_base = newstr(ldapmap_dequote(lmap->ldap_base)); /* ** Save the server from extra work. If request is for a single ** match, tell the server to only return enough records to ** determine if there is a single match or not. This can not ** be one since the server would only return one and we wouldn't ** know if there were others available. */ if (bitset(MF_SINGLEMATCH, map->map_mflags)) lmap->ldap_sizelimit = 2; /* If setting defaults, don't process ldap_filter and ldap_attr */ if (lmap == LDAPDefaults) return true; if (lmap->ldap_filter != NULL) lmap->ldap_filter = newstr(ldapmap_dequote(lmap->ldap_filter)); else { if (!bitset(MCF_OPTFILE, map->map_class->map_cflags)) { syserr("No filter given in map %s", map->map_mname); return false; } } if (!attrssetup && lmap->ldap_attr[0] != NULL) { bool recurse = false; bool normalseen = false; i = 0; p = ldapmap_dequote(lmap->ldap_attr[0]); lmap->ldap_attr[0] = NULL; /* Prime the attr list with the objectClass attribute */ lmap->ldap_attr[i] = "objectClass"; lmap->ldap_attr_type[i] = SM_LDAP_ATTR_OBJCLASS; lmap->ldap_attr_needobjclass[i] = NULL; i++; while (p != NULL) { char *v; while (isascii(*p) && isspace(*p)) p++; if (*p == '\0') break; v = p; p = strchr(v, ','); if (p != NULL) *p++ = '\0'; if (i >= LDAPMAP_MAX_ATTR) { syserr("Too many return attributes in %s (max %d)", map->map_mname, LDAPMAP_MAX_ATTR); return false; } if (*v != '\0') { int j; int use; char *type; char *needobjclass; type = strchr(v, ':'); if (type != NULL) { *type++ = '\0'; needobjclass = strchr(type, ':'); if (needobjclass != NULL) *needobjclass++ = '\0'; } else { needobjclass = NULL; } use = i; /* allow override on "objectClass" type */ if (sm_strcasecmp(v, "objectClass") == 0 && lmap->ldap_attr_type[0] == SM_LDAP_ATTR_OBJCLASS) { use = 0; } else { /* ** Don't add something to attribute ** list twice. */ for (j = 1; j < i; j++) { if (sm_strcasecmp(v, lmap->ldap_attr[j]) == 0) { syserr("Duplicate attribute (%s) in %s", v, map->map_mname); return false; } } lmap->ldap_attr[use] = newstr(v); if (needobjclass != NULL && *needobjclass != '\0' && *needobjclass != '*') { lmap->ldap_attr_needobjclass[use] = newstr(needobjclass); } else { lmap->ldap_attr_needobjclass[use] = NULL; } } if (type != NULL && *type != '\0') { if (sm_strcasecmp(type, "dn") == 0) { recurse = true; lmap->ldap_attr_type[use] = SM_LDAP_ATTR_DN; } else if (sm_strcasecmp(type, "filter") == 0) { recurse = true; lmap->ldap_attr_type[use] = SM_LDAP_ATTR_FILTER; } else if (sm_strcasecmp(type, "url") == 0) { recurse = true; lmap->ldap_attr_type[use] = SM_LDAP_ATTR_URL; } else if (sm_strcasecmp(type, "normal") == 0) { lmap->ldap_attr_type[use] = SM_LDAP_ATTR_NORMAL; normalseen = true; } else { syserr("Unknown attribute type (%s) in %s", type, map->map_mname); return false; } } else { lmap->ldap_attr_type[use] = SM_LDAP_ATTR_NORMAL; normalseen = true; } i++; } } lmap->ldap_attr[i] = NULL; /* Set in case needed in future code */ attrssetup = true; if (recurse && !normalseen) { syserr("LDAP recursion requested in %s but no returnable attribute given", map->map_mname); return false; } if (recurse && lmap->ldap_attrsonly == LDAPMAP_TRUE) { syserr("LDAP recursion requested in %s can not be used with -n", map->map_mname); return false; } } map->map_db1 = (ARBPTR_T) lmap; return true; } /* ** LDAPMAP_SET_DEFAULTS -- Read default map spec from LDAPDefaults in .cf ** ** Parameters: ** spec -- map argument string from LDAPDefaults option ** ** Returns: ** None. */ void ldapmap_set_defaults(spec) char *spec; { STAB *class; MAP map; /* Allocate and set the default values */ if (LDAPDefaults == NULL) LDAPDefaults = (SM_LDAP_STRUCT *) xalloc(sizeof(*LDAPDefaults)); sm_ldap_clear(LDAPDefaults); memset(&map, '\0', sizeof(map)); /* look up the class */ class = stab("ldap", ST_MAPCLASS, ST_FIND); if (class == NULL) { syserr("readcf: LDAPDefaultSpec: class ldap not available"); return; } map.map_class = &class->s_mapclass; map.map_db1 = (ARBPTR_T) LDAPDefaults; map.map_mname = "O LDAPDefaultSpec"; (void) ldapmap_parseargs(&map, spec); /* These should never be set in LDAPDefaults */ if (map.map_mflags != (MF_TRY0NULL|MF_TRY1NULL) || map.map_spacesub != SpaceSub || map.map_app != NULL || map.map_tapp != NULL) { syserr("readcf: option LDAPDefaultSpec: Do not set non-LDAP specific flags"); SM_FREE_CLR(map.map_app); SM_FREE_CLR(map.map_tapp); } if (LDAPDefaults->ldap_filter != NULL) { syserr("readcf: option LDAPDefaultSpec: Do not set the LDAP search filter"); /* don't free, it isn't malloc'ed in parseargs */ LDAPDefaults->ldap_filter = NULL; } if (LDAPDefaults->ldap_attr[0] != NULL) { syserr("readcf: option LDAPDefaultSpec: Do not set the requested LDAP attributes"); /* don't free, they aren't malloc'ed in parseargs */ LDAPDefaults->ldap_attr[0] = NULL; } } #endif /* LDAPMAP */ /* ** PH map */ #if PH_MAP /* ** Support for the CCSO Nameserver (ph/qi). ** This code is intended to replace the so-called "ph mailer". ** Contributed by Mark D. Roth. Contact him for support. */ /* what version of the ph map code we're running */ static char phmap_id[128]; /* sendmail version for phmap id string */ extern const char Version[]; /* assume we're using nph-1.2.x if not specified */ # ifndef NPH_VERSION # define NPH_VERSION 10200 # endif /* compatibility for versions older than nph-1.2.0 */ # if NPH_VERSION < 10200 # define PH_OPEN_ROUNDROBIN PH_ROUNDROBIN # define PH_OPEN_DONTID PH_DONTID # define PH_CLOSE_FAST PH_FASTCLOSE # define PH_ERR_DATAERR PH_DATAERR # define PH_ERR_NOMATCH PH_NOMATCH # endif /* NPH_VERSION < 10200 */ /* ** PH_MAP_PARSEARGS -- parse ph map definition args. */ bool ph_map_parseargs(map, args) MAP *map; char *args; { register bool done; register char *p = args; PH_MAP_STRUCT *pmap = NULL; /* initialize version string */ (void) sm_snprintf(phmap_id, sizeof(phmap_id), "sendmail-%s phmap-20010529 libphclient-%s", Version, libphclient_version); pmap = (PH_MAP_STRUCT *) xalloc(sizeof(*pmap)); /* defaults */ pmap->ph_servers = NULL; pmap->ph_field_list = NULL; pmap->ph = NULL; pmap->ph_timeout = 0; pmap->ph_fastclose = 0; map->map_mflags |= MF_TRY0NULL|MF_TRY1NULL; for (;;) { while (isascii(*p) && isspace(*p)) p++; if (*p != '-') break; switch (*++p) { case 'N': map->map_mflags |= MF_INCLNULL; map->map_mflags &= ~MF_TRY0NULL; break; case 'O': map->map_mflags &= ~MF_TRY1NULL; break; case 'o': map->map_mflags |= MF_OPTIONAL; break; case 'f': map->map_mflags |= MF_NOFOLDCASE; break; case 'm': map->map_mflags |= MF_MATCHONLY; break; case 'A': map->map_mflags |= MF_APPEND; break; case 'q': map->map_mflags |= MF_KEEPQUOTES; break; case 't': map->map_mflags |= MF_NODEFER; break; case 'a': map->map_app = ++p; break; case 'T': map->map_tapp = ++p; break; case 'l': while (isascii(*++p) && isspace(*p)) continue; pmap->ph_timeout = atoi(p); break; case 'S': map->map_spacesub = *++p; break; case 'D': map->map_mflags |= MF_DEFER; break; case 'h': /* PH server list */ while (isascii(*++p) && isspace(*p)) continue; pmap->ph_servers = p; break; case 'k': /* fields to search for */ while (isascii(*++p) && isspace(*p)) continue; pmap->ph_field_list = p; break; default: syserr("ph_map_parseargs: unknown option -%c", *p); } /* try to account for quoted strings */ done = isascii(*p) && isspace(*p); while (*p != '\0' && !done) { if (*p == '"') { while (*++p != '"' && *p != '\0') continue; if (*p != '\0') p++; } else p++; done = isascii(*p) && isspace(*p); } if (*p != '\0') *p++ = '\0'; } if (map->map_app != NULL) map->map_app = newstr(ph_map_dequote(map->map_app)); if (map->map_tapp != NULL) map->map_tapp = newstr(ph_map_dequote(map->map_tapp)); if (pmap->ph_field_list != NULL) pmap->ph_field_list = newstr(ph_map_dequote(pmap->ph_field_list)); if (pmap->ph_servers != NULL) pmap->ph_servers = newstr(ph_map_dequote(pmap->ph_servers)); else { syserr("ph_map_parseargs: -h flag is required"); return false; } map->map_db1 = (ARBPTR_T) pmap; return true; } /* ** PH_MAP_CLOSE -- close the connection to the ph server */ void ph_map_close(map) MAP *map; { PH_MAP_STRUCT *pmap; pmap = (PH_MAP_STRUCT *)map->map_db1; if (tTd(38, 9)) sm_dprintf("ph_map_close(%s): pmap->ph_fastclose=%d\n", map->map_mname, pmap->ph_fastclose); if (pmap->ph != NULL) { ph_set_sendhook(pmap->ph, NULL); ph_set_recvhook(pmap->ph, NULL); ph_close(pmap->ph, pmap->ph_fastclose); } map->map_mflags &= ~(MF_OPEN|MF_WRITABLE); } static jmp_buf PHTimeout; /* ARGSUSED */ static void ph_timeout(unused) int unused; { /* ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ errno = ETIMEDOUT; longjmp(PHTimeout, 1); } static void #if NPH_VERSION >= 10200 ph_map_send_debug(appdata, text) void *appdata; #else ph_map_send_debug(text) #endif char *text; { if (LogLevel > 9) sm_syslog(LOG_NOTICE, CurEnv->e_id, "ph_map_send_debug: ==> %s", text); if (tTd(38, 20)) sm_dprintf("ph_map_send_debug: ==> %s\n", text); } static void #if NPH_VERSION >= 10200 ph_map_recv_debug(appdata, text) void *appdata; #else ph_map_recv_debug(text) #endif char *text; { if (LogLevel > 10) sm_syslog(LOG_NOTICE, CurEnv->e_id, "ph_map_recv_debug: <== %s", text); if (tTd(38, 21)) sm_dprintf("ph_map_recv_debug: <== %s\n", text); } /* ** PH_MAP_OPEN -- sub for opening PH map */ bool ph_map_open(map, mode) MAP *map; int mode; { PH_MAP_STRUCT *pmap; register SM_EVENT *ev = NULL; int save_errno = 0; char *hostlist, *host; if (tTd(38, 2)) sm_dprintf("ph_map_open(%s)\n", map->map_mname); mode &= O_ACCMODE; if (mode != O_RDONLY) { /* issue a pseudo-error message */ errno = SM_EMAPCANTWRITE; return false; } if (CurEnv != NULL && CurEnv->e_sendmode == SM_DEFER && bitset(MF_DEFER, map->map_mflags)) { if (tTd(9, 1)) sm_dprintf("ph_map_open(%s) => DEFERRED\n", map->map_mname); /* ** Unset MF_DEFER here so that map_lookup() returns ** a temporary failure using the bogus map and ** map->map_tapp instead of the default permanent error. */ map->map_mflags &= ~MF_DEFER; return false; } pmap = (PH_MAP_STRUCT *)map->map_db1; pmap->ph_fastclose = 0; /* refresh field for reopen */ /* try each host in the list */ hostlist = newstr(pmap->ph_servers); for (host = strtok(hostlist, " "); host != NULL; host = strtok(NULL, " ")) { /* set timeout */ if (pmap->ph_timeout != 0) { if (setjmp(PHTimeout) != 0) { ev = NULL; if (LogLevel > 1) sm_syslog(LOG_NOTICE, CurEnv->e_id, "timeout connecting to PH server %.100s", host); errno = ETIMEDOUT; goto ph_map_open_abort; } ev = sm_setevent(pmap->ph_timeout, ph_timeout, 0); } /* open connection to server */ if (ph_open(&(pmap->ph), host, PH_OPEN_ROUNDROBIN|PH_OPEN_DONTID, ph_map_send_debug, ph_map_recv_debug #if NPH_VERSION >= 10200 , NULL #endif ) == 0 && ph_id(pmap->ph, phmap_id) == 0) { if (ev != NULL) sm_clrevent(ev); sm_free(hostlist); /* XXX */ return true; } ph_map_open_abort: save_errno = errno; if (ev != NULL) sm_clrevent(ev); pmap->ph_fastclose = PH_CLOSE_FAST; ph_map_close(map); errno = save_errno; } if (bitset(MF_NODEFER, map->map_mflags)) { if (errno == 0) errno = EAGAIN; syserr("ph_map_open: %s: cannot connect to PH server", map->map_mname); } else if (!bitset(MF_OPTIONAL, map->map_mflags) && LogLevel > 1) sm_syslog(LOG_NOTICE, CurEnv->e_id, "ph_map_open: %s: cannot connect to PH server", map->map_mname); sm_free(hostlist); /* XXX */ return false; } /* ** PH_MAP_LOOKUP -- look up key from ph server */ char * ph_map_lookup(map, key, args, pstat) MAP *map; char *key; char **args; int *pstat; { int i, save_errno = 0; register SM_EVENT *ev = NULL; PH_MAP_STRUCT *pmap; char *value = NULL; pmap = (PH_MAP_STRUCT *)map->map_db1; *pstat = EX_OK; /* set timeout */ if (pmap->ph_timeout != 0) { if (setjmp(PHTimeout) != 0) { ev = NULL; if (LogLevel > 1) sm_syslog(LOG_NOTICE, CurEnv->e_id, "timeout during PH lookup of %.100s", key); errno = ETIMEDOUT; *pstat = EX_TEMPFAIL; goto ph_map_lookup_abort; } ev = sm_setevent(pmap->ph_timeout, ph_timeout, 0); } /* perform lookup */ i = ph_email_resolve(pmap->ph, key, pmap->ph_field_list, &value); if (i == -1) *pstat = EX_TEMPFAIL; else if (i == PH_ERR_NOMATCH || i == PH_ERR_DATAERR) *pstat = EX_UNAVAILABLE; ph_map_lookup_abort: if (ev != NULL) sm_clrevent(ev); /* ** Close the connection if the timer popped ** or we got a temporary PH error */ if (*pstat == EX_TEMPFAIL) { save_errno = errno; pmap->ph_fastclose = PH_CLOSE_FAST; ph_map_close(map); errno = save_errno; } if (*pstat == EX_OK) { if (tTd(38,20)) sm_dprintf("ph_map_lookup: %s => %s\n", key, value); if (bitset(MF_MATCHONLY, map->map_mflags)) return map_rewrite(map, key, strlen(key), NULL); else return map_rewrite(map, value, strlen(value), args); } return NULL; } #endif /* PH_MAP */ /* ** syslog map */ #define map_prio map_lockfd /* overload field */ /* ** SYSLOG_MAP_PARSEARGS -- check for priority level to syslog messages. */ bool syslog_map_parseargs(map, args) MAP *map; char *args; { char *p = args; char *priority = NULL; /* there is no check whether there is really an argument */ while (*p != '\0') { while (isascii(*p) && isspace(*p)) p++; if (*p != '-') break; ++p; if (*p == 'D') { map->map_mflags |= MF_DEFER; ++p; } else if (*p == 'S') { map->map_spacesub = *++p; if (*p != '\0') p++; } else if (*p == 'L') { while (*++p != '\0' && isascii(*p) && isspace(*p)) continue; if (*p == '\0') break; priority = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; } else { syserr("Illegal option %c map syslog", *p); ++p; } } if (priority == NULL) map->map_prio = LOG_INFO; else { if (sm_strncasecmp("LOG_", priority, 4) == 0) priority += 4; #ifdef LOG_EMERG if (sm_strcasecmp("EMERG", priority) == 0) map->map_prio = LOG_EMERG; else #endif /* LOG_EMERG */ #ifdef LOG_ALERT if (sm_strcasecmp("ALERT", priority) == 0) map->map_prio = LOG_ALERT; else #endif /* LOG_ALERT */ #ifdef LOG_CRIT if (sm_strcasecmp("CRIT", priority) == 0) map->map_prio = LOG_CRIT; else #endif /* LOG_CRIT */ #ifdef LOG_ERR if (sm_strcasecmp("ERR", priority) == 0) map->map_prio = LOG_ERR; else #endif /* LOG_ERR */ #ifdef LOG_WARNING if (sm_strcasecmp("WARNING", priority) == 0) map->map_prio = LOG_WARNING; else #endif /* LOG_WARNING */ #ifdef LOG_NOTICE if (sm_strcasecmp("NOTICE", priority) == 0) map->map_prio = LOG_NOTICE; else #endif /* LOG_NOTICE */ #ifdef LOG_INFO if (sm_strcasecmp("INFO", priority) == 0) map->map_prio = LOG_INFO; else #endif /* LOG_INFO */ #ifdef LOG_DEBUG if (sm_strcasecmp("DEBUG", priority) == 0) map->map_prio = LOG_DEBUG; else #endif /* LOG_DEBUG */ { syserr("syslog_map_parseargs: Unknown priority %s", priority); return false; } } return true; } /* ** SYSLOG_MAP_LOOKUP -- rewrite and syslog message. Always return empty string */ char * syslog_map_lookup(map, string, args, statp) MAP *map; char *string; char **args; int *statp; { char *ptr = map_rewrite(map, string, strlen(string), args); if (ptr != NULL) { if (tTd(38, 20)) sm_dprintf("syslog_map_lookup(%s (priority %d): %s\n", map->map_mname, map->map_prio, ptr); sm_syslog(map->map_prio, CurEnv->e_id, "%s", ptr); } *statp = EX_OK; return ""; } #if _FFR_DPRINTF_MAP /* ** dprintf map */ #define map_dbg_level map_lockfd /* overload field */ /* ** DPRINTF_MAP_PARSEARGS -- check for priority level to dprintf messages. */ bool dprintf_map_parseargs(map, args) MAP *map; char *args; { char *p = args; char *dbg_level = NULL; /* there is no check whether there is really an argument */ while (*p != '\0') { while (isascii(*p) && isspace(*p)) p++; if (*p != '-') break; ++p; if (*p == 'D') { map->map_mflags |= MF_DEFER; ++p; } else if (*p == 'S') { map->map_spacesub = *++p; if (*p != '\0') p++; } else if (*p == 'd') { while (*++p != '\0' && isascii(*p) && isspace(*p)) continue; if (*p == '\0') break; dbg_level = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; } else { syserr("Illegal option %c map dprintf", *p); ++p; } } if (dbg_level == NULL) map->map_dbg_level = 0; else { if (!(isascii(*dbg_level) && isdigit(*dbg_level))) { syserr("dprintf map \"%s\", file %s: -d should specify a number, not %s", map->map_mname, map->map_file, dbg_level); return false; } map->map_dbg_level = atoi(dbg_level); } return true; } /* ** DPRINTF_MAP_LOOKUP -- rewrite and print message. Always return empty string */ char * dprintf_map_lookup(map, string, args, statp) MAP *map; char *string; char **args; int *statp; { char *ptr = map_rewrite(map, string, strlen(string), args); if (ptr != NULL && tTd(85, map->map_dbg_level)) sm_dprintf("%s\n", ptr); *statp = EX_OK; return ""; } #endif /* _FFR_DPRINTF_MAP */ /* ** HESIOD Modules */ #if HESIOD bool hes_map_open(map, mode) MAP *map; int mode; { if (tTd(38, 2)) sm_dprintf("hes_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); if (mode != O_RDONLY) { /* issue a pseudo-error message */ errno = SM_EMAPCANTWRITE; return false; } # ifdef HESIOD_INIT if (HesiodContext != NULL || hesiod_init(&HesiodContext) == 0) return true; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("451 4.3.5 cannot initialize Hesiod map (%s)", sm_errstring(errno)); return false; # else /* HESIOD_INIT */ if (hes_error() == HES_ER_UNINIT) hes_init(); switch (hes_error()) { case HES_ER_OK: case HES_ER_NOTFOUND: return true; } if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("451 4.3.5 cannot initialize Hesiod map (%d)", hes_error()); return false; # endif /* HESIOD_INIT */ } char * hes_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { char **hp; if (tTd(38, 20)) sm_dprintf("hes_map_lookup(%s, %s)\n", map->map_file, name); if (name[0] == '\\') { char *np; int nl; int save_errno; char nbuf[MAXNAME]; nl = strlen(name); if (nl < sizeof(nbuf) - 1) np = nbuf; else np = xalloc(strlen(name) + 2); np[0] = '\\'; (void) sm_strlcpy(&np[1], name, (sizeof(nbuf)) - 1); # ifdef HESIOD_INIT hp = hesiod_resolve(HesiodContext, np, map->map_file); # else /* HESIOD_INIT */ hp = hes_resolve(np, map->map_file); # endif /* HESIOD_INIT */ save_errno = errno; if (np != nbuf) sm_free(np); /* XXX */ errno = save_errno; } else { # ifdef HESIOD_INIT hp = hesiod_resolve(HesiodContext, name, map->map_file); # else /* HESIOD_INIT */ hp = hes_resolve(name, map->map_file); # endif /* HESIOD_INIT */ } # ifdef HESIOD_INIT if (hp == NULL || *hp == NULL) { switch (errno) { case ENOENT: *statp = EX_NOTFOUND; break; case ECONNREFUSED: *statp = EX_TEMPFAIL; break; case EMSGSIZE: case ENOMEM: default: *statp = EX_UNAVAILABLE; break; } if (hp != NULL) hesiod_free_list(HesiodContext, hp); return NULL; } # else /* HESIOD_INIT */ if (hp == NULL || hp[0] == NULL) { switch (hes_error()) { case HES_ER_OK: *statp = EX_OK; break; case HES_ER_NOTFOUND: *statp = EX_NOTFOUND; break; case HES_ER_CONFIG: *statp = EX_UNAVAILABLE; break; case HES_ER_NET: *statp = EX_TEMPFAIL; break; } return NULL; } # endif /* HESIOD_INIT */ if (bitset(MF_MATCHONLY, map->map_mflags)) return map_rewrite(map, name, strlen(name), NULL); else return map_rewrite(map, hp[0], strlen(hp[0]), av); } /* ** HES_MAP_CLOSE -- free the Hesiod context */ void hes_map_close(map) MAP *map; { if (tTd(38, 20)) sm_dprintf("hes_map_close(%s)\n", map->map_file); # ifdef HESIOD_INIT /* Free the hesiod context */ if (HesiodContext != NULL) { hesiod_end(HesiodContext); HesiodContext = NULL; } # endif /* HESIOD_INIT */ } #endif /* HESIOD */ /* ** NeXT NETINFO Modules */ #if NETINFO # define NETINFO_DEFAULT_DIR "/aliases" # define NETINFO_DEFAULT_PROPERTY "members" /* ** NI_MAP_OPEN -- open NetInfo Aliases */ bool ni_map_open(map, mode) MAP *map; int mode; { if (tTd(38, 2)) sm_dprintf("ni_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); mode &= O_ACCMODE; if (*map->map_file == '\0') map->map_file = NETINFO_DEFAULT_DIR; if (map->map_valcolnm == NULL) map->map_valcolnm = NETINFO_DEFAULT_PROPERTY; if (map->map_coldelim == '\0') { if (bitset(MF_ALIAS, map->map_mflags)) map->map_coldelim = ','; else if (bitset(MF_FILECLASS, map->map_mflags)) map->map_coldelim = ' '; } return true; } /* ** NI_MAP_LOOKUP -- look up a datum in NetInfo */ char * ni_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { char *res; char *propval; if (tTd(38, 20)) sm_dprintf("ni_map_lookup(%s, %s)\n", map->map_mname, name); propval = ni_propval(map->map_file, map->map_keycolnm, name, map->map_valcolnm, map->map_coldelim); if (propval == NULL) return NULL; SM_TRY if (bitset(MF_MATCHONLY, map->map_mflags)) res = map_rewrite(map, name, strlen(name), NULL); else res = map_rewrite(map, propval, strlen(propval), av); SM_FINALLY sm_free(propval); SM_END_TRY return res; } static bool ni_getcanonname(name, hbsize, statp) char *name; int hbsize; int *statp; { char *vptr; char *ptr; char nbuf[MAXNAME + 1]; if (tTd(38, 20)) sm_dprintf("ni_getcanonname(%s)\n", name); if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf)) { *statp = EX_UNAVAILABLE; return false; } (void) shorten_hostname(nbuf); /* we only accept single token search key */ if (strchr(nbuf, '.')) { *statp = EX_NOHOST; return false; } /* Do the search */ vptr = ni_propval("/machines", NULL, nbuf, "name", '\n'); if (vptr == NULL) { *statp = EX_NOHOST; return false; } /* Only want the first machine name */ if ((ptr = strchr(vptr, '\n')) != NULL) *ptr = '\0'; if (sm_strlcpy(name, vptr, hbsize) >= hbsize) { sm_free(vptr); *statp = EX_UNAVAILABLE; return true; } sm_free(vptr); *statp = EX_OK; return false; } #endif /* NETINFO */ /* ** TEXT (unindexed text file) Modules ** ** This code donated by Sun Microsystems. */ #define map_sff map_lockfd /* overload field */ /* ** TEXT_MAP_OPEN -- open text table */ bool text_map_open(map, mode) MAP *map; int mode; { long sff; int i; if (tTd(38, 2)) sm_dprintf("text_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); mode &= O_ACCMODE; if (mode != O_RDONLY) { errno = EPERM; return false; } if (*map->map_file == '\0') { syserr("text map \"%s\": file name required", map->map_mname); return false; } if (map->map_file[0] != '/') { syserr("text map \"%s\": file name must be fully qualified", map->map_mname); return false; } sff = SFF_ROOTOK|SFF_REGONLY; if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_SAFEDIRPATH; if ((i = safefile(map->map_file, RunAsUid, RunAsGid, RunAsUserName, sff, S_IRUSR, NULL)) != 0) { int save_errno = errno; /* cannot open this map */ if (tTd(38, 2)) sm_dprintf("\tunsafe map file: %d\n", i); errno = save_errno; if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("text map \"%s\": unsafe map file %s", map->map_mname, map->map_file); return false; } if (map->map_keycolnm == NULL) map->map_keycolno = 0; else { if (!(isascii(*map->map_keycolnm) && isdigit(*map->map_keycolnm))) { syserr("text map \"%s\", file %s: -k should specify a number, not %s", map->map_mname, map->map_file, map->map_keycolnm); return false; } map->map_keycolno = atoi(map->map_keycolnm); } if (map->map_valcolnm == NULL) map->map_valcolno = 0; else { if (!(isascii(*map->map_valcolnm) && isdigit(*map->map_valcolnm))) { syserr("text map \"%s\", file %s: -v should specify a number, not %s", map->map_mname, map->map_file, map->map_valcolnm); return false; } map->map_valcolno = atoi(map->map_valcolnm); } if (tTd(38, 2)) { sm_dprintf("text_map_open(%s, %s): delimiter = ", map->map_mname, map->map_file); if (map->map_coldelim == '\0') sm_dprintf("(white space)\n"); else sm_dprintf("%c\n", map->map_coldelim); } map->map_sff = sff; return true; } /* ** TEXT_MAP_LOOKUP -- look up a datum in a TEXT table */ char * text_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { char *vp; auto int vsize; int buflen; SM_FILE_T *f; char delim; int key_idx; bool found_it; long sff = map->map_sff; char search_key[MAXNAME + 1]; char linebuf[MAXLINE]; char buf[MAXNAME + 1]; found_it = false; if (tTd(38, 20)) sm_dprintf("text_map_lookup(%s, %s)\n", map->map_mname, name); buflen = strlen(name); if (buflen > sizeof(search_key) - 1) buflen = sizeof(search_key) - 1; /* XXX just cut if off? */ memmove(search_key, name, buflen); search_key[buflen] = '\0'; if (!bitset(MF_NOFOLDCASE, map->map_mflags)) makelower(search_key); f = safefopen(map->map_file, O_RDONLY, FileMode, sff); if (f == NULL) { map->map_mflags &= ~(MF_VALID|MF_OPEN); *statp = EX_UNAVAILABLE; return NULL; } key_idx = map->map_keycolno; delim = map->map_coldelim; while (sm_io_fgets(f, SM_TIME_DEFAULT, - linebuf, sizeof(linebuf)) != NULL) + linebuf, sizeof(linebuf)) >= 0) { char *p; /* skip comment line */ if (linebuf[0] == '#') continue; p = strchr(linebuf, '\n'); if (p != NULL) *p = '\0'; p = get_column(linebuf, key_idx, delim, buf, sizeof(buf)); if (p != NULL && sm_strcasecmp(search_key, p) == 0) { found_it = true; break; } } (void) sm_io_close(f, SM_TIME_DEFAULT); if (!found_it) { *statp = EX_NOTFOUND; return NULL; } vp = get_column(linebuf, map->map_valcolno, delim, buf, sizeof(buf)); if (vp == NULL) { *statp = EX_NOTFOUND; return NULL; } vsize = strlen(vp); *statp = EX_OK; if (bitset(MF_MATCHONLY, map->map_mflags)) return map_rewrite(map, name, strlen(name), NULL); else return map_rewrite(map, vp, vsize, av); } /* ** TEXT_GETCANONNAME -- look up canonical name in hosts file */ static bool text_getcanonname(name, hbsize, statp) char *name; int hbsize; int *statp; { bool found; char *dot; SM_FILE_T *f; char linebuf[MAXLINE]; char cbuf[MAXNAME + 1]; char nbuf[MAXNAME + 1]; if (tTd(38, 20)) sm_dprintf("text_getcanonname(%s)\n", name); if (sm_strlcpy(nbuf, name, sizeof(nbuf)) >= sizeof(nbuf)) { *statp = EX_UNAVAILABLE; return false; } dot = shorten_hostname(nbuf); f = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, HostsFile, SM_IO_RDONLY, NULL); if (f == NULL) { *statp = EX_UNAVAILABLE; return false; } found = false; while (!found && sm_io_fgets(f, SM_TIME_DEFAULT, - linebuf, sizeof(linebuf)) != NULL) + linebuf, sizeof(linebuf)) >= 0) { char *p = strpbrk(linebuf, "#\n"); if (p != NULL) *p = '\0'; if (linebuf[0] != '\0') found = extract_canonname(nbuf, dot, linebuf, cbuf, sizeof(cbuf)); } (void) sm_io_close(f, SM_TIME_DEFAULT); if (!found) { *statp = EX_NOHOST; return false; } if (sm_strlcpy(name, cbuf, hbsize) >= hbsize) { *statp = EX_UNAVAILABLE; return false; } *statp = EX_OK; return true; } /* ** STAB (Symbol Table) Modules */ /* ** STAB_MAP_LOOKUP -- look up alias in symbol table */ /* ARGSUSED2 */ char * stab_map_lookup(map, name, av, pstat) register MAP *map; char *name; char **av; int *pstat; { register STAB *s; if (tTd(38, 20)) sm_dprintf("stab_lookup(%s, %s)\n", map->map_mname, name); s = stab(name, ST_ALIAS, ST_FIND); if (s == NULL) return NULL; if (bitset(MF_MATCHONLY, map->map_mflags)) return map_rewrite(map, name, strlen(name), NULL); else return map_rewrite(map, s->s_alias, strlen(s->s_alias), av); } /* ** STAB_MAP_STORE -- store in symtab (actually using during init, not rebuild) */ void stab_map_store(map, lhs, rhs) register MAP *map; char *lhs; char *rhs; { register STAB *s; s = stab(lhs, ST_ALIAS, ST_ENTER); s->s_alias = newstr(rhs); } /* ** STAB_MAP_OPEN -- initialize (reads data file) ** ** This is a weird case -- it is only intended as a fallback for ** aliases. For this reason, opens for write (only during a ** "newaliases") always fails, and opens for read open the ** actual underlying text file instead of the database. */ bool stab_map_open(map, mode) register MAP *map; int mode; { SM_FILE_T *af; long sff; struct stat st; if (tTd(38, 2)) sm_dprintf("stab_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); mode &= O_ACCMODE; if (mode != O_RDONLY) { errno = EPERM; return false; } sff = SFF_ROOTOK|SFF_REGONLY; if (!bitnset(DBS_LINKEDMAPINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; if (!bitnset(DBS_MAPINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_SAFEDIRPATH; af = safefopen(map->map_file, O_RDONLY, 0444, sff); if (af == NULL) return false; readaliases(map, af, false, false); if (fstat(sm_io_getinfo(af, SM_IO_WHAT_FD, NULL), &st) >= 0) map->map_mtime = st.st_mtime; (void) sm_io_close(af, SM_TIME_DEFAULT); return true; } /* ** Implicit Modules ** ** Tries several types. For back compatibility of aliases. */ /* ** IMPL_MAP_LOOKUP -- lookup in best open database */ char * impl_map_lookup(map, name, av, pstat) MAP *map; char *name; char **av; int *pstat; { if (tTd(38, 20)) sm_dprintf("impl_map_lookup(%s, %s)\n", map->map_mname, name); #if NEWDB if (bitset(MF_IMPL_HASH, map->map_mflags)) return db_map_lookup(map, name, av, pstat); #endif /* NEWDB */ #if NDBM if (bitset(MF_IMPL_NDBM, map->map_mflags)) return ndbm_map_lookup(map, name, av, pstat); #endif /* NDBM */ return stab_map_lookup(map, name, av, pstat); } /* ** IMPL_MAP_STORE -- store in open databases */ void impl_map_store(map, lhs, rhs) MAP *map; char *lhs; char *rhs; { if (tTd(38, 12)) sm_dprintf("impl_map_store(%s, %s, %s)\n", map->map_mname, lhs, rhs); #if NEWDB if (bitset(MF_IMPL_HASH, map->map_mflags)) db_map_store(map, lhs, rhs); #endif /* NEWDB */ #if NDBM if (bitset(MF_IMPL_NDBM, map->map_mflags)) ndbm_map_store(map, lhs, rhs); #endif /* NDBM */ stab_map_store(map, lhs, rhs); } /* ** IMPL_MAP_OPEN -- implicit database open */ bool impl_map_open(map, mode) MAP *map; int mode; { if (tTd(38, 2)) sm_dprintf("impl_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); mode &= O_ACCMODE; #if NEWDB map->map_mflags |= MF_IMPL_HASH; if (hash_map_open(map, mode)) { # ifdef NDBM_YP_COMPAT if (mode == O_RDONLY || strstr(map->map_file, "/yp/") == NULL) # endif /* NDBM_YP_COMPAT */ return true; } else map->map_mflags &= ~MF_IMPL_HASH; #endif /* NEWDB */ #if NDBM map->map_mflags |= MF_IMPL_NDBM; if (ndbm_map_open(map, mode)) { return true; } else map->map_mflags &= ~MF_IMPL_NDBM; #endif /* NDBM */ #if defined(NEWDB) || defined(NDBM) if (Verbose) message("WARNING: cannot open alias database %s%s", map->map_file, mode == O_RDONLY ? "; reading text version" : ""); #else /* defined(NEWDB) || defined(NDBM) */ if (mode != O_RDONLY) usrerr("Cannot rebuild aliases: no database format defined"); #endif /* defined(NEWDB) || defined(NDBM) */ if (mode == O_RDONLY) return stab_map_open(map, mode); else return false; } /* ** IMPL_MAP_CLOSE -- close any open database(s) */ void impl_map_close(map) MAP *map; { if (tTd(38, 9)) sm_dprintf("impl_map_close(%s, %s, %lx)\n", map->map_mname, map->map_file, map->map_mflags); #if NEWDB if (bitset(MF_IMPL_HASH, map->map_mflags)) { db_map_close(map); map->map_mflags &= ~MF_IMPL_HASH; } #endif /* NEWDB */ #if NDBM if (bitset(MF_IMPL_NDBM, map->map_mflags)) { ndbm_map_close(map); map->map_mflags &= ~MF_IMPL_NDBM; } #endif /* NDBM */ } /* ** User map class. ** ** Provides access to the system password file. */ /* ** USER_MAP_OPEN -- open user map ** ** Really just binds field names to field numbers. */ bool user_map_open(map, mode) MAP *map; int mode; { if (tTd(38, 2)) sm_dprintf("user_map_open(%s, %d)\n", map->map_mname, mode); mode &= O_ACCMODE; if (mode != O_RDONLY) { /* issue a pseudo-error message */ errno = SM_EMAPCANTWRITE; return false; } if (map->map_valcolnm == NULL) /* EMPTY */ /* nothing */ ; else if (sm_strcasecmp(map->map_valcolnm, "name") == 0) map->map_valcolno = 1; else if (sm_strcasecmp(map->map_valcolnm, "passwd") == 0) map->map_valcolno = 2; else if (sm_strcasecmp(map->map_valcolnm, "uid") == 0) map->map_valcolno = 3; else if (sm_strcasecmp(map->map_valcolnm, "gid") == 0) map->map_valcolno = 4; else if (sm_strcasecmp(map->map_valcolnm, "gecos") == 0) map->map_valcolno = 5; else if (sm_strcasecmp(map->map_valcolnm, "dir") == 0) map->map_valcolno = 6; else if (sm_strcasecmp(map->map_valcolnm, "shell") == 0) map->map_valcolno = 7; else { syserr("User map %s: unknown column name %s", map->map_mname, map->map_valcolnm); return false; } return true; } /* ** USER_MAP_LOOKUP -- look up a user in the passwd file. */ /* ARGSUSED3 */ char * user_map_lookup(map, key, av, statp) MAP *map; char *key; char **av; int *statp; { auto bool fuzzy; SM_MBDB_T user; if (tTd(38, 20)) sm_dprintf("user_map_lookup(%s, %s)\n", map->map_mname, key); *statp = finduser(key, &fuzzy, &user); if (*statp != EX_OK) return NULL; if (bitset(MF_MATCHONLY, map->map_mflags)) return map_rewrite(map, key, strlen(key), NULL); else { char *rwval = NULL; char buf[30]; switch (map->map_valcolno) { case 0: case 1: rwval = user.mbdb_name; break; case 2: rwval = "x"; /* passwd no longer supported */ break; case 3: (void) sm_snprintf(buf, sizeof(buf), "%d", (int) user.mbdb_uid); rwval = buf; break; case 4: (void) sm_snprintf(buf, sizeof(buf), "%d", (int) user.mbdb_gid); rwval = buf; break; case 5: rwval = user.mbdb_fullname; break; case 6: rwval = user.mbdb_homedir; break; case 7: rwval = user.mbdb_shell; break; default: syserr("user_map %s: bogus field %d", map->map_mname, map->map_valcolno); return NULL; } return map_rewrite(map, rwval, strlen(rwval), av); } } /* ** Program map type. ** ** This provides access to arbitrary programs. It should be used ** only very sparingly, since there is no way to bound the cost ** of invoking an arbitrary program. */ char * prog_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { int i; int save_errno; int fd; int status; auto pid_t pid; register char *p; char *rval; char *argv[MAXPV + 1]; char buf[MAXLINE]; if (tTd(38, 20)) sm_dprintf("prog_map_lookup(%s, %s) %s\n", map->map_mname, name, map->map_file); i = 0; argv[i++] = map->map_file; if (map->map_rebuild != NULL) { (void) sm_strlcpy(buf, map->map_rebuild, sizeof(buf)); for (p = strtok(buf, " \t"); p != NULL; p = strtok(NULL, " \t")) { if (i >= MAXPV - 1) break; argv[i++] = p; } } argv[i++] = name; argv[i] = NULL; if (tTd(38, 21)) { sm_dprintf("prog_open:"); for (i = 0; argv[i] != NULL; i++) sm_dprintf(" %s", argv[i]); sm_dprintf("\n"); } (void) sm_blocksignal(SIGCHLD); pid = prog_open(argv, &fd, CurEnv); if (pid < 0) { if (!bitset(MF_OPTIONAL, map->map_mflags)) syserr("prog_map_lookup(%s) failed (%s) -- closing", map->map_mname, sm_errstring(errno)); else if (tTd(38, 9)) sm_dprintf("prog_map_lookup(%s) failed (%s) -- closing", map->map_mname, sm_errstring(errno)); map->map_mflags &= ~(MF_VALID|MF_OPEN); *statp = EX_OSFILE; return NULL; } i = read(fd, buf, sizeof(buf) - 1); if (i < 0) { syserr("prog_map_lookup(%s): read error %s", map->map_mname, sm_errstring(errno)); rval = NULL; } else if (i == 0) { if (tTd(38, 20)) sm_dprintf("prog_map_lookup(%s): empty answer\n", map->map_mname); rval = NULL; } else { buf[i] = '\0'; p = strchr(buf, '\n'); if (p != NULL) *p = '\0'; /* collect the return value */ if (bitset(MF_MATCHONLY, map->map_mflags)) rval = map_rewrite(map, name, strlen(name), NULL); else rval = map_rewrite(map, buf, strlen(buf), av); /* now flush any additional output */ while ((i = read(fd, buf, sizeof(buf))) > 0) continue; } /* wait for the process to terminate */ (void) close(fd); status = waitfor(pid); save_errno = errno; (void) sm_releasesignal(SIGCHLD); errno = save_errno; if (status == -1) { syserr("prog_map_lookup(%s): wait error %s", map->map_mname, sm_errstring(errno)); *statp = EX_SOFTWARE; rval = NULL; } else if (WIFEXITED(status)) { if ((*statp = WEXITSTATUS(status)) != EX_OK) rval = NULL; } else { syserr("prog_map_lookup(%s): child died on signal %d", map->map_mname, status); *statp = EX_UNAVAILABLE; rval = NULL; } return rval; } /* ** Sequenced map type. ** ** Tries each map in order until something matches, much like ** implicit. Stores go to the first map in the list that can ** support storing. ** ** This is slightly unusual in that there are two interfaces. ** The "sequence" interface lets you stack maps arbitrarily. ** The "switch" interface builds a sequence map by looking ** at a system-dependent configuration file such as ** /etc/nsswitch.conf on Solaris or /etc/svc.conf on Ultrix. ** ** We don't need an explicit open, since all maps are ** opened on demand. */ /* ** SEQ_MAP_PARSE -- Sequenced map parsing */ bool seq_map_parse(map, ap) MAP *map; char *ap; { int maxmap; if (tTd(38, 2)) sm_dprintf("seq_map_parse(%s, %s)\n", map->map_mname, ap); maxmap = 0; while (*ap != '\0') { register char *p; STAB *s; /* find beginning of map name */ while (isascii(*ap) && isspace(*ap)) ap++; for (p = ap; (isascii(*p) && isalnum(*p)) || *p == '_' || *p == '.'; p++) continue; if (*p != '\0') *p++ = '\0'; while (*p != '\0' && (!isascii(*p) || !isalnum(*p))) p++; if (*ap == '\0') { ap = p; continue; } s = stab(ap, ST_MAP, ST_FIND); if (s == NULL) { syserr("Sequence map %s: unknown member map %s", map->map_mname, ap); } else if (maxmap >= MAXMAPSTACK) { syserr("Sequence map %s: too many member maps (%d max)", map->map_mname, MAXMAPSTACK); maxmap++; } else if (maxmap < MAXMAPSTACK) { map->map_stack[maxmap++] = &s->s_map; } ap = p; } return true; } /* ** SWITCH_MAP_OPEN -- open a switched map ** ** This looks at the system-dependent configuration and builds ** a sequence map that does the same thing. ** ** Every system must define a switch_map_find routine in conf.c ** that will return the list of service types associated with a ** given service class. */ bool switch_map_open(map, mode) MAP *map; int mode; { int mapno; int nmaps; char *maptype[MAXMAPSTACK]; if (tTd(38, 2)) sm_dprintf("switch_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); mode &= O_ACCMODE; nmaps = switch_map_find(map->map_file, maptype, map->map_return); if (tTd(38, 19)) { sm_dprintf("\tswitch_map_find => %d\n", nmaps); for (mapno = 0; mapno < nmaps; mapno++) sm_dprintf("\t\t%s\n", maptype[mapno]); } if (nmaps <= 0 || nmaps > MAXMAPSTACK) return false; for (mapno = 0; mapno < nmaps; mapno++) { register STAB *s; char nbuf[MAXNAME + 1]; if (maptype[mapno] == NULL) continue; (void) sm_strlcpyn(nbuf, sizeof(nbuf), 3, map->map_mname, ".", maptype[mapno]); s = stab(nbuf, ST_MAP, ST_FIND); if (s == NULL) { syserr("Switch map %s: unknown member map %s", map->map_mname, nbuf); } else { map->map_stack[mapno] = &s->s_map; if (tTd(38, 4)) sm_dprintf("\tmap_stack[%d] = %s:%s\n", mapno, s->s_map.map_class->map_cname, nbuf); } } return true; } #if 0 /* ** SEQ_MAP_CLOSE -- close all underlying maps */ void seq_map_close(map) MAP *map; { int mapno; if (tTd(38, 9)) sm_dprintf("seq_map_close(%s)\n", map->map_mname); for (mapno = 0; mapno < MAXMAPSTACK; mapno++) { MAP *mm = map->map_stack[mapno]; if (mm == NULL || !bitset(MF_OPEN, mm->map_mflags)) continue; mm->map_mflags |= MF_CLOSING; mm->map_class->map_close(mm); mm->map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING); } } #endif /* 0 */ /* ** SEQ_MAP_LOOKUP -- sequenced map lookup */ char * seq_map_lookup(map, key, args, pstat) MAP *map; char *key; char **args; int *pstat; { int mapno; int mapbit = 0x01; bool tempfail = false; if (tTd(38, 20)) sm_dprintf("seq_map_lookup(%s, %s)\n", map->map_mname, key); for (mapno = 0; mapno < MAXMAPSTACK; mapbit <<= 1, mapno++) { MAP *mm = map->map_stack[mapno]; char *rv; if (mm == NULL) continue; if (!bitset(MF_OPEN, mm->map_mflags) && !openmap(mm)) { if (bitset(mapbit, map->map_return[MA_UNAVAIL])) { *pstat = EX_UNAVAILABLE; return NULL; } continue; } *pstat = EX_OK; rv = mm->map_class->map_lookup(mm, key, args, pstat); if (rv != NULL) return rv; if (*pstat == EX_TEMPFAIL) { if (bitset(mapbit, map->map_return[MA_TRYAGAIN])) return NULL; tempfail = true; } else if (bitset(mapbit, map->map_return[MA_NOTFOUND])) break; } if (tempfail) *pstat = EX_TEMPFAIL; else if (*pstat == EX_OK) *pstat = EX_NOTFOUND; return NULL; } /* ** SEQ_MAP_STORE -- sequenced map store */ void seq_map_store(map, key, val) MAP *map; char *key; char *val; { int mapno; if (tTd(38, 12)) sm_dprintf("seq_map_store(%s, %s, %s)\n", map->map_mname, key, val); for (mapno = 0; mapno < MAXMAPSTACK; mapno++) { MAP *mm = map->map_stack[mapno]; if (mm == NULL || !bitset(MF_WRITABLE, mm->map_mflags)) continue; mm->map_class->map_store(mm, key, val); return; } syserr("seq_map_store(%s, %s, %s): no writable map", map->map_mname, key, val); } /* ** NULL stubs */ /* ARGSUSED */ bool null_map_open(map, mode) MAP *map; int mode; { return true; } /* ARGSUSED */ void null_map_close(map) MAP *map; { return; } char * null_map_lookup(map, key, args, pstat) MAP *map; char *key; char **args; int *pstat; { *pstat = EX_NOTFOUND; return NULL; } /* ARGSUSED */ void null_map_store(map, key, val) MAP *map; char *key; char *val; { return; } MAPCLASS NullMapClass = { "null-map", NULL, 0, NULL, null_map_lookup, null_map_store, null_map_open, null_map_close, }; /* ** BOGUS stubs */ char * bogus_map_lookup(map, key, args, pstat) MAP *map; char *key; char **args; int *pstat; { *pstat = EX_TEMPFAIL; return NULL; } MAPCLASS BogusMapClass = { "bogus-map", NULL, 0, NULL, bogus_map_lookup, null_map_store, null_map_open, null_map_close, }; /* ** MACRO modules */ char * macro_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { int mid; if (tTd(38, 20)) sm_dprintf("macro_map_lookup(%s, %s)\n", map->map_mname, name == NULL ? "NULL" : name); if (name == NULL || *name == '\0' || (mid = macid(name)) == 0) { *statp = EX_CONFIG; return NULL; } if (av[1] == NULL) macdefine(&CurEnv->e_macro, A_PERM, mid, NULL); else macdefine(&CurEnv->e_macro, A_TEMP, mid, av[1]); *statp = EX_OK; return ""; } /* ** REGEX modules */ #if MAP_REGEX # include # define DEFAULT_DELIM CONDELSE # define END_OF_FIELDS -1 # define ERRBUF_SIZE 80 # define MAX_MATCH 32 # define xnalloc(s) memset(xalloc(s), '\0', s); struct regex_map { regex_t *regex_pattern_buf; /* xalloc it */ int *regex_subfields; /* move to type MAP */ char *regex_delim; /* move to type MAP */ }; static int parse_fields __P((char *, int *, int, int)); static char *regex_map_rewrite __P((MAP *, const char*, size_t, char **)); static int parse_fields(s, ibuf, blen, nr_substrings) char *s; int *ibuf; /* array */ int blen; /* number of elements in ibuf */ int nr_substrings; /* number of substrings in the pattern */ { register char *cp; int i = 0; bool lastone = false; blen--; /* for terminating END_OF_FIELDS */ cp = s; do { for (;; cp++) { if (*cp == ',') { *cp = '\0'; break; } if (*cp == '\0') { lastone = true; break; } } if (i < blen) { int val = atoi(s); if (val < 0 || val >= nr_substrings) { syserr("field (%d) out of range, only %d substrings in pattern", val, nr_substrings); return -1; } ibuf[i++] = val; } else { syserr("too many fields, %d max", blen); return -1; } s = ++cp; } while (!lastone); ibuf[i] = END_OF_FIELDS; return i; } bool regex_map_init(map, ap) MAP *map; char *ap; { int regerr; struct regex_map *map_p; register char *p; char *sub_param = NULL; int pflags; static char defdstr[] = { (char) DEFAULT_DELIM, '\0' }; if (tTd(38, 2)) sm_dprintf("regex_map_init: mapname '%s', args '%s'\n", map->map_mname, ap); pflags = REG_ICASE | REG_EXTENDED | REG_NOSUB; p = ap; map_p = (struct regex_map *) xnalloc(sizeof(*map_p)); map_p->regex_pattern_buf = (regex_t *)xnalloc(sizeof(regex_t)); for (;;) { while (isascii(*p) && isspace(*p)) p++; if (*p != '-') break; switch (*++p) { case 'n': /* not */ map->map_mflags |= MF_REGEX_NOT; break; case 'f': /* case sensitive */ map->map_mflags |= MF_NOFOLDCASE; pflags &= ~REG_ICASE; break; case 'b': /* basic regular expressions */ pflags &= ~REG_EXTENDED; break; case 's': /* substring match () syntax */ sub_param = ++p; pflags &= ~REG_NOSUB; break; case 'd': /* delimiter */ map_p->regex_delim = ++p; break; case 'a': /* map append */ map->map_app = ++p; break; case 'm': /* matchonly */ map->map_mflags |= MF_MATCHONLY; break; case 'q': map->map_mflags |= MF_KEEPQUOTES; break; case 'S': map->map_spacesub = *++p; break; case 'D': map->map_mflags |= MF_DEFER; break; } while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; } if (tTd(38, 3)) sm_dprintf("regex_map_init: compile '%s' 0x%x\n", p, pflags); if ((regerr = regcomp(map_p->regex_pattern_buf, p, pflags)) != 0) { /* Errorhandling */ char errbuf[ERRBUF_SIZE]; (void) regerror(regerr, map_p->regex_pattern_buf, errbuf, sizeof(errbuf)); syserr("pattern-compile-error: %s", errbuf); sm_free(map_p->regex_pattern_buf); /* XXX */ sm_free(map_p); /* XXX */ return false; } if (map->map_app != NULL) map->map_app = newstr(map->map_app); if (map_p->regex_delim != NULL) map_p->regex_delim = newstr(map_p->regex_delim); else map_p->regex_delim = defdstr; if (!bitset(REG_NOSUB, pflags)) { /* substring matching */ int substrings; int *fields = (int *) xalloc(sizeof(int) * (MAX_MATCH + 1)); substrings = map_p->regex_pattern_buf->re_nsub + 1; if (tTd(38, 3)) sm_dprintf("regex_map_init: nr of substrings %d\n", substrings); if (substrings >= MAX_MATCH) { syserr("too many substrings, %d max", MAX_MATCH); sm_free(map_p->regex_pattern_buf); /* XXX */ sm_free(map_p); /* XXX */ return false; } if (sub_param != NULL && sub_param[0] != '\0') { /* optional parameter -sfields */ if (parse_fields(sub_param, fields, MAX_MATCH + 1, substrings) == -1) return false; } else { int i; /* set default fields */ for (i = 0; i < substrings; i++) fields[i] = i; fields[i] = END_OF_FIELDS; } map_p->regex_subfields = fields; if (tTd(38, 3)) { int *ip; sm_dprintf("regex_map_init: subfields"); for (ip = fields; *ip != END_OF_FIELDS; ip++) sm_dprintf(" %d", *ip); sm_dprintf("\n"); } } map->map_db1 = (ARBPTR_T) map_p; /* dirty hack */ return true; } static char * regex_map_rewrite(map, s, slen, av) MAP *map; const char *s; size_t slen; char **av; { if (bitset(MF_MATCHONLY, map->map_mflags)) return map_rewrite(map, av[0], strlen(av[0]), NULL); else return map_rewrite(map, s, slen, av); } char * regex_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { int reg_res; struct regex_map *map_p; regmatch_t pmatch[MAX_MATCH]; if (tTd(38, 20)) { char **cpp; sm_dprintf("regex_map_lookup: key '%s'\n", name); for (cpp = av; cpp != NULL && *cpp != NULL; cpp++) sm_dprintf("regex_map_lookup: arg '%s'\n", *cpp); } map_p = (struct regex_map *)(map->map_db1); reg_res = regexec(map_p->regex_pattern_buf, name, MAX_MATCH, pmatch, 0); if (bitset(MF_REGEX_NOT, map->map_mflags)) { /* option -n */ if (reg_res == REG_NOMATCH) return regex_map_rewrite(map, "", (size_t) 0, av); else return NULL; } if (reg_res == REG_NOMATCH) return NULL; if (map_p->regex_subfields != NULL) { /* option -s */ static char retbuf[MAXNAME]; int fields[MAX_MATCH + 1]; bool first = true; int anglecnt = 0, cmntcnt = 0, spacecnt = 0; bool quotemode = false, bslashmode = false; register char *dp, *sp; char *endp, *ldp; int *ip; dp = retbuf; ldp = retbuf + sizeof(retbuf) - 1; if (av[1] != NULL) { if (parse_fields(av[1], fields, MAX_MATCH + 1, (int) map_p->regex_pattern_buf->re_nsub + 1) == -1) { *statp = EX_CONFIG; return NULL; } ip = fields; } else ip = map_p->regex_subfields; for ( ; *ip != END_OF_FIELDS; ip++) { if (!first) { for (sp = map_p->regex_delim; *sp; sp++) { if (dp < ldp) *dp++ = *sp; } } else first = false; if (*ip >= MAX_MATCH || pmatch[*ip].rm_so < 0 || pmatch[*ip].rm_eo < 0) continue; sp = name + pmatch[*ip].rm_so; endp = name + pmatch[*ip].rm_eo; for (; endp > sp; sp++) { if (dp < ldp) { if (bslashmode) { *dp++ = *sp; bslashmode = false; } else if (quotemode && *sp != '"' && *sp != '\\') { *dp++ = *sp; } else switch (*dp++ = *sp) { case '\\': bslashmode = true; break; case '(': cmntcnt++; break; case ')': cmntcnt--; break; case '<': anglecnt++; break; case '>': anglecnt--; break; case ' ': spacecnt++; break; case '"': quotemode = !quotemode; break; } } } } if (anglecnt != 0 || cmntcnt != 0 || quotemode || bslashmode || spacecnt != 0) { sm_syslog(LOG_WARNING, NOQID, "Warning: regex may cause prescan() failure map=%s lookup=%s", map->map_mname, name); return NULL; } *dp = '\0'; return regex_map_rewrite(map, retbuf, strlen(retbuf), av); } return regex_map_rewrite(map, "", (size_t)0, av); } #endif /* MAP_REGEX */ /* ** NSD modules */ #if MAP_NSD # include # define _DATUM_DEFINED # include typedef struct ns_map_list { ns_map_t *map; /* XXX ns_ ? */ char *mapname; struct ns_map_list *next; } ns_map_list_t; static ns_map_t * ns_map_t_find(mapname) char *mapname; { static ns_map_list_t *ns_maps = NULL; ns_map_list_t *ns_map; /* walk the list of maps looking for the correctly named map */ for (ns_map = ns_maps; ns_map != NULL; ns_map = ns_map->next) { if (strcmp(ns_map->mapname, mapname) == 0) break; } /* if we are looking at a NULL ns_map_list_t, then create a new one */ if (ns_map == NULL) { ns_map = (ns_map_list_t *) xalloc(sizeof(*ns_map)); ns_map->mapname = newstr(mapname); ns_map->map = (ns_map_t *) xalloc(sizeof(*ns_map->map)); memset(ns_map->map, '\0', sizeof(*ns_map->map)); ns_map->next = ns_maps; ns_maps = ns_map; } return ns_map->map; } char * nsd_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { int buflen, r; char *p; ns_map_t *ns_map; char keybuf[MAXNAME + 1]; char buf[MAXLINE]; if (tTd(38, 20)) sm_dprintf("nsd_map_lookup(%s, %s)\n", map->map_mname, name); buflen = strlen(name); if (buflen > sizeof(keybuf) - 1) buflen = sizeof(keybuf) - 1; /* XXX simply cut off? */ memmove(keybuf, name, buflen); keybuf[buflen] = '\0'; if (!bitset(MF_NOFOLDCASE, map->map_mflags)) makelower(keybuf); ns_map = ns_map_t_find(map->map_file); if (ns_map == NULL) { if (tTd(38, 20)) sm_dprintf("nsd_map_t_find failed\n"); *statp = EX_UNAVAILABLE; return NULL; } r = ns_lookup(ns_map, NULL, map->map_file, keybuf, NULL, buf, sizeof(buf)); if (r == NS_UNAVAIL || r == NS_TRYAGAIN) { *statp = EX_TEMPFAIL; return NULL; } if (r == NS_BADREQ # ifdef NS_NOPERM || r == NS_NOPERM # endif /* NS_NOPERM */ ) { *statp = EX_CONFIG; return NULL; } if (r != NS_SUCCESS) { *statp = EX_NOTFOUND; return NULL; } *statp = EX_OK; /* Null out trailing \n */ if ((p = strchr(buf, '\n')) != NULL) *p = '\0'; return map_rewrite(map, buf, strlen(buf), av); } #endif /* MAP_NSD */ char * arith_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { long r; long v[2]; bool res = false; bool boolres; static char result[16]; char **cpp; if (tTd(38, 2)) { sm_dprintf("arith_map_lookup: key '%s'\n", name); for (cpp = av; cpp != NULL && *cpp != NULL; cpp++) sm_dprintf("arith_map_lookup: arg '%s'\n", *cpp); } r = 0; boolres = false; cpp = av; *statp = EX_OK; /* ** read arguments for arith map ** - no check is made whether they are really numbers ** - just ignores args after the second */ for (++cpp; cpp != NULL && *cpp != NULL && r < 2; cpp++) v[r++] = strtol(*cpp, NULL, 0); /* operator and (at least) two operands given? */ if (name != NULL && r == 2) { switch (*name) { case '|': r = v[0] | v[1]; break; case '&': r = v[0] & v[1]; break; case '%': if (v[1] == 0) return NULL; r = v[0] % v[1]; break; case '+': r = v[0] + v[1]; break; case '-': r = v[0] - v[1]; break; case '*': r = v[0] * v[1]; break; case '/': if (v[1] == 0) return NULL; r = v[0] / v[1]; break; case 'l': res = v[0] < v[1]; boolres = true; break; case '=': res = v[0] == v[1]; boolres = true; break; case 'r': r = v[1] - v[0] + 1; if (r <= 0) return NULL; r = get_random() % r + v[0]; break; default: /* XXX */ *statp = EX_CONFIG; if (LogLevel > 10) sm_syslog(LOG_WARNING, NOQID, "arith_map: unknown operator %c", (isascii(*name) && isprint(*name)) ? *name : '?'); return NULL; } if (boolres) (void) sm_snprintf(result, sizeof(result), res ? "TRUE" : "FALSE"); else (void) sm_snprintf(result, sizeof(result), "%ld", r); return result; } *statp = EX_CONFIG; return NULL; } #if SOCKETMAP # if NETINET || NETINET6 # include # endif /* NETINET || NETINET6 */ # define socket_map_next map_stack[0] /* ** SOCKET_MAP_OPEN -- open socket table */ bool socket_map_open(map, mode) MAP *map; int mode; { STAB *s; int sock = 0; SOCKADDR_LEN_T addrlen = 0; int addrno = 0; int save_errno; char *p; char *colon; char *at; struct hostent *hp = NULL; SOCKADDR addr; if (tTd(38, 2)) sm_dprintf("socket_map_open(%s, %s, %d)\n", map->map_mname, map->map_file, mode); mode &= O_ACCMODE; /* sendmail doesn't have the ability to write to SOCKET (yet) */ if (mode != O_RDONLY) { /* issue a pseudo-error message */ errno = SM_EMAPCANTWRITE; return false; } if (*map->map_file == '\0') { syserr("socket map \"%s\": empty or missing socket information", map->map_mname); return false; } s = socket_map_findconn(map->map_file); if (s->s_socketmap != NULL) { /* Copy open connection */ map->map_db1 = s->s_socketmap->map_db1; /* Add this map as head of linked list */ map->socket_map_next = s->s_socketmap; s->s_socketmap = map; if (tTd(38, 2)) sm_dprintf("using cached connection\n"); return true; } if (tTd(38, 2)) sm_dprintf("opening new connection\n"); /* following code is ripped from milter.c */ /* XXX It should be put in a library... */ /* protocol:filename or protocol:port@host */ memset(&addr, '\0', sizeof(addr)); p = map->map_file; colon = strchr(p, ':'); if (colon != NULL) { *colon = '\0'; if (*p == '\0') { # if NETUNIX /* default to AF_UNIX */ addr.sa.sa_family = AF_UNIX; # else /* NETUNIX */ # if NETINET /* default to AF_INET */ addr.sa.sa_family = AF_INET; # else /* NETINET */ # if NETINET6 /* default to AF_INET6 */ addr.sa.sa_family = AF_INET6; # else /* NETINET6 */ /* no protocols available */ syserr("socket map \"%s\": no valid socket protocols available", map->map_mname); return false; # endif /* NETINET6 */ # endif /* NETINET */ # endif /* NETUNIX */ } # if NETUNIX else if (sm_strcasecmp(p, "unix") == 0 || sm_strcasecmp(p, "local") == 0) addr.sa.sa_family = AF_UNIX; # endif /* NETUNIX */ # if NETINET else if (sm_strcasecmp(p, "inet") == 0) addr.sa.sa_family = AF_INET; # endif /* NETINET */ # if NETINET6 else if (sm_strcasecmp(p, "inet6") == 0) addr.sa.sa_family = AF_INET6; # endif /* NETINET6 */ else { # ifdef EPROTONOSUPPORT errno = EPROTONOSUPPORT; # else /* EPROTONOSUPPORT */ errno = EINVAL; # endif /* EPROTONOSUPPORT */ syserr("socket map \"%s\": unknown socket type %s", map->map_mname, p); return false; } *colon++ = ':'; } else { colon = p; #if NETUNIX /* default to AF_UNIX */ addr.sa.sa_family = AF_UNIX; #else /* NETUNIX */ # if NETINET /* default to AF_INET */ addr.sa.sa_family = AF_INET; # else /* NETINET */ # if NETINET6 /* default to AF_INET6 */ addr.sa.sa_family = AF_INET6; # else /* NETINET6 */ syserr("socket map \"%s\": unknown socket type %s", map->map_mname, p); return false; # endif /* NETINET6 */ # endif /* NETINET */ #endif /* NETUNIX */ } # if NETUNIX if (addr.sa.sa_family == AF_UNIX) { long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_EXECOK; at = colon; if (strlen(colon) >= sizeof(addr.sunix.sun_path)) { syserr("socket map \"%s\": local socket name %s too long", map->map_mname, colon); return false; } errno = safefile(colon, RunAsUid, RunAsGid, RunAsUserName, sff, S_IRUSR|S_IWUSR, NULL); if (errno != 0) { /* if not safe, don't create */ syserr("socket map \"%s\": local socket name %s unsafe", map->map_mname, colon); return false; } (void) sm_strlcpy(addr.sunix.sun_path, colon, sizeof(addr.sunix.sun_path)); addrlen = sizeof(struct sockaddr_un); } else # endif /* NETUNIX */ # if NETINET || NETINET6 if (false # if NETINET || addr.sa.sa_family == AF_INET # endif /* NETINET */ # if NETINET6 || addr.sa.sa_family == AF_INET6 # endif /* NETINET6 */ ) { unsigned short port; /* Parse port@host */ at = strchr(colon, '@'); if (at == NULL) { syserr("socket map \"%s\": bad address %s (expected port@host)", map->map_mname, colon); return false; } *at = '\0'; if (isascii(*colon) && isdigit(*colon)) port = htons((unsigned short) atoi(colon)); else { # ifdef NO_GETSERVBYNAME syserr("socket map \"%s\": invalid port number %s", map->map_mname, colon); return false; # else /* NO_GETSERVBYNAME */ register struct servent *sp; sp = getservbyname(colon, "tcp"); if (sp == NULL) { syserr("socket map \"%s\": unknown port name %s", map->map_mname, colon); return false; } port = sp->s_port; # endif /* NO_GETSERVBYNAME */ } *at++ = '@'; if (*at == '[') { char *end; end = strchr(at, ']'); if (end != NULL) { bool found = false; # if NETINET unsigned long hid = INADDR_NONE; # endif /* NETINET */ # if NETINET6 struct sockaddr_in6 hid6; # endif /* NETINET6 */ *end = '\0'; # if NETINET if (addr.sa.sa_family == AF_INET && (hid = inet_addr(&at[1])) != INADDR_NONE) { addr.sin.sin_addr.s_addr = hid; addr.sin.sin_port = port; found = true; } # endif /* NETINET */ # if NETINET6 (void) memset(&hid6, '\0', sizeof(hid6)); if (addr.sa.sa_family == AF_INET6 && anynet_pton(AF_INET6, &at[1], &hid6.sin6_addr) == 1) { addr.sin6.sin6_addr = hid6.sin6_addr; addr.sin6.sin6_port = port; found = true; } # endif /* NETINET6 */ *end = ']'; if (!found) { syserr("socket map \"%s\": Invalid numeric domain spec \"%s\"", map->map_mname, at); return false; } } else { syserr("socket map \"%s\": Invalid numeric domain spec \"%s\"", map->map_mname, at); return false; } } else { hp = sm_gethostbyname(at, addr.sa.sa_family); if (hp == NULL) { syserr("socket map \"%s\": Unknown host name %s", map->map_mname, at); return false; } addr.sa.sa_family = hp->h_addrtype; switch (hp->h_addrtype) { # if NETINET case AF_INET: memmove(&addr.sin.sin_addr, hp->h_addr, INADDRSZ); addr.sin.sin_port = port; addrlen = sizeof(struct sockaddr_in); addrno = 1; break; # endif /* NETINET */ # if NETINET6 case AF_INET6: memmove(&addr.sin6.sin6_addr, hp->h_addr, IN6ADDRSZ); addr.sin6.sin6_port = port; addrlen = sizeof(struct sockaddr_in6); addrno = 1; break; # endif /* NETINET6 */ default: syserr("socket map \"%s\": Unknown protocol for %s (%d)", map->map_mname, at, hp->h_addrtype); # if NETINET6 freehostent(hp); # endif /* NETINET6 */ return false; } } } else # endif /* NETINET || NETINET6 */ { syserr("socket map \"%s\": unknown socket protocol", map->map_mname); return false; } /* nope, actually connecting */ for (;;) { sock = socket(addr.sa.sa_family, SOCK_STREAM, 0); if (sock < 0) { save_errno = errno; if (tTd(38, 5)) sm_dprintf("socket map \"%s\": error creating socket: %s\n", map->map_mname, sm_errstring(save_errno)); # if NETINET6 if (hp != NULL) freehostent(hp); # endif /* NETINET6 */ return false; } if (connect(sock, (struct sockaddr *) &addr, addrlen) >= 0) break; /* couldn't connect.... try next address */ save_errno = errno; p = CurHostName; CurHostName = at; if (tTd(38, 5)) sm_dprintf("socket_open (%s): open %s failed: %s\n", map->map_mname, at, sm_errstring(save_errno)); CurHostName = p; (void) close(sock); /* try next address */ if (hp != NULL && hp->h_addr_list[addrno] != NULL) { switch (addr.sa.sa_family) { # if NETINET case AF_INET: memmove(&addr.sin.sin_addr, hp->h_addr_list[addrno++], INADDRSZ); break; # endif /* NETINET */ # if NETINET6 case AF_INET6: memmove(&addr.sin6.sin6_addr, hp->h_addr_list[addrno++], IN6ADDRSZ); break; # endif /* NETINET6 */ default: if (tTd(38, 5)) sm_dprintf("socket map \"%s\": Unknown protocol for %s (%d)\n", map->map_mname, at, hp->h_addrtype); # if NETINET6 freehostent(hp); # endif /* NETINET6 */ return false; } continue; } p = CurHostName; CurHostName = at; if (tTd(38, 5)) sm_dprintf("socket map \"%s\": error connecting to socket map: %s\n", map->map_mname, sm_errstring(save_errno)); CurHostName = p; # if NETINET6 if (hp != NULL) freehostent(hp); # endif /* NETINET6 */ return false; } # if NETINET6 if (hp != NULL) { freehostent(hp); hp = NULL; } # endif /* NETINET6 */ if ((map->map_db1 = (ARBPTR_T) sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &sock, SM_IO_RDWR, NULL)) == NULL) { close(sock); if (tTd(38, 2)) sm_dprintf("socket_open (%s): failed to create stream: %s\n", map->map_mname, sm_errstring(errno)); return false; } /* Save connection for reuse */ s->s_socketmap = map; return true; } /* ** SOCKET_MAP_FINDCONN -- find a SOCKET connection to the server ** ** Cache SOCKET connections based on the connection specifier ** and PID so we don't have multiple connections open to ** the same server for different maps. Need a separate connection ** per PID since a parent process may close the map before the ** child is done with it. ** ** Parameters: ** conn -- SOCKET map connection specifier ** ** Returns: ** Symbol table entry for the SOCKET connection. */ static STAB * socket_map_findconn(conn) const char *conn; { char *nbuf; STAB *SM_NONVOLATILE s = NULL; nbuf = sm_stringf_x("%s%c%d", conn, CONDELSE, (int) CurrentPid); SM_TRY s = stab(nbuf, ST_SOCKETMAP, ST_ENTER); SM_FINALLY sm_free(nbuf); SM_END_TRY return s; } /* ** SOCKET_MAP_CLOSE -- close the socket */ void socket_map_close(map) MAP *map; { STAB *s; MAP *smap; if (tTd(38, 20)) sm_dprintf("socket_map_close(%s), pid=%ld\n", map->map_file, (long) CurrentPid); /* Check if already closed */ if (map->map_db1 == NULL) { if (tTd(38, 20)) sm_dprintf("socket_map_close(%s) already closed\n", map->map_file); return; } sm_io_close((SM_FILE_T *)map->map_db1, SM_TIME_DEFAULT); /* Mark all the maps that share the connection as closed */ s = socket_map_findconn(map->map_file); smap = s->s_socketmap; while (smap != NULL) { MAP *next; if (tTd(38, 2) && smap != map) sm_dprintf("socket_map_close(%s): closed %s (shared SOCKET connection)\n", map->map_mname, smap->map_mname); smap->map_mflags &= ~(MF_OPEN|MF_WRITABLE); smap->map_db1 = NULL; next = smap->socket_map_next; smap->socket_map_next = NULL; smap = next; } s->s_socketmap = NULL; } /* ** SOCKET_MAP_LOOKUP -- look up a datum in a SOCKET table */ char * socket_map_lookup(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { unsigned int nettolen, replylen, recvlen; char *replybuf, *rval, *value, *status, *key; SM_FILE_T *f; char keybuf[MAXNAME + 1]; replybuf = NULL; rval = NULL; f = (SM_FILE_T *)map->map_db1; if (tTd(38, 20)) sm_dprintf("socket_map_lookup(%s, %s) %s\n", map->map_mname, name, map->map_file); if (!bitset(MF_NOFOLDCASE, map->map_mflags)) { nettolen = strlen(name); if (nettolen > sizeof(keybuf) - 1) nettolen = sizeof(keybuf) - 1; memmove(keybuf, name, nettolen); keybuf[nettolen] = '\0'; makelower(keybuf); key = keybuf; } else key = name; nettolen = strlen(map->map_mname) + 1 + strlen(key); SM_ASSERT(nettolen > strlen(map->map_mname)); SM_ASSERT(nettolen > strlen(key)); if ((sm_io_fprintf(f, SM_TIME_DEFAULT, "%u:%s %s,", nettolen, map->map_mname, key) == SM_IO_EOF) || (sm_io_flush(f, SM_TIME_DEFAULT) != 0) || (sm_io_error(f))) { syserr("451 4.3.0 socket_map_lookup(%s): failed to send lookup request", map->map_mname); *statp = EX_TEMPFAIL; goto errcl; } if (sm_io_fscanf(f, SM_TIME_DEFAULT, "%9u", &replylen) != 1) { syserr("451 4.3.0 socket_map_lookup(%s): failed to read length parameter of reply", map->map_mname); *statp = EX_TEMPFAIL; goto errcl; } if (replylen > SOCKETMAP_MAXL) { syserr("451 4.3.0 socket_map_lookup(%s): reply too long: %u", map->map_mname, replylen); *statp = EX_TEMPFAIL; goto errcl; } if (sm_io_getc(f, SM_TIME_DEFAULT) != ':') { syserr("451 4.3.0 socket_map_lookup(%s): missing ':' in reply", map->map_mname); *statp = EX_TEMPFAIL; goto error; } replybuf = (char *) sm_malloc(replylen + 1); if (replybuf == NULL) { syserr("451 4.3.0 socket_map_lookup(%s): can't allocate %u bytes", map->map_mname, replylen + 1); *statp = EX_OSERR; goto error; } recvlen = sm_io_read(f, SM_TIME_DEFAULT, replybuf, replylen); if (recvlen < replylen) { syserr("451 4.3.0 socket_map_lookup(%s): received only %u of %u reply characters", map->map_mname, recvlen, replylen); *statp = EX_TEMPFAIL; goto errcl; } if (sm_io_getc(f, SM_TIME_DEFAULT) != ',') { syserr("451 4.3.0 socket_map_lookup(%s): missing ',' in reply", map->map_mname); *statp = EX_TEMPFAIL; goto errcl; } status = replybuf; replybuf[recvlen] = '\0'; value = strchr(replybuf, ' '); if (value != NULL) { *value = '\0'; value++; } if (strcmp(status, "OK") == 0) { *statp = EX_OK; /* collect the return value */ if (bitset(MF_MATCHONLY, map->map_mflags)) rval = map_rewrite(map, key, strlen(key), NULL); else rval = map_rewrite(map, value, strlen(value), av); } else if (strcmp(status, "NOTFOUND") == 0) { *statp = EX_NOTFOUND; if (tTd(38, 20)) sm_dprintf("socket_map_lookup(%s): %s not found\n", map->map_mname, key); } else { if (tTd(38, 5)) sm_dprintf("socket_map_lookup(%s, %s): server returned error: type=%s, reason=%s\n", map->map_mname, key, status, value ? value : ""); if ((strcmp(status, "TEMP") == 0) || (strcmp(status, "TIMEOUT") == 0)) *statp = EX_TEMPFAIL; else if(strcmp(status, "PERM") == 0) *statp = EX_UNAVAILABLE; else *statp = EX_PROTOCOL; } if (replybuf != NULL) sm_free(replybuf); return rval; errcl: socket_map_close(map); error: if (replybuf != NULL) sm_free(replybuf); return rval; } #endif /* SOCKETMAP */ Index: head/contrib/sendmail/src/mci.c =================================================================== --- head/contrib/sendmail/src/mci.c (revision 249728) +++ head/contrib/sendmail/src/mci.c (revision 249729) @@ -1,1607 +1,1607 @@ /* * Copyright (c) 1998-2005, 2010 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: mci.c,v 8.223 2010/03/10 04:35:28 ca Exp $") +SM_RCSID("@(#)$Id: mci.c,v 8.224 2013/03/12 15:24:53 ca Exp $") #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ #include static int mci_generate_persistent_path __P((const char *, char *, int, bool)); static bool mci_load_persistent __P((MCI *)); static void mci_uncache __P((MCI **, bool)); static int mci_lock_host_statfile __P((MCI *)); static int mci_read_persistent __P((SM_FILE_T *, MCI *)); /* ** Mail Connection Information (MCI) Caching Module. ** ** There are actually two separate things cached. The first is ** the set of all open connections -- these are stored in a ** (small) list. The second is stored in the symbol table; it ** has the overall status for all hosts, whether or not there ** is a connection open currently. ** ** There should never be too many connections open (since this ** could flood the socket table), nor should a connection be ** allowed to sit idly for too long. ** ** MaxMciCache is the maximum number of open connections that ** will be supported. ** ** MciCacheTimeout is the time (in seconds) that a connection ** is permitted to survive without activity. ** ** We actually try any cached connections by sending a RSET ** before we use them; if the RSET fails we close down the ** connection and reopen it (see smtpprobe()). ** ** The persistent MCI code is donated by Mark Lovell and Paul ** Vixie. It is based on the long term host status code in KJS ** written by Paul but has been adapted by Mark to fit into the ** MCI structure. */ static MCI **MciCache; /* the open connection cache */ /* ** MCI_CACHE -- enter a connection structure into the open connection cache ** ** This may cause something else to be flushed. ** ** Parameters: ** mci -- the connection to cache. ** ** Returns: ** none. */ void mci_cache(mci) register MCI *mci; { register MCI **mcislot; /* ** Find the best slot. This may cause expired connections ** to be closed. */ mcislot = mci_scan(mci); if (mcislot == NULL) { /* we don't support caching */ return; } if (mci->mci_host == NULL) return; /* if this is already cached, we are done */ if (bitset(MCIF_CACHED, mci->mci_flags)) return; /* otherwise we may have to clear the slot */ if (*mcislot != NULL) mci_uncache(mcislot, true); if (tTd(42, 5)) sm_dprintf("mci_cache: caching %p (%s) in slot %d\n", mci, mci->mci_host, (int) (mcislot - MciCache)); if (tTd(91, 100)) sm_syslog(LOG_DEBUG, CurEnv->e_id, "mci_cache: caching %lx (%.100s) in slot %d", (unsigned long) mci, mci->mci_host, (int) (mcislot - MciCache)); *mcislot = mci; mci->mci_flags |= MCIF_CACHED; } /* ** MCI_SCAN -- scan the cache, flush junk, and return best slot ** ** Parameters: ** savemci -- never flush this one. Can be null. ** ** Returns: ** The LRU (or empty) slot. */ MCI ** mci_scan(savemci) MCI *savemci; { time_t now; register MCI **bestmci; register MCI *mci; register int i; if (MaxMciCache <= 0) { /* we don't support caching */ return NULL; } if (MciCache == NULL) { /* first call */ MciCache = (MCI **) sm_pmalloc_x(MaxMciCache * sizeof(*MciCache)); memset((char *) MciCache, '\0', MaxMciCache * sizeof(*MciCache)); return &MciCache[0]; } now = curtime(); bestmci = &MciCache[0]; for (i = 0; i < MaxMciCache; i++) { mci = MciCache[i]; if (mci == NULL || mci->mci_state == MCIS_CLOSED) { bestmci = &MciCache[i]; continue; } if ((mci->mci_lastuse + MciCacheTimeout <= now || (mci->mci_mailer != NULL && mci->mci_mailer->m_maxdeliveries > 0 && mci->mci_deliveries + 1 >= mci->mci_mailer->m_maxdeliveries))&& mci != savemci) { /* connection idle too long or too many deliveries */ bestmci = &MciCache[i]; /* close it */ mci_uncache(bestmci, true); continue; } if (*bestmci == NULL) continue; if (mci->mci_lastuse < (*bestmci)->mci_lastuse) bestmci = &MciCache[i]; } return bestmci; } /* ** MCI_UNCACHE -- remove a connection from a slot. ** ** May close a connection. ** ** Parameters: ** mcislot -- the slot to empty. ** doquit -- if true, send QUIT protocol on this connection. ** if false, we are assumed to be in a forked child; ** all we want to do is close the file(s). ** ** Returns: ** none. */ static void mci_uncache(mcislot, doquit) register MCI **mcislot; bool doquit; { register MCI *mci; extern ENVELOPE BlankEnvelope; mci = *mcislot; if (mci == NULL) return; *mcislot = NULL; if (mci->mci_host == NULL) return; mci_unlock_host(mci); if (tTd(42, 5)) sm_dprintf("mci_uncache: uncaching %p (%s) from slot %d (%d)\n", mci, mci->mci_host, (int) (mcislot - MciCache), doquit); if (tTd(91, 100)) sm_syslog(LOG_DEBUG, CurEnv->e_id, "mci_uncache: uncaching %lx (%.100s) from slot %d (%d)", (unsigned long) mci, mci->mci_host, (int) (mcislot - MciCache), doquit); mci->mci_deliveries = 0; if (doquit) { message("Closing connection to %s", mci->mci_host); mci->mci_flags &= ~MCIF_CACHED; /* only uses the envelope to flush the transcript file */ if (mci->mci_state != MCIS_CLOSED) smtpquit(mci->mci_mailer, mci, &BlankEnvelope); #if XLA xla_host_end(mci->mci_host); #endif /* XLA */ } else { if (mci->mci_in != NULL) (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT); if (mci->mci_out != NULL) (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT); mci->mci_in = mci->mci_out = NULL; mci->mci_state = MCIS_CLOSED; mci->mci_exitstat = EX_OK; mci->mci_errno = 0; mci->mci_flags = 0; mci->mci_retryrcpt = false; mci->mci_tolist = NULL; #if PIPELINING mci->mci_okrcpts = 0; #endif /* PIPELINING */ } SM_FREE_CLR(mci->mci_status); SM_FREE_CLR(mci->mci_rstatus); SM_FREE_CLR(mci->mci_heloname); if (mci->mci_rpool != NULL) { sm_rpool_free(mci->mci_rpool); mci->mci_macro.mac_rpool = NULL; mci->mci_rpool = NULL; } } /* ** MCI_FLUSH -- flush the entire cache ** ** Parameters: ** doquit -- if true, send QUIT protocol. ** if false, just close the connection. ** allbut -- but leave this one open. ** ** Returns: ** none. */ void mci_flush(doquit, allbut) bool doquit; MCI *allbut; { register int i; if (MciCache == NULL) return; for (i = 0; i < MaxMciCache; i++) { if (allbut != MciCache[i]) mci_uncache(&MciCache[i], doquit); } } /* ** MCI_CLR_EXTENSIONS -- clear knowledge about SMTP extensions ** ** Parameters: ** mci -- the connection to clear. ** ** Returns: ** none. */ void mci_clr_extensions(mci) MCI *mci; { if (mci == NULL) return; mci->mci_flags &= ~MCIF_EXTENS; mci->mci_maxsize = 0; mci->mci_min_by = 0; #if SASL mci->mci_saslcap = NULL; #endif /* SASL */ } /* ** MCI_GET -- get information about a particular host ** ** Parameters: ** host -- host to look for. ** m -- mailer. ** ** Returns: ** mci for this host (might be new). */ MCI * mci_get(host, m) char *host; MAILER *m; { register MCI *mci; register STAB *s; extern SOCKADDR CurHostAddr; /* clear CurHostAddr so we don't get a bogus address with this name */ memset(&CurHostAddr, '\0', sizeof(CurHostAddr)); /* clear out any expired connections */ (void) mci_scan(NULL); if (m->m_mno < 0) syserr("!negative mno %d (%s)", m->m_mno, m->m_name); s = stab(host, ST_MCI + m->m_mno, ST_ENTER); mci = &s->s_mci; /* initialize per-message data */ mci->mci_retryrcpt = false; mci->mci_tolist = NULL; #if PIPELINING mci->mci_okrcpts = 0; #endif /* PIPELINING */ if (mci->mci_rpool == NULL) mci->mci_rpool = sm_rpool_new_x(NULL); if (mci->mci_macro.mac_rpool == NULL) mci->mci_macro.mac_rpool = mci->mci_rpool; /* ** We don't need to load the persistent data if we have data ** already loaded in the cache. */ if (mci->mci_host == NULL && (mci->mci_host = s->s_name) != NULL && !mci_load_persistent(mci)) { if (tTd(42, 2)) sm_dprintf("mci_get(%s %s): lock failed\n", host, m->m_name); mci->mci_exitstat = EX_TEMPFAIL; mci->mci_state = MCIS_CLOSED; mci->mci_statfile = NULL; return mci; } if (tTd(42, 2)) { sm_dprintf("mci_get(%s %s): mci_state=%d, _flags=%lx, _exitstat=%d, _errno=%d\n", host, m->m_name, mci->mci_state, mci->mci_flags, mci->mci_exitstat, mci->mci_errno); } if (mci->mci_state == MCIS_OPEN) { /* poke the connection to see if it's still alive */ (void) smtpprobe(mci); /* reset the stored state in the event of a timeout */ if (mci->mci_state != MCIS_OPEN) { mci->mci_errno = 0; mci->mci_exitstat = EX_OK; mci->mci_state = MCIS_CLOSED; } else { /* get peer host address */ /* (this should really be in the mci struct) */ SOCKADDR_LEN_T socklen = sizeof(CurHostAddr); (void) getpeername(sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL), (struct sockaddr *) &CurHostAddr, &socklen); } } if (mci->mci_state == MCIS_CLOSED) { time_t now = curtime(); /* if this info is stale, ignore it */ if (mci->mci_lastuse + MciInfoTimeout <= now) { mci->mci_lastuse = now; mci->mci_errno = 0; mci->mci_exitstat = EX_OK; } } return mci; } /* ** MCI_CLOSE -- (forcefully) close files used for a connection. ** Note: this is a last resort, usually smtpquit() or endmailer() ** should be used to close a connection. ** ** Parameters: ** mci -- the connection to close. ** where -- where has this been called? ** ** Returns: ** none. */ void mci_close(mci, where) MCI *mci; char *where; { bool dumped; if (mci == NULL) return; dumped = false; if (mci->mci_out != NULL) { if (tTd(56, 1)) { sm_dprintf("mci_close: mci_out!=NULL, where=%s\n", where); mci_dump(sm_debug_file(), mci, false); dumped = true; } (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT); mci->mci_out = NULL; } if (mci->mci_in != NULL) { if (tTd(56, 1)) { sm_dprintf("mci_close: mci_in!=NULL, where=%s\n", where); if (!dumped) mci_dump(sm_debug_file(), mci, false); } (void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT); mci->mci_in = NULL; } mci->mci_state = MCIS_CLOSED; } /* ** MCI_NEW -- allocate new MCI structure ** ** Parameters: ** rpool -- if non-NULL: allocate from that rpool. ** ** Returns: ** mci (new). */ MCI * mci_new(rpool) SM_RPOOL_T *rpool; { register MCI *mci; if (rpool == NULL) mci = (MCI *) sm_malloc_x(sizeof(*mci)); else mci = (MCI *) sm_rpool_malloc_x(rpool, sizeof(*mci)); memset((char *) mci, '\0', sizeof(*mci)); mci->mci_rpool = sm_rpool_new_x(NULL); mci->mci_macro.mac_rpool = mci->mci_rpool; return mci; } /* ** MCI_MATCH -- check connection cache for a particular host ** ** Parameters: ** host -- host to look for. ** m -- mailer. ** ** Returns: ** true iff open connection exists. */ bool mci_match(host, m) char *host; MAILER *m; { register MCI *mci; register STAB *s; if (m->m_mno < 0 || m->m_mno > MAXMAILERS) return false; s = stab(host, ST_MCI + m->m_mno, ST_FIND); if (s == NULL) return false; mci = &s->s_mci; return mci->mci_state == MCIS_OPEN; } /* ** MCI_SETSTAT -- set status codes in MCI structure. ** ** Parameters: ** mci -- the MCI structure to set. ** xstat -- the exit status code. ** dstat -- the DSN status code. ** rstat -- the SMTP status code. ** ** Returns: ** none. */ void mci_setstat(mci, xstat, dstat, rstat) MCI *mci; int xstat; char *dstat; char *rstat; { /* protocol errors should never be interpreted as sticky */ if (xstat != EX_NOTSTICKY && xstat != EX_PROTOCOL) mci->mci_exitstat = xstat; SM_FREE_CLR(mci->mci_status); if (dstat != NULL) mci->mci_status = sm_strdup_x(dstat); SM_FREE_CLR(mci->mci_rstatus); if (rstat != NULL) mci->mci_rstatus = sm_strdup_x(rstat); } /* ** MCI_DUMP -- dump the contents of an MCI structure. ** ** Parameters: ** fp -- output file pointer ** mci -- the MCI structure to dump. ** ** Returns: ** none. ** ** Side Effects: ** none. */ struct mcifbits { int mcif_bit; /* flag bit */ char *mcif_name; /* flag name */ }; static struct mcifbits MciFlags[] = { { MCIF_VALID, "VALID" }, { MCIF_CACHED, "CACHED" }, { MCIF_ESMTP, "ESMTP" }, { MCIF_EXPN, "EXPN" }, { MCIF_SIZE, "SIZE" }, { MCIF_8BITMIME, "8BITMIME" }, { MCIF_7BIT, "7BIT" }, { MCIF_INHEADER, "INHEADER" }, { MCIF_CVT8TO7, "CVT8TO7" }, { MCIF_DSN, "DSN" }, { MCIF_8BITOK, "8BITOK" }, { MCIF_CVT7TO8, "CVT7TO8" }, { MCIF_INMIME, "INMIME" }, { MCIF_AUTH, "AUTH" }, { MCIF_AUTH2, "AUTH2" }, { MCIF_AUTHACT, "AUTHACT" }, { MCIF_ENHSTAT, "ENHSTAT" }, { MCIF_PIPELINED, "PIPELINED" }, #if STARTTLS { MCIF_TLS, "TLS" }, { MCIF_TLSACT, "TLSACT" }, #endif /* STARTTLS */ { MCIF_DLVR_BY, "DLVR_BY" }, { 0, NULL } }; void mci_dump(fp, mci, logit) SM_FILE_T *fp; register MCI *mci; bool logit; { register char *p; char *sep; char buf[4000]; sep = logit ? " " : "\n\t"; p = buf; (void) sm_snprintf(p, SPACELEFT(buf, p), "MCI@%p: ", mci); p += strlen(p); if (mci == NULL) { (void) sm_snprintf(p, SPACELEFT(buf, p), "NULL"); goto printit; } (void) sm_snprintf(p, SPACELEFT(buf, p), "flags=%lx", mci->mci_flags); p += strlen(p); /* ** The following check is just for paranoia. It protects the ** assignment in the if() clause. If there's not some minimum ** amount of space we can stop right now. The check will not ** trigger as long as sizeof(buf)=4000. */ if (p >= buf + sizeof(buf) - 4) goto printit; if (mci->mci_flags != 0) { struct mcifbits *f; *p++ = '<'; /* protected above */ for (f = MciFlags; f->mcif_bit != 0; f++) { if (!bitset(f->mcif_bit, mci->mci_flags)) continue; (void) sm_strlcpyn(p, SPACELEFT(buf, p), 2, f->mcif_name, ","); p += strlen(p); } p[-1] = '>'; } /* Note: sm_snprintf() takes care of NULL arguments for %s */ (void) sm_snprintf(p, SPACELEFT(buf, p), ",%serrno=%d, herrno=%d, exitstat=%d, state=%d, pid=%d,%s", sep, mci->mci_errno, mci->mci_herrno, mci->mci_exitstat, mci->mci_state, (int) mci->mci_pid, sep); p += strlen(p); (void) sm_snprintf(p, SPACELEFT(buf, p), "maxsize=%ld, phase=%s, mailer=%s,%s", mci->mci_maxsize, mci->mci_phase, mci->mci_mailer == NULL ? "NULL" : mci->mci_mailer->m_name, sep); p += strlen(p); (void) sm_snprintf(p, SPACELEFT(buf, p), "status=%s, rstatus=%s,%s", mci->mci_status, mci->mci_rstatus, sep); p += strlen(p); (void) sm_snprintf(p, SPACELEFT(buf, p), "host=%s, lastuse=%s", mci->mci_host, ctime(&mci->mci_lastuse)); printit: if (logit) sm_syslog(LOG_DEBUG, CurEnv->e_id, "%.1000s", buf); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s\n", buf); } /* ** MCI_DUMP_ALL -- print the entire MCI cache ** ** Parameters: ** fp -- output file pointer ** logit -- if set, log the result instead of printing ** to stdout. ** ** Returns: ** none. */ void mci_dump_all(fp, logit) SM_FILE_T *fp; bool logit; { register int i; if (MciCache == NULL) return; for (i = 0; i < MaxMciCache; i++) mci_dump(fp, MciCache[i], logit); } /* ** MCI_LOCK_HOST -- Lock host while sending. ** ** If we are contacting a host, we'll need to ** update the status information in the host status ** file, and if we want to do that, we ought to have ** locked it. This has the (according to some) ** desirable effect of serializing connectivity with ** remote hosts -- i.e.: one connection to a given ** host at a time. ** ** Parameters: ** mci -- containing the host we want to lock. ** ** Returns: ** EX_OK -- got the lock. ** EX_TEMPFAIL -- didn't get the lock. */ int mci_lock_host(mci) MCI *mci; { if (mci == NULL) { if (tTd(56, 1)) sm_dprintf("mci_lock_host: NULL mci\n"); return EX_OK; } if (!SingleThreadDelivery) return EX_OK; return mci_lock_host_statfile(mci); } static int mci_lock_host_statfile(mci) MCI *mci; { int save_errno = errno; int retVal = EX_OK; char fname[MAXPATHLEN]; if (HostStatDir == NULL || mci->mci_host == NULL) return EX_OK; if (tTd(56, 2)) sm_dprintf("mci_lock_host: attempting to lock %s\n", mci->mci_host); if (mci_generate_persistent_path(mci->mci_host, fname, sizeof(fname), true) < 0) { /* of course this should never happen */ if (tTd(56, 2)) sm_dprintf("mci_lock_host: Failed to generate host path for %s\n", mci->mci_host); retVal = EX_TEMPFAIL; goto cleanup; } mci->mci_statfile = safefopen(fname, O_RDWR, FileMode, SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH|SFF_CREAT); if (mci->mci_statfile == NULL) { syserr("mci_lock_host: cannot create host lock file %s", fname); goto cleanup; } if (!lockfile(sm_io_getinfo(mci->mci_statfile, SM_IO_WHAT_FD, NULL), fname, "", LOCK_EX|LOCK_NB)) { if (tTd(56, 2)) sm_dprintf("mci_lock_host: couldn't get lock on %s\n", fname); (void) sm_io_close(mci->mci_statfile, SM_TIME_DEFAULT); mci->mci_statfile = NULL; retVal = EX_TEMPFAIL; goto cleanup; } if (tTd(56, 12) && mci->mci_statfile != NULL) sm_dprintf("mci_lock_host: Sanity check -- lock is good\n"); cleanup: errno = save_errno; return retVal; } /* ** MCI_UNLOCK_HOST -- unlock host ** ** Clean up the lock on a host, close the file, let ** someone else use it. ** ** Parameters: ** mci -- us. ** ** Returns: ** nothing. */ void mci_unlock_host(mci) MCI *mci; { int save_errno = errno; if (mci == NULL) { if (tTd(56, 1)) sm_dprintf("mci_unlock_host: NULL mci\n"); return; } if (HostStatDir == NULL || mci->mci_host == NULL) return; if (!SingleThreadDelivery && mci_lock_host_statfile(mci) == EX_TEMPFAIL) { if (tTd(56, 1)) sm_dprintf("mci_unlock_host: stat file already locked\n"); } else { if (tTd(56, 2)) sm_dprintf("mci_unlock_host: store prior to unlock\n"); mci_store_persistent(mci); } if (mci->mci_statfile != NULL) { (void) sm_io_close(mci->mci_statfile, SM_TIME_DEFAULT); mci->mci_statfile = NULL; } errno = save_errno; } /* ** MCI_LOAD_PERSISTENT -- load persistent host info ** ** Load information about host that is kept ** in common for all running sendmails. ** ** Parameters: ** mci -- the host/connection to load persistent info for. ** ** Returns: ** true -- lock was successful ** false -- lock failed */ static bool mci_load_persistent(mci) MCI *mci; { int save_errno = errno; bool locked = true; SM_FILE_T *fp; char fname[MAXPATHLEN]; if (mci == NULL) { if (tTd(56, 1)) sm_dprintf("mci_load_persistent: NULL mci\n"); return true; } if (IgnoreHostStatus || HostStatDir == NULL || mci->mci_host == NULL) return true; /* Already have the persistent information in memory */ if (SingleThreadDelivery && mci->mci_statfile != NULL) return true; if (tTd(56, 1)) sm_dprintf("mci_load_persistent: Attempting to load persistent information for %s\n", mci->mci_host); if (mci_generate_persistent_path(mci->mci_host, fname, sizeof(fname), false) < 0) { /* Not much we can do if the file isn't there... */ if (tTd(56, 1)) sm_dprintf("mci_load_persistent: Couldn't generate host path\n"); goto cleanup; } fp = safefopen(fname, O_RDONLY, FileMode, SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH); if (fp == NULL) { /* I can't think of any reason this should ever happen */ if (tTd(56, 1)) sm_dprintf("mci_load_persistent: open(%s): %s\n", fname, sm_errstring(errno)); goto cleanup; } FileName = fname; locked = lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), fname, "", LOCK_SH|LOCK_NB); if (locked) { (void) mci_read_persistent(fp, mci); (void) lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), fname, "", LOCK_UN); } FileName = NULL; (void) sm_io_close(fp, SM_TIME_DEFAULT); cleanup: errno = save_errno; return locked; } /* ** MCI_READ_PERSISTENT -- read persistent host status file ** ** Parameters: ** fp -- the file pointer to read. ** mci -- the pointer to fill in. ** ** Returns: ** -1 -- if the file was corrupt. ** 0 -- otherwise. ** ** Warning: ** This code makes the assumption that this data ** will be read in an atomic fashion, and that the data ** was written in an atomic fashion. Any other functioning ** may lead to some form of insanity. This should be ** perfectly safe due to underlying stdio buffering. */ static int mci_read_persistent(fp, mci) SM_FILE_T *fp; register MCI *mci; { int ver; register char *p; int saveLineNumber = LineNumber; char buf[MAXLINE]; if (fp == NULL) { syserr("mci_read_persistent: NULL fp"); /* NOTREACHED */ return -1; } if (mci == NULL) { syserr("mci_read_persistent: NULL mci"); /* NOTREACHED */ return -1; } if (tTd(56, 93)) { sm_dprintf("mci_read_persistent: fp=%lx, mci=", (unsigned long) fp); } SM_FREE_CLR(mci->mci_status); SM_FREE_CLR(mci->mci_rstatus); sm_io_rewind(fp, SM_TIME_DEFAULT); ver = -1; LineNumber = 0; - while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { LineNumber++; p = strchr(buf, '\n'); if (p != NULL) *p = '\0'; switch (buf[0]) { case 'V': /* version stamp */ ver = atoi(&buf[1]); if (ver < 0 || ver > 0) syserr("Unknown host status version %d: %d max", ver, 0); break; case 'E': /* UNIX error number */ mci->mci_errno = atoi(&buf[1]); break; case 'H': /* DNS error number */ mci->mci_herrno = atoi(&buf[1]); break; case 'S': /* UNIX exit status */ mci->mci_exitstat = atoi(&buf[1]); break; case 'D': /* DSN status */ mci->mci_status = newstr(&buf[1]); break; case 'R': /* SMTP status */ mci->mci_rstatus = newstr(&buf[1]); break; case 'U': /* last usage time */ mci->mci_lastuse = atol(&buf[1]); break; case '.': /* end of file */ if (tTd(56, 93)) mci_dump(sm_debug_file(), mci, false); return 0; default: sm_syslog(LOG_CRIT, NOQID, "%s: line %d: Unknown host status line \"%s\"", FileName == NULL ? mci->mci_host : FileName, LineNumber, buf); LineNumber = saveLineNumber; return -1; } } LineNumber = saveLineNumber; if (tTd(56, 93)) sm_dprintf("incomplete (missing dot for EOF)\n"); if (ver < 0) return -1; return 0; } /* ** MCI_STORE_PERSISTENT -- Store persistent MCI information ** ** Store information about host that is kept ** in common for all running sendmails. ** ** Parameters: ** mci -- the host/connection to store persistent info for. ** ** Returns: ** none. */ void mci_store_persistent(mci) MCI *mci; { int save_errno = errno; if (mci == NULL) { if (tTd(56, 1)) sm_dprintf("mci_store_persistent: NULL mci\n"); return; } if (HostStatDir == NULL || mci->mci_host == NULL) return; if (tTd(56, 1)) sm_dprintf("mci_store_persistent: Storing information for %s\n", mci->mci_host); if (mci->mci_statfile == NULL) { if (tTd(56, 1)) sm_dprintf("mci_store_persistent: no statfile\n"); return; } sm_io_rewind(mci->mci_statfile, SM_TIME_DEFAULT); #if !NOFTRUNCATE (void) ftruncate(sm_io_getinfo(mci->mci_statfile, SM_IO_WHAT_FD, NULL), (off_t) 0); #endif /* !NOFTRUNCATE */ (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "V0\n"); (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "E%d\n", mci->mci_errno); (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "H%d\n", mci->mci_herrno); (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "S%d\n", mci->mci_exitstat); if (mci->mci_status != NULL) (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "D%.80s\n", denlstring(mci->mci_status, true, false)); if (mci->mci_rstatus != NULL) (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "R%.80s\n", denlstring(mci->mci_rstatus, true, false)); (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, "U%ld\n", (long)(mci->mci_lastuse)); (void) sm_io_fprintf(mci->mci_statfile, SM_TIME_DEFAULT, ".\n"); (void) sm_io_flush(mci->mci_statfile, SM_TIME_DEFAULT); errno = save_errno; return; } /* ** MCI_TRAVERSE_PERSISTENT -- walk persistent status tree ** ** Recursively find all the mci host files in `pathname'. Default to ** main host status directory if no path is provided. ** Call (*action)(pathname, host) for each file found. ** ** Note: all information is collected in a list before it is processed. ** This may not be the best way to do it, but it seems safest, since ** the file system would be touched while we are attempting to traverse ** the directory tree otherwise (during purges). ** ** Parameters: ** action -- function to call on each node. If returns < 0, ** return immediately. ** pathname -- root of tree. If null, use main host status ** directory. ** ** Returns: ** < 0 -- if any action routine returns a negative value, that ** value is returned. ** 0 -- if we successfully went to completion. ** > 0 -- return status from action() */ int mci_traverse_persistent(action, pathname) int (*action)__P((char *, char *)); char *pathname; { struct stat statbuf; DIR *d; int ret; if (pathname == NULL) pathname = HostStatDir; if (pathname == NULL) return -1; if (tTd(56, 1)) sm_dprintf("mci_traverse: pathname is %s\n", pathname); ret = stat(pathname, &statbuf); if (ret < 0) { if (tTd(56, 2)) sm_dprintf("mci_traverse: Failed to stat %s: %s\n", pathname, sm_errstring(errno)); return ret; } if (S_ISDIR(statbuf.st_mode)) { bool leftone, removedone; size_t len; char *newptr; struct dirent *e; char newpath[MAXPATHLEN]; #if MAXPATHLEN <= MAXNAMLEN - 3 ERROR "MAXPATHLEN <= MAXNAMLEN - 3" #endif /* MAXPATHLEN <= MAXNAMLEN - 3 */ if ((d = opendir(pathname)) == NULL) { if (tTd(56, 2)) sm_dprintf("mci_traverse: opendir %s: %s\n", pathname, sm_errstring(errno)); return -1; } /* ** Reserve space for trailing '/', at least one ** character, and '\0' */ len = sizeof(newpath) - 3; if (sm_strlcpy(newpath, pathname, len) >= len) { int save_errno = errno; if (tTd(56, 2)) sm_dprintf("mci_traverse: path \"%s\" too long", pathname); (void) closedir(d); errno = save_errno; return -1; } newptr = newpath + strlen(newpath); *newptr++ = '/'; len = sizeof(newpath) - (newptr - newpath); /* ** repeat until no file has been removed ** this may become ugly when several files "expire" ** during these loops, but it's better than doing ** a rewinddir() inside the inner loop */ do { leftone = removedone = false; while ((e = readdir(d)) != NULL) { if (e->d_name[0] == '.') continue; if (sm_strlcpy(newptr, e->d_name, len) >= len) { /* Skip truncated copies */ if (tTd(56, 4)) { *newptr = '\0'; sm_dprintf("mci_traverse: path \"%s%s\" too long", newpath, e->d_name); } continue; } if (StopRequest) stop_sendmail(); ret = mci_traverse_persistent(action, newpath); if (ret < 0) break; if (ret == 1) leftone = true; if (!removedone && ret == 0 && action == mci_purge_persistent) removedone = true; } if (ret < 0) break; /* ** The following appears to be ** necessary during purges, since ** we modify the directory structure */ if (removedone) rewinddir(d); if (tTd(56, 40)) sm_dprintf("mci_traverse: path %s: ret %d removed %d left %d\n", pathname, ret, removedone, leftone); } while (removedone); /* purge (or whatever) the directory proper */ if (!leftone) { *--newptr = '\0'; ret = (*action)(newpath, NULL); } (void) closedir(d); } else if (S_ISREG(statbuf.st_mode)) { char *end = pathname + strlen(pathname) - 1; char *start; char *scan; char host[MAXHOSTNAMELEN]; char *hostptr = host; /* ** Reconstruct the host name from the path to the ** persistent information. */ do { if (hostptr != host) *(hostptr++) = '.'; start = end; while (start > pathname && *(start - 1) != '/') start--; if (*end == '.') end--; for (scan = start; scan <= end; scan++) *(hostptr++) = *scan; end = start - 2; } while (end > pathname && *end == '.'); *hostptr = '\0'; /* ** Do something with the file containing the persistent ** information. */ ret = (*action)(pathname, host); } return ret; } /* ** MCI_PRINT_PERSISTENT -- print persistent info ** ** Dump the persistent information in the file 'pathname' ** ** Parameters: ** pathname -- the pathname to the status file. ** hostname -- the corresponding host name. ** ** Returns: ** 0 */ int mci_print_persistent(pathname, hostname) char *pathname; char *hostname; { static bool initflag = false; SM_FILE_T *fp; int width = Verbose ? 78 : 25; bool locked; MCI mcib; /* skip directories */ if (hostname == NULL) return 0; if (StopRequest) stop_sendmail(); if (!initflag) { initflag = true; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " -------------- Hostname --------------- How long ago ---------Results---------\n"); } fp = safefopen(pathname, O_RDONLY, FileMode, SFF_NOLOCK|SFF_NOLINK|SFF_OPENASROOT|SFF_REGONLY|SFF_SAFEDIRPATH); if (fp == NULL) { if (tTd(56, 1)) sm_dprintf("mci_print_persistent: cannot open %s: %s\n", pathname, sm_errstring(errno)); return 0; } FileName = pathname; memset(&mcib, '\0', sizeof(mcib)); if (mci_read_persistent(fp, &mcib) < 0) { syserr("%s: could not read status file", pathname); (void) sm_io_close(fp, SM_TIME_DEFAULT); FileName = NULL; return 0; } locked = !lockfile(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), pathname, "", LOCK_SH|LOCK_NB); (void) sm_io_close(fp, SM_TIME_DEFAULT); FileName = NULL; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%c%-39s %12s ", locked ? '*' : ' ', hostname, pintvl(curtime() - mcib.mci_lastuse, true)); if (mcib.mci_rstatus != NULL) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n", width, mcib.mci_rstatus); else if (mcib.mci_exitstat == EX_TEMPFAIL && mcib.mci_errno != 0) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Deferred: %.*s\n", width - 10, sm_errstring(mcib.mci_errno)); else if (mcib.mci_exitstat != 0) { char *exmsg = sm_sysexmsg(mcib.mci_exitstat); if (exmsg == NULL) { char buf[80]; (void) sm_snprintf(buf, sizeof(buf), "Unknown mailer error %d", mcib.mci_exitstat); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n", width, buf); } else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%.*s\n", width, &exmsg[5]); } else if (mcib.mci_errno == 0) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK\n"); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK: %.*s\n", width - 4, sm_errstring(mcib.mci_errno)); return 0; } /* ** MCI_PURGE_PERSISTENT -- Remove a persistence status file. ** ** Parameters: ** pathname -- path to the status file. ** hostname -- name of host corresponding to that file. ** NULL if this is a directory (domain). ** ** Returns: ** 0 -- ok ** 1 -- file not deleted (too young, incorrect format) ** < 0 -- some error occurred */ int mci_purge_persistent(pathname, hostname) char *pathname; char *hostname; { struct stat statbuf; char *end = pathname + strlen(pathname) - 1; int ret; if (tTd(56, 1)) sm_dprintf("mci_purge_persistent: purging %s\n", pathname); ret = stat(pathname, &statbuf); if (ret < 0) { if (tTd(56, 2)) sm_dprintf("mci_purge_persistent: Failed to stat %s: %s\n", pathname, sm_errstring(errno)); return ret; } if (curtime() - statbuf.st_mtime <= MciInfoTimeout) return 1; if (hostname != NULL) { /* remove the file */ ret = unlink(pathname); if (ret < 0) { if (LogLevel > 8) sm_syslog(LOG_ERR, NOQID, "mci_purge_persistent: failed to unlink %s: %s", pathname, sm_errstring(errno)); if (tTd(56, 2)) sm_dprintf("mci_purge_persistent: failed to unlink %s: %s\n", pathname, sm_errstring(errno)); return ret; } } else { /* remove the directory */ if (*end != '.') return 1; if (tTd(56, 1)) sm_dprintf("mci_purge_persistent: dpurge %s\n", pathname); ret = rmdir(pathname); if (ret < 0) { if (tTd(56, 2)) sm_dprintf("mci_purge_persistent: rmdir %s: %s\n", pathname, sm_errstring(errno)); return ret; } } return 0; } /* ** MCI_GENERATE_PERSISTENT_PATH -- generate path from hostname ** ** Given `host', convert from a.b.c to $HostStatDir/c./b./a, ** putting the result into `path'. if `createflag' is set, intervening ** directories will be created as needed. ** ** Parameters: ** host -- host name to convert from. ** path -- place to store result. ** pathlen -- length of path buffer. ** createflag -- if set, create intervening directories as ** needed. ** ** Returns: ** 0 -- success ** -1 -- failure */ static int mci_generate_persistent_path(host, path, pathlen, createflag) const char *host; char *path; int pathlen; bool createflag; { char *elem, *p, *x, ch; int ret = 0; int len; char t_host[MAXHOSTNAMELEN]; #if NETINET6 struct in6_addr in6_addr; #endif /* NETINET6 */ /* ** Rationality check the arguments. */ if (host == NULL) { syserr("mci_generate_persistent_path: null host"); return -1; } if (path == NULL) { syserr("mci_generate_persistent_path: null path"); return -1; } if (tTd(56, 80)) sm_dprintf("mci_generate_persistent_path(%s): ", host); if (*host == '\0' || *host == '.') return -1; /* make certain this is not a bracketed host number */ if (strlen(host) > sizeof(t_host) - 1) return -1; if (host[0] == '[') (void) sm_strlcpy(t_host, host + 1, sizeof(t_host)); else (void) sm_strlcpy(t_host, host, sizeof(t_host)); /* ** Delete any trailing dots from the hostname. ** Leave 'elem' pointing at the \0. */ elem = t_host + strlen(t_host); while (elem > t_host && (elem[-1] == '.' || (host[0] == '[' && elem[-1] == ']'))) *--elem = '\0'; /* check for bogus bracketed address */ if (host[0] == '[') { bool good = false; # if NETINET6 if (anynet_pton(AF_INET6, t_host, &in6_addr) == 1) good = true; # endif /* NETINET6 */ # if NETINET if (inet_addr(t_host) != INADDR_NONE) good = true; # endif /* NETINET */ if (!good) return -1; } /* check for what will be the final length of the path */ len = strlen(HostStatDir) + 2; for (p = (char *) t_host; *p != '\0'; p++) { if (*p == '.') len++; len++; if (p[0] == '.' && p[1] == '.') return -1; } if (len > pathlen || len < 1) return -1; (void) sm_strlcpy(path, HostStatDir, pathlen); p = path + strlen(path); while (elem > t_host) { if (!path_is_dir(path, createflag)) { ret = -1; break; } elem--; while (elem >= t_host && *elem != '.') elem--; *p++ = '/'; x = elem + 1; while ((ch = *x++) != '\0' && ch != '.') { if (isascii(ch) && isupper(ch)) ch = tolower(ch); if (ch == '/') ch = ':'; /* / -> : */ *p++ = ch; } if (elem >= t_host) *p++ = '.'; *p = '\0'; } if (tTd(56, 80)) { if (ret < 0) sm_dprintf("FAILURE %d\n", ret); else sm_dprintf("SUCCESS %s\n", path); } return ret; } Index: head/contrib/sendmail/src/milter.c =================================================================== --- head/contrib/sendmail/src/milter.c (revision 249728) +++ head/contrib/sendmail/src/milter.c (revision 249729) @@ -1,4781 +1,4780 @@ /* - * Copyright (c) 1999-2009 Sendmail, Inc. and its suppliers. + * Copyright (c) 1999-2009, 2012, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: milter.c,v 8.279 2012/11/16 20:25:03 ca Exp $") +SM_RCSID("@(#)$Id: milter.c,v 8.280 2013/01/16 18:48:36 ca Exp $") #if MILTER # include # include # include # include # include # include # if NETINET || NETINET6 # include # if MILTER_NO_NAGLE # include # endif /* MILTER_NO_NAGLE */ # endif /* NETINET || NETINET6 */ # include static void milter_connect_timeout __P((int)); static void milter_error __P((struct milter *, ENVELOPE *)); static int milter_open __P((struct milter *, bool, ENVELOPE *)); static void milter_parse_timeouts __P((char *, struct milter *)); static char *milter_sysread __P((struct milter *, char *, ssize_t, time_t, ENVELOPE *, const char *)); static char *milter_read __P((struct milter *, char *, ssize_t *, time_t, ENVELOPE *, const char *)); static char *milter_write __P((struct milter *, int, char *, ssize_t, time_t, ENVELOPE *, const char *)); static char *milter_send_command __P((struct milter *, int, void *, ssize_t, ENVELOPE *, char *, const char *)); static char *milter_command __P((int, void *, ssize_t, int, ENVELOPE *, char *, const char *, bool)); static char *milter_body __P((struct milter *, ENVELOPE *, char *)); static int milter_reopen_df __P((ENVELOPE *)); static int milter_reset_df __P((ENVELOPE *)); static void milter_quit_filter __P((struct milter *, ENVELOPE *)); static void milter_abort_filter __P((struct milter *, ENVELOPE *)); static void milter_send_macros __P((struct milter *, char **, int, ENVELOPE *)); static int milter_negotiate __P((struct milter *, ENVELOPE *, milters_T *)); static void milter_per_connection_check __P((ENVELOPE *)); static char *milter_headers __P((struct milter *, ENVELOPE *, char *)); static void milter_addheader __P((struct milter *, char *, ssize_t, ENVELOPE *)); static void milter_insheader __P((struct milter *, char *, ssize_t, ENVELOPE *)); static void milter_changeheader __P((struct milter *, char *, ssize_t, ENVELOPE *)); static void milter_chgfrom __P((char *, ssize_t, ENVELOPE *)); static void milter_addrcpt __P((char *, ssize_t, ENVELOPE *)); static void milter_addrcpt_par __P((char *, ssize_t, ENVELOPE *)); static void milter_delrcpt __P((char *, ssize_t, ENVELOPE *)); static int milter_replbody __P((char *, ssize_t, bool, ENVELOPE *)); static int milter_set_macros __P((char *, char **, char *, int)); /* milter states */ # define SMFS_CLOSED 'C' /* closed for all further actions */ # define SMFS_OPEN 'O' /* connected to remote milter filter */ # define SMFS_INMSG 'M' /* currently servicing a message */ # define SMFS_DONE 'D' /* done with current message */ # define SMFS_CLOSABLE 'Q' /* done with current connection */ # define SMFS_ERROR 'E' /* error state */ # define SMFS_READY 'R' /* ready for action */ # define SMFS_SKIP 'S' /* skip body */ /* ** MilterMacros contains the milter macros for each milter and each stage. ** indices are (in order): stages, milter-index, macro ** milter-index == 0: "global" macros (not for a specific milter). */ static char *MilterMacros[SMFIM_LAST + 1][MAXFILTERS + 1][MAXFILTERMACROS + 1]; static size_t MilterMaxDataSize = MILTER_MAX_DATA_SIZE; # define MILTER_CHECK_DONE_MSG() \ if (*state == SMFIR_REPLYCODE || \ *state == SMFIR_REJECT || \ *state == SMFIR_DISCARD || \ *state == SMFIR_TEMPFAIL) \ { \ /* Abort the filters to let them know we are done with msg */ \ milter_abort(e); \ } /* set state in case of an error */ # define MILTER_SET_STATE \ if (bitnset(SMF_TEMPFAIL, m->mf_flags)) \ *state = SMFIR_TEMPFAIL; \ else if (bitnset(SMF_TEMPDROP, m->mf_flags)) \ *state = SMFIR_SHUTDOWN; \ else if (bitnset(SMF_REJECT, m->mf_flags)) \ *state = SMFIR_REJECT /* flow through code maybe using continue; don't wrap in do {} while */ # define MILTER_CHECK_ERROR(initial, action) \ if (!initial && tTd(71, 100)) \ { \ if (e->e_quarmsg == NULL) \ { \ e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \ "filter failure"); \ macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \ e->e_quarmsg); \ } \ } \ else if (tTd(71, 101)) \ { \ if (e->e_quarmsg == NULL) \ { \ e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \ "filter failure"); \ macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \ e->e_quarmsg); \ } \ } \ else MILTER_SET_STATE; \ else \ action; # define MILTER_CHECK_REPLYCODE(default) \ if (response == NULL || \ strlen(response) + 1 != (size_t) rlen || \ rlen < 3 || \ (response[0] != '4' && response[0] != '5') || \ !isascii(response[1]) || !isdigit(response[1]) || \ !isascii(response[2]) || !isdigit(response[2])) \ { \ if (response != NULL) \ sm_free(response); /* XXX */ \ response = newstr(default); \ } \ else \ { \ char *ptr = response; \ \ /* Check for unprotected %'s in the string */ \ while (*ptr != '\0') \ { \ if (*ptr == '%' && *++ptr != '%') \ { \ sm_free(response); /* XXX */ \ response = newstr(default); \ break; \ } \ ptr++; \ } \ } # define MILTER_DF_ERROR(msg) \ { \ int save_errno = errno; \ \ if (tTd(64, 5)) \ { \ sm_dprintf(msg, dfname, sm_errstring(save_errno)); \ sm_dprintf("\n"); \ } \ if (MilterLogLevel > 0) \ sm_syslog(LOG_ERR, e->e_id, msg, dfname, sm_errstring(save_errno)); \ if (SuperSafe == SAFE_REALLY) \ { \ if (e->e_dfp != NULL) \ { \ (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT); \ e->e_dfp = NULL; \ } \ e->e_flags &= ~EF_HAS_DF; \ } \ errno = save_errno; \ } /* ** MILTER_TIMEOUT -- make sure socket is ready in time ** ** Parameters: ** routine -- routine name for debug/logging ** secs -- number of seconds in timeout ** write -- waiting to read or write? ** started -- whether this is part of a previous sequence ** ** Assumes 'm' is a milter structure for the current socket. */ # define MILTER_TIMEOUT(routine, secs, write, started, function) \ { \ int ret; \ int save_errno; \ fd_set fds; \ struct timeval tv; \ \ if (SM_FD_SETSIZE > 0 && m->mf_sock >= SM_FD_SETSIZE) \ { \ if (tTd(64, 5)) \ sm_dprintf("milter_%s(%s): socket %d is larger than FD_SETSIZE %d\n", \ (routine), m->mf_name, m->mf_sock, \ SM_FD_SETSIZE); \ if (MilterLogLevel > 0) \ sm_syslog(LOG_ERR, e->e_id, \ "Milter (%s): socket(%s) %d is larger than FD_SETSIZE %d", \ m->mf_name, (routine), m->mf_sock, \ SM_FD_SETSIZE); \ milter_error(m, e); \ return NULL; \ } \ \ do \ { \ FD_ZERO(&fds); \ SM_FD_SET(m->mf_sock, &fds); \ tv.tv_sec = (secs); \ tv.tv_usec = 0; \ ret = select(m->mf_sock + 1, \ (write) ? NULL : &fds, \ (write) ? &fds : NULL, \ NULL, &tv); \ } while (ret < 0 && errno == EINTR); \ \ switch (ret) \ { \ case 0: \ if (tTd(64, 5)) \ sm_dprintf("milter_%s(%s): timeout, where=%s\n", \ (routine), m->mf_name, (function)); \ if (MilterLogLevel > 0) \ sm_syslog(LOG_ERR, e->e_id, \ "Milter (%s): timeout %s data %s, where=%s", \ m->mf_name, \ started ? "during" : "before", \ (routine), (function)); \ milter_error(m, e); \ return NULL; \ \ case -1: \ save_errno = errno; \ if (tTd(64, 5)) \ sm_dprintf("milter_%s(%s): select: %s\n", (routine), \ m->mf_name, sm_errstring(save_errno)); \ if (MilterLogLevel > 0) \ { \ sm_syslog(LOG_ERR, e->e_id, \ "Milter (%s): select(%s): %s", \ m->mf_name, (routine), \ sm_errstring(save_errno)); \ } \ milter_error(m, e); \ return NULL; \ \ default: \ if (SM_FD_ISSET(m->mf_sock, &fds)) \ break; \ if (tTd(64, 5)) \ sm_dprintf("milter_%s(%s): socket not ready\n", \ (routine), m->mf_name); \ if (MilterLogLevel > 0) \ { \ sm_syslog(LOG_ERR, e->e_id, \ "Milter (%s): socket(%s) not ready", \ m->mf_name, (routine)); \ } \ milter_error(m, e); \ return NULL; \ } \ } /* ** Low level functions */ /* ** MILTER_READ -- read from a remote milter filter ** ** Parameters: ** m -- milter to read from. ** cmd -- return param for command read. ** rlen -- return length of response string. ** to -- timeout in seconds. ** e -- current envelope. ** ** Returns: ** response string (may be NULL) */ static char * milter_sysread(m, buf, sz, to, e, where) struct milter *m; char *buf; ssize_t sz; time_t to; ENVELOPE *e; const char *where; { time_t readstart = 0; ssize_t len, curl; bool started = false; curl = 0; if (to > 0) readstart = curtime(); for (;;) { if (to > 0) { time_t now; now = curtime(); if (now - readstart >= to) { if (tTd(64, 5)) sm_dprintf("milter_sys_read (%s): timeout %s data read in %s", m->mf_name, started ? "during" : "before", where); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): timeout %s data read in %s", m->mf_name, started ? "during" : "before", where); milter_error(m, e); return NULL; } to -= now - readstart; readstart = now; MILTER_TIMEOUT("read", to, false, started, where); } len = read(m->mf_sock, buf + curl, sz - curl); if (len < 0) { int save_errno = errno; if (tTd(64, 5)) sm_dprintf("milter_sys_read(%s): read returned %ld: %s\n", m->mf_name, (long) len, sm_errstring(save_errno)); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): read returned %ld: %s", m->mf_name, (long) len, sm_errstring(save_errno)); milter_error(m, e); return NULL; } started = true; curl += len; if (len == 0 || curl >= sz) break; } if (curl != sz) { if (tTd(64, 5)) sm_dprintf("milter_sys_read(%s): cmd read returned %ld, expecting %ld\n", m->mf_name, (long) curl, (long) sz); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_sys_read(%s): cmd read returned %ld, expecting %ld", m->mf_name, (long) curl, (long) sz); milter_error(m, e); return NULL; } return buf; } static char * milter_read(m, cmd, rlen, to, e, where) struct milter *m; char *cmd; ssize_t *rlen; time_t to; ENVELOPE *e; const char *where; { time_t readstart = 0; ssize_t expl; mi_int32 i; # if MILTER_NO_NAGLE && defined(TCP_CORK) int cork = 0; # endif /* MILTER_NO_NAGLE && defined(TCP_CORK) */ char *buf; char data[MILTER_LEN_BYTES + 1]; if (m->mf_sock < 0) { if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_read(%s): socket closed, where=%s", m->mf_name, where); milter_error(m, e); return NULL; } *rlen = 0; *cmd = '\0'; if (to > 0) readstart = curtime(); # if MILTER_NO_NAGLE && defined(TCP_CORK) setsockopt(m->mf_sock, IPPROTO_TCP, TCP_CORK, (char *)&cork, sizeof(cork)); # endif /* MILTER_NO_NAGLE && defined(TCP_CORK) */ if (milter_sysread(m, data, sizeof(data), to, e, where) == NULL) return NULL; # if MILTER_NO_NAGLE && defined(TCP_CORK) cork = 1; setsockopt(m->mf_sock, IPPROTO_TCP, TCP_CORK, (char *)&cork, sizeof(cork)); # endif /* MILTER_NO_NAGLE && defined(TCP_CORK) */ /* reset timeout */ if (to > 0) { time_t now; now = curtime(); if (now - readstart >= to) { if (tTd(64, 5)) sm_dprintf("milter_read(%s): timeout before data read, where=%s\n", m->mf_name, where); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter read(%s): timeout before data read, where=%s", m->mf_name, where); milter_error(m, e); return NULL; } to -= now - readstart; } *cmd = data[MILTER_LEN_BYTES]; data[MILTER_LEN_BYTES] = '\0'; (void) memcpy(&i, data, MILTER_LEN_BYTES); expl = ntohl(i) - 1; if (tTd(64, 25)) sm_dprintf("milter_read(%s): expecting %ld bytes\n", m->mf_name, (long) expl); if (expl < 0) { if (tTd(64, 5)) sm_dprintf("milter_read(%s): read size %ld out of range, where=%s\n", m->mf_name, (long) expl, where); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_read(%s): read size %ld out of range, where=%s", m->mf_name, (long) expl, where); milter_error(m, e); return NULL; } if (expl == 0) return NULL; buf = (char *) xalloc(expl); if (milter_sysread(m, buf, expl, to, e, where) == NULL) { sm_free(buf); /* XXX */ return NULL; } if (tTd(64, 50)) sm_dprintf("milter_read(%s): Returning %*s\n", m->mf_name, (int) expl, buf); *rlen = expl; return buf; } /* ** MILTER_WRITE -- write to a remote milter filter ** ** Parameters: ** m -- milter to read from. ** cmd -- command to send. ** buf -- optional command data. ** len -- length of buf. ** to -- timeout in seconds. ** e -- current envelope. ** ** Returns: ** buf if successful, NULL otherwise ** Not actually used anywhere but function prototype ** must match milter_read() */ static char * milter_write(m, cmd, buf, len, to, e, where) struct milter *m; int cmd; char *buf; ssize_t len; time_t to; ENVELOPE *e; const char *where; { ssize_t sl, i; int num_vectors; mi_int32 nl; char command = (char) cmd; char data[MILTER_LEN_BYTES + 1]; bool started = false; struct iovec vector[2]; /* ** At most two buffers will be written, though ** only one may actually be used (see num_vectors). ** The first is the size/command and the second is the command data. */ if (len < 0 || len > MilterMaxDataSize) { if (tTd(64, 5)) { sm_dprintf("milter_write(%s): length %ld out of range, cmd=%c\n", m->mf_name, (long) len, command); sm_dprintf("milter_write(%s): buf=%s\n", m->mf_name, str2prt(buf)); } if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_write(%s): length %ld out of range, cmd=%c", m->mf_name, (long) len, command); milter_error(m, e); return NULL; } if (m->mf_sock < 0) { if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_write(%s): socket closed", m->mf_name); milter_error(m, e); return NULL; } if (tTd(64, 20)) sm_dprintf("milter_write(%s): cmd %c, len %ld\n", m->mf_name, command, (long) len); nl = htonl(len + 1); /* add 1 for the command char */ (void) memcpy(data, (char *) &nl, MILTER_LEN_BYTES); data[MILTER_LEN_BYTES] = command; sl = MILTER_LEN_BYTES + 1; /* set up the vector for the size / command */ vector[0].iov_base = (void *) data; vector[0].iov_len = sl; /* ** Determine if there is command data. If so, there will be two ** vectors. If not, there will be only one. The vectors are set ** up here and 'num_vectors' and 'sl' are set appropriately. */ /* NOTE: len<0 has already been checked for. Pedantic */ if (len <= 0 || buf == NULL) { /* There is no command data -- only a size / command data */ num_vectors = 1; } else { /* ** There is both size / command and command data. ** Set up the vector for the command data. */ num_vectors = 2; sl += len; vector[1].iov_base = (void *) buf; vector[1].iov_len = len; if (tTd(64, 50)) sm_dprintf("milter_write(%s): Sending %*s\n", m->mf_name, (int) len, buf); } if (to > 0) MILTER_TIMEOUT("write", to, true, started, where); /* write the vector(s) */ i = writev(m->mf_sock, vector, num_vectors); if (i != sl) { int save_errno = errno; if (tTd(64, 5)) sm_dprintf("milter_write(%s): write(%c) returned %ld, expected %ld: %s\n", m->mf_name, command, (long) i, (long) sl, sm_errstring(save_errno)); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): write(%c) returned %ld, expected %ld: %s", m->mf_name, command, (long) i, (long) sl, sm_errstring(save_errno)); milter_error(m, e); return NULL; } return buf; } /* ** Utility functions */ /* ** MILTER_OPEN -- connect to remote milter filter ** ** Parameters: ** m -- milter to connect to. ** parseonly -- parse but don't connect. ** e -- current envelope. ** ** Returns: ** connected socket if successful && !parseonly, ** 0 upon parse success if parseonly, ** -1 otherwise. */ static jmp_buf MilterConnectTimeout; static int milter_open(m, parseonly, e) struct milter *m; bool parseonly; ENVELOPE *e; { int sock = 0; SOCKADDR_LEN_T addrlen = 0; int addrno = 0; int save_errno; char *p; char *colon; char *at; struct hostent *hp = NULL; SOCKADDR addr; if (m->mf_conn == NULL || m->mf_conn[0] == '\0') { if (tTd(64, 5)) sm_dprintf("X%s: empty or missing socket information\n", m->mf_name); if (parseonly) syserr("X%s: empty or missing socket information", m->mf_name); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): empty or missing socket information", m->mf_name); milter_error(m, e); return -1; } /* protocol:filename or protocol:port@host */ memset(&addr, '\0', sizeof(addr)); p = m->mf_conn; colon = strchr(p, ':'); if (colon != NULL) { *colon = '\0'; if (*p == '\0') { # if NETUNIX /* default to AF_UNIX */ addr.sa.sa_family = AF_UNIX; # else /* NETUNIX */ # if NETINET /* default to AF_INET */ addr.sa.sa_family = AF_INET; # else /* NETINET */ # if NETINET6 /* default to AF_INET6 */ addr.sa.sa_family = AF_INET6; # else /* NETINET6 */ /* no protocols available */ if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): no valid socket protocols available", m->mf_name); milter_error(m, e); return -1; # endif /* NETINET6 */ # endif /* NETINET */ # endif /* NETUNIX */ } # if NETUNIX else if (sm_strcasecmp(p, "unix") == 0 || sm_strcasecmp(p, "local") == 0) addr.sa.sa_family = AF_UNIX; # endif /* NETUNIX */ # if NETINET else if (sm_strcasecmp(p, "inet") == 0) addr.sa.sa_family = AF_INET; # endif /* NETINET */ # if NETINET6 else if (sm_strcasecmp(p, "inet6") == 0) addr.sa.sa_family = AF_INET6; # endif /* NETINET6 */ else { # ifdef EPROTONOSUPPORT errno = EPROTONOSUPPORT; # else /* EPROTONOSUPPORT */ errno = EINVAL; # endif /* EPROTONOSUPPORT */ if (tTd(64, 5)) sm_dprintf("X%s: unknown socket type %s\n", m->mf_name, p); if (parseonly) syserr("X%s: unknown socket type %s", m->mf_name, p); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): unknown socket type %s", m->mf_name, p); milter_error(m, e); return -1; } *colon++ = ':'; } else { /* default to AF_UNIX */ addr.sa.sa_family = AF_UNIX; colon = p; } # if NETUNIX if (addr.sa.sa_family == AF_UNIX) { long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_EXECOK; at = colon; if (strlen(colon) >= sizeof(addr.sunix.sun_path)) { if (tTd(64, 5)) sm_dprintf("X%s: local socket name %s too long\n", m->mf_name, colon); errno = EINVAL; if (parseonly) syserr("X%s: local socket name %s too long", m->mf_name, colon); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): local socket name %s too long", m->mf_name, colon); milter_error(m, e); return -1; } errno = safefile(colon, RunAsUid, RunAsGid, RunAsUserName, sff, S_IRUSR|S_IWUSR, NULL); /* if just parsing .cf file, socket doesn't need to exist */ if (parseonly && errno == ENOENT) { if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "WARNING: X%s: local socket name %s missing\n", m->mf_name, colon); } else if (errno != 0) { /* if not safe, don't create */ save_errno = errno; if (tTd(64, 5)) sm_dprintf("X%s: local socket name %s unsafe\n", m->mf_name, colon); errno = save_errno; if (parseonly) { if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON || OpMode == MD_SMTP) syserr("X%s: local socket name %s unsafe", m->mf_name, colon); } else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): local socket name %s unsafe", m->mf_name, colon); milter_error(m, e); return -1; } (void) sm_strlcpy(addr.sunix.sun_path, colon, sizeof(addr.sunix.sun_path)); addrlen = sizeof(struct sockaddr_un); } else # endif /* NETUNIX */ # if NETINET || NETINET6 if (false # if NETINET || addr.sa.sa_family == AF_INET # endif /* NETINET */ # if NETINET6 || addr.sa.sa_family == AF_INET6 # endif /* NETINET6 */ ) { unsigned short port; /* Parse port@host */ at = strchr(colon, '@'); if (at == NULL) { if (tTd(64, 5)) sm_dprintf("X%s: bad address %s (expected port@host)\n", m->mf_name, colon); if (parseonly) syserr("X%s: bad address %s (expected port@host)", m->mf_name, colon); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): bad address %s (expected port@host)", m->mf_name, colon); milter_error(m, e); return -1; } *at = '\0'; if (isascii(*colon) && isdigit(*colon)) port = htons((unsigned short) atoi(colon)); else { # ifdef NO_GETSERVBYNAME if (tTd(64, 5)) sm_dprintf("X%s: invalid port number %s\n", m->mf_name, colon); if (parseonly) syserr("X%s: invalid port number %s", m->mf_name, colon); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): invalid port number %s", m->mf_name, colon); milter_error(m, e); return -1; # else /* NO_GETSERVBYNAME */ struct servent *sp; sp = getservbyname(colon, "tcp"); if (sp == NULL) { save_errno = errno; if (tTd(64, 5)) sm_dprintf("X%s: unknown port name %s\n", m->mf_name, colon); errno = save_errno; if (parseonly) syserr("X%s: unknown port name %s", m->mf_name, colon); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): unknown port name %s", m->mf_name, colon); milter_error(m, e); return -1; } port = sp->s_port; # endif /* NO_GETSERVBYNAME */ } *at++ = '@'; if (*at == '[') { char *end; end = strchr(at, ']'); if (end != NULL) { bool found = false; # if NETINET unsigned long hid = INADDR_NONE; # endif /* NETINET */ # if NETINET6 struct sockaddr_in6 hid6; # endif /* NETINET6 */ *end = '\0'; # if NETINET if (addr.sa.sa_family == AF_INET && (hid = inet_addr(&at[1])) != INADDR_NONE) { addr.sin.sin_addr.s_addr = hid; addr.sin.sin_port = port; found = true; } # endif /* NETINET */ # if NETINET6 (void) memset(&hid6, '\0', sizeof(hid6)); if (addr.sa.sa_family == AF_INET6 && anynet_pton(AF_INET6, &at[1], &hid6.sin6_addr) == 1) { addr.sin6.sin6_addr = hid6.sin6_addr; addr.sin6.sin6_port = port; found = true; } # endif /* NETINET6 */ *end = ']'; if (!found) { if (tTd(64, 5)) sm_dprintf("X%s: Invalid numeric domain spec \"%s\"\n", m->mf_name, at); if (parseonly) syserr("X%s: Invalid numeric domain spec \"%s\"", m->mf_name, at); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): Invalid numeric domain spec \"%s\"", m->mf_name, at); milter_error(m, e); return -1; } } else { if (tTd(64, 5)) sm_dprintf("X%s: Invalid numeric domain spec \"%s\"\n", m->mf_name, at); if (parseonly) syserr("X%s: Invalid numeric domain spec \"%s\"", m->mf_name, at); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): Invalid numeric domain spec \"%s\"", m->mf_name, at); milter_error(m, e); return -1; } } else { hp = sm_gethostbyname(at, addr.sa.sa_family); if (hp == NULL) { save_errno = errno; if (tTd(64, 5)) sm_dprintf("X%s: Unknown host name %s\n", m->mf_name, at); errno = save_errno; if (parseonly) syserr("X%s: Unknown host name %s", m->mf_name, at); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): Unknown host name %s", m->mf_name, at); milter_error(m, e); return -1; } addr.sa.sa_family = hp->h_addrtype; switch (hp->h_addrtype) { # if NETINET case AF_INET: memmove(&addr.sin.sin_addr, hp->h_addr, INADDRSZ); addr.sin.sin_port = port; addrlen = sizeof(struct sockaddr_in); addrno = 1; break; # endif /* NETINET */ # if NETINET6 case AF_INET6: memmove(&addr.sin6.sin6_addr, hp->h_addr, IN6ADDRSZ); addr.sin6.sin6_port = port; addrlen = sizeof(struct sockaddr_in6); addrno = 1; break; # endif /* NETINET6 */ default: if (tTd(64, 5)) sm_dprintf("X%s: Unknown protocol for %s (%d)\n", m->mf_name, at, hp->h_addrtype); if (parseonly) syserr("X%s: Unknown protocol for %s (%d)", m->mf_name, at, hp->h_addrtype); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): Unknown protocol for %s (%d)", m->mf_name, at, hp->h_addrtype); milter_error(m, e); # if NETINET6 freehostent(hp); # endif /* NETINET6 */ return -1; } } } else # endif /* NETINET || NETINET6 */ { if (tTd(64, 5)) sm_dprintf("X%s: unknown socket protocol\n", m->mf_name); if (parseonly) syserr("X%s: unknown socket protocol", m->mf_name); else if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): unknown socket protocol", m->mf_name); milter_error(m, e); return -1; } /* just parsing through? */ if (parseonly) { m->mf_state = SMFS_READY; # if NETINET6 if (hp != NULL) freehostent(hp); # endif /* NETINET6 */ return 0; } /* sanity check */ if (m->mf_state != SMFS_READY && m->mf_state != SMFS_CLOSED) { /* shouldn't happen */ if (tTd(64, 1)) sm_dprintf("Milter (%s): Trying to open filter in state %c\n", m->mf_name, (char) m->mf_state); milter_error(m, e); # if NETINET6 if (hp != NULL) freehostent(hp); # endif /* NETINET6 */ return -1; } /* nope, actually connecting */ for (;;) { sock = socket(addr.sa.sa_family, SOCK_STREAM, 0); if (sock < 0) { save_errno = errno; if (tTd(64, 5)) sm_dprintf("Milter (%s): error creating socket: %s\n", m->mf_name, sm_errstring(save_errno)); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): error creating socket: %s", m->mf_name, sm_errstring(save_errno)); milter_error(m, e); # if NETINET6 if (hp != NULL) freehostent(hp); # endif /* NETINET6 */ return -1; } if (setjmp(MilterConnectTimeout) == 0) { SM_EVENT *ev = NULL; int i; if (m->mf_timeout[SMFTO_CONNECT] > 0) ev = sm_setevent(m->mf_timeout[SMFTO_CONNECT], milter_connect_timeout, 0); i = connect(sock, (struct sockaddr *) &addr, addrlen); save_errno = errno; if (ev != NULL) sm_clrevent(ev); errno = save_errno; if (i >= 0) break; } /* couldn't connect.... try next address */ save_errno = errno; p = CurHostName; CurHostName = at; if (tTd(64, 5)) sm_dprintf("milter_open (%s): open %s failed: %s\n", m->mf_name, at, sm_errstring(save_errno)); if (MilterLogLevel > 13) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): open %s failed: %s", m->mf_name, at, sm_errstring(save_errno)); CurHostName = p; (void) close(sock); /* try next address */ if (hp != NULL && hp->h_addr_list[addrno] != NULL) { switch (addr.sa.sa_family) { # if NETINET case AF_INET: memmove(&addr.sin.sin_addr, hp->h_addr_list[addrno++], INADDRSZ); break; # endif /* NETINET */ # if NETINET6 case AF_INET6: memmove(&addr.sin6.sin6_addr, hp->h_addr_list[addrno++], IN6ADDRSZ); break; # endif /* NETINET6 */ default: if (tTd(64, 5)) sm_dprintf("X%s: Unknown protocol for %s (%d)\n", m->mf_name, at, hp->h_addrtype); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): Unknown protocol for %s (%d)", m->mf_name, at, hp->h_addrtype); milter_error(m, e); # if NETINET6 freehostent(hp); # endif /* NETINET6 */ return -1; } continue; } p = CurHostName; CurHostName = at; if (tTd(64, 5)) sm_dprintf("X%s: error connecting to filter: %s\n", m->mf_name, sm_errstring(save_errno)); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): error connecting to filter: %s", m->mf_name, sm_errstring(save_errno)); CurHostName = p; milter_error(m, e); # if NETINET6 if (hp != NULL) freehostent(hp); # endif /* NETINET6 */ return -1; } m->mf_state = SMFS_OPEN; # if NETINET6 if (hp != NULL) { freehostent(hp); hp = NULL; } # endif /* NETINET6 */ # if MILTER_NO_NAGLE && !defined(TCP_CORK) { int nodelay = 1; setsockopt(m->mf_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay)); } # endif /* MILTER_NO_NAGLE && !defined(TCP_CORK) */ return sock; } static void milter_connect_timeout(ignore) int ignore; { /* ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ errno = ETIMEDOUT; longjmp(MilterConnectTimeout, 1); } /* ** MILTER_SETUP -- setup structure for a mail filter ** ** Parameters: ** line -- the options line. ** ** Returns: ** none */ void milter_setup(line) char *line; { char fcode; char *p; struct milter *m; STAB *s; static int idx = 0; /* collect the filter name */ for (p = line; *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p)); p++) continue; if (*p != '\0') *p++ = '\0'; if (line[0] == '\0') { syserr("name required for mail filter"); return; } m = (struct milter *) xalloc(sizeof(*m)); memset((char *) m, '\0', sizeof(*m)); m->mf_name = newstr(line); m->mf_state = SMFS_READY; m->mf_sock = -1; m->mf_timeout[SMFTO_CONNECT] = (time_t) 300; m->mf_timeout[SMFTO_WRITE] = (time_t) 10; m->mf_timeout[SMFTO_READ] = (time_t) 10; m->mf_timeout[SMFTO_EOM] = (time_t) 300; #if _FFR_MILTER_CHECK m->mf_mta_prot_version = SMFI_PROT_VERSION; m->mf_mta_prot_flags = SMFI_CURR_PROT; m->mf_mta_actions = SMFI_CURR_ACTS; #endif /* _FFR_MILTER_CHECK */ /* now scan through and assign info from the fields */ while (*p != '\0') { char *delimptr; while (*p != '\0' && (*p == ',' || (isascii(*p) && isspace(*p)))) p++; /* p now points to field code */ fcode = *p; while (*p != '\0' && *p != '=' && *p != ',') p++; if (*p++ != '=') { syserr("X%s: `=' expected", m->mf_name); return; } while (isascii(*p) && isspace(*p)) p++; /* p now points to the field body */ p = munchstring(p, &delimptr, ','); /* install the field into the filter struct */ switch (fcode) { case 'S': /* socket */ if (p == NULL) m->mf_conn = NULL; else m->mf_conn = newstr(p); break; case 'F': /* Milter flags configured on MTA */ for (; *p != '\0'; p++) { if (!(isascii(*p) && isspace(*p))) setbitn(bitidx(*p), m->mf_flags); } break; case 'T': /* timeouts */ milter_parse_timeouts(p, m); break; #if _FFR_MILTER_CHECK case 'a': m->mf_mta_actions = strtoul(p, NULL, 0); break; case 'f': m->mf_mta_prot_flags = strtoul(p, NULL, 0); break; case 'v': m->mf_mta_prot_version = strtoul(p, NULL, 0); break; #endif /* _FFR_MILTER_CHECK */ default: syserr("X%s: unknown filter equate %c=", m->mf_name, fcode); break; } p = delimptr; } /* early check for errors */ (void) milter_open(m, true, CurEnv); /* enter the filter into the symbol table */ s = stab(m->mf_name, ST_MILTER, ST_ENTER); if (s->s_milter != NULL) syserr("X%s: duplicate filter definition", m->mf_name); else { s->s_milter = m; m->mf_idx = ++idx; } } /* ** MILTER_CONFIG -- parse option list into an array and check config ** ** Called when reading configuration file. ** ** Parameters: ** spec -- the filter list. ** list -- the array to fill in. ** max -- the maximum number of entries in list. ** ** Returns: ** none */ void milter_config(spec, list, max) char *spec; struct milter **list; int max; { int numitems = 0; char *p; /* leave one for the NULL signifying the end of the list */ max--; for (p = spec; p != NULL; ) { STAB *s; while (isascii(*p) && isspace(*p)) p++; if (*p == '\0') break; spec = p; if (numitems >= max) { syserr("Too many filters defined, %d max", max); if (max > 0) list[0] = NULL; return; } p = strpbrk(p, ";,"); if (p != NULL) *p++ = '\0'; s = stab(spec, ST_MILTER, ST_FIND); if (s == NULL) { syserr("InputFilter %s not defined", spec); ExitStat = EX_CONFIG; return; } list[numitems++] = s->s_milter; } list[numitems] = NULL; /* if not set, set to LogLevel */ if (MilterLogLevel == -1) MilterLogLevel = LogLevel; } /* ** MILTER_PARSE_TIMEOUTS -- parse timeout list ** ** Called when reading configuration file. ** ** Parameters: ** spec -- the timeout list. ** m -- milter to set. ** ** Returns: ** none */ static void milter_parse_timeouts(spec, m) char *spec; struct milter *m; { char fcode; int tcode; char *p; p = spec; /* now scan through and assign info from the fields */ while (*p != '\0') { char *delimptr; while (*p != '\0' && (*p == ';' || (isascii(*p) && isspace(*p)))) p++; /* p now points to field code */ fcode = *p; while (*p != '\0' && *p != ':') p++; if (*p++ != ':') { syserr("X%s, T=: `:' expected", m->mf_name); return; } while (isascii(*p) && isspace(*p)) p++; /* p now points to the field body */ p = munchstring(p, &delimptr, ';'); tcode = -1; /* install the field into the filter struct */ switch (fcode) { case 'C': tcode = SMFTO_CONNECT; break; case 'S': tcode = SMFTO_WRITE; break; case 'R': tcode = SMFTO_READ; break; case 'E': tcode = SMFTO_EOM; break; default: if (tTd(64, 5)) sm_dprintf("X%s: %c unknown\n", m->mf_name, fcode); syserr("X%s: unknown filter timeout %c", m->mf_name, fcode); break; } if (tcode >= 0) { m->mf_timeout[tcode] = convtime(p, 's'); if (tTd(64, 5)) sm_dprintf("X%s: %c=%ld\n", m->mf_name, fcode, (u_long) m->mf_timeout[tcode]); } p = delimptr; } } /* ** MILTER_SET_MACROS -- set milter macros ** ** Parameters: ** name -- name of milter. ** macros -- where to store macros. ** val -- the value of the option. ** nummac -- current number of macros ** ** Returns: ** new number of macros */ static int milter_set_macros(name, macros, val, nummac) char *name; char **macros; char *val; int nummac; { char *p; p = newstr(val); while (*p != '\0') { char *macro; /* Skip leading commas, spaces */ while (*p != '\0' && (*p == ',' || (isascii(*p) && isspace(*p)))) p++; if (*p == '\0') break; /* Find end of macro */ macro = p; while (*p != '\0' && *p != ',' && isascii(*p) && !isspace(*p)) p++; if (*p != '\0') *p++ = '\0'; if (nummac >= MAXFILTERMACROS) { syserr("milter_set_option: too many macros in Milter.%s (max %d)", name, MAXFILTERMACROS); macros[nummac] = NULL; return -1; } macros[nummac++] = macro; } macros[nummac] = NULL; return nummac; } /* ** MILTER_SET_OPTION -- set an individual milter option ** ** Parameters: ** name -- the name of the option. ** val -- the value of the option. ** sticky -- if set, don't let other setoptions override ** this value. ** ** Returns: ** none. */ /* set if Milter sub-option is stuck */ static BITMAP256 StickyMilterOpt; static struct milteropt { char *mo_name; /* long name of milter option */ unsigned char mo_code; /* code for option */ } MilterOptTab[] = { { "macros.connect", SMFIM_CONNECT }, { "macros.helo", SMFIM_HELO }, { "macros.envfrom", SMFIM_ENVFROM }, { "macros.envrcpt", SMFIM_ENVRCPT }, { "macros.data", SMFIM_DATA }, { "macros.eom", SMFIM_EOM }, { "macros.eoh", SMFIM_EOH }, # define MO_LOGLEVEL 0x07 { "loglevel", MO_LOGLEVEL }, # if _FFR_MAXDATASIZE || _FFR_MDS_NEGOTIATE # define MO_MAXDATASIZE 0x08 { "maxdatasize", MO_MAXDATASIZE }, # endif /* _FFR_MAXDATASIZE || _FFR_MDS_NEGOTIATE */ { NULL, (unsigned char)-1 }, }; void milter_set_option(name, val, sticky) char *name; char *val; bool sticky; { int nummac, r; struct milteropt *mo; char **macros = NULL; nummac = 0; if (tTd(37, 2) || tTd(64, 5)) sm_dprintf("milter_set_option(%s = %s)", name, val); if (name == NULL) { syserr("milter_set_option: invalid Milter option, must specify suboption"); return; } for (mo = MilterOptTab; mo->mo_name != NULL; mo++) { if (sm_strcasecmp(mo->mo_name, name) == 0) break; } if (mo->mo_name == NULL) { syserr("milter_set_option: invalid Milter option %s", name); return; } /* ** See if this option is preset for us. */ if (!sticky && bitnset(mo->mo_code, StickyMilterOpt)) { if (tTd(37, 2) || tTd(64,5)) sm_dprintf(" (ignored)\n"); return; } if (tTd(37, 2) || tTd(64,5)) sm_dprintf("\n"); switch (mo->mo_code) { case MO_LOGLEVEL: MilterLogLevel = atoi(val); break; # if _FFR_MAXDATASIZE || _FFR_MDS_NEGOTIATE case MO_MAXDATASIZE: # if _FFR_MDS_NEGOTIATE MilterMaxDataSize = (size_t)atol(val); if (MilterMaxDataSize != MILTER_MDS_64K && MilterMaxDataSize != MILTER_MDS_256K && MilterMaxDataSize != MILTER_MDS_1M) { sm_syslog(LOG_WARNING, NOQID, "WARNING: Milter.%s=%d, allowed are only %d, %d, and %d", name, MilterMaxDataSize, MILTER_MDS_64K, MILTER_MDS_256K, MILTER_MDS_1M); if (MilterMaxDataSize < MILTER_MDS_64K) MilterMaxDataSize = MILTER_MDS_64K; else if (MilterMaxDataSize < MILTER_MDS_256K) MilterMaxDataSize = MILTER_MDS_256K; else MilterMaxDataSize = MILTER_MDS_1M; } # endif /* _FFR_MDS_NEGOTIATE */ break; # endif /* _FFR_MAXDATASIZE || _FFR_MDS_NEGOTIATE */ case SMFIM_CONNECT: case SMFIM_HELO: case SMFIM_ENVFROM: case SMFIM_ENVRCPT: case SMFIM_EOH: case SMFIM_EOM: case SMFIM_DATA: macros = MilterMacros[mo->mo_code][0]; r = milter_set_macros(name, macros, val, nummac); if (r >= 0) nummac = r; break; default: syserr("milter_set_option: invalid Milter option %s", name); break; } if (sticky) setbitn(mo->mo_code, StickyMilterOpt); } /* ** MILTER_REOPEN_DF -- open & truncate the data file (for replbody) ** ** Parameters: ** e -- current envelope. ** ** Returns: ** 0 if succesful, -1 otherwise */ static int milter_reopen_df(e) ENVELOPE *e; { char dfname[MAXPATHLEN]; (void) sm_strlcpy(dfname, queuename(e, DATAFL_LETTER), sizeof(dfname)); /* ** In SuperSafe == SAFE_REALLY mode, e->e_dfp is a read-only FP so ** close and reopen writable (later close and reopen ** read only again). ** ** In SuperSafe != SAFE_REALLY mode, e->e_dfp still points at the ** buffered file I/O descriptor, still open for writing so there ** isn't any work to do here (except checking for consistency). */ if (SuperSafe == SAFE_REALLY) { /* close read-only data file */ if (bitset(EF_HAS_DF, e->e_flags) && e->e_dfp != NULL) { (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT); e->e_flags &= ~EF_HAS_DF; } /* open writable */ if ((e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname, SM_IO_RDWR_B, NULL)) == NULL) { MILTER_DF_ERROR("milter_reopen_df: sm_io_open %s: %s"); return -1; } } else if (e->e_dfp == NULL) { /* shouldn't happen */ errno = ENOENT; MILTER_DF_ERROR("milter_reopen_df: NULL e_dfp (%s: %s)"); return -1; } return 0; } /* ** MILTER_RESET_DF -- re-open read-only the data file (for replbody) ** ** Parameters: ** e -- current envelope. ** ** Returns: ** 0 if succesful, -1 otherwise */ static int milter_reset_df(e) ENVELOPE *e; { int afd; char dfname[MAXPATHLEN]; (void) sm_strlcpy(dfname, queuename(e, DATAFL_LETTER), sizeof(dfname)); if (sm_io_flush(e->e_dfp, SM_TIME_DEFAULT) != 0 || sm_io_error(e->e_dfp)) { MILTER_DF_ERROR("milter_reset_df: error writing/flushing %s: %s"); return -1; } else if (SuperSafe != SAFE_REALLY) { /* skip next few clauses */ /* EMPTY */ } else if ((afd = sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL)) >= 0 && fsync(afd) < 0) { MILTER_DF_ERROR("milter_reset_df: error sync'ing %s: %s"); return -1; } else if (sm_io_close(e->e_dfp, SM_TIME_DEFAULT) < 0) { MILTER_DF_ERROR("milter_reset_df: error closing %s: %s"); return -1; } else if ((e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname, SM_IO_RDONLY_B, NULL)) == NULL) { MILTER_DF_ERROR("milter_reset_df: error reopening %s: %s"); return -1; } else e->e_flags |= EF_HAS_DF; return 0; } /* ** MILTER_QUIT_FILTER -- close down a single filter ** ** Parameters: ** m -- milter structure of filter to close down. ** e -- current envelope. ** ** Returns: ** none */ static void milter_quit_filter(m, e) struct milter *m; ENVELOPE *e; { if (tTd(64, 10)) sm_dprintf("milter_quit_filter(%s)\n", m->mf_name); if (MilterLogLevel > 18) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): quit filter", m->mf_name); /* Never replace error state */ if (m->mf_state == SMFS_ERROR) return; if (m->mf_sock < 0 || m->mf_state == SMFS_CLOSED || m->mf_state == SMFS_READY) { m->mf_sock = -1; m->mf_state = SMFS_CLOSED; return; } (void) milter_write(m, SMFIC_QUIT, (char *) NULL, 0, m->mf_timeout[SMFTO_WRITE], e, "quit_filter"); if (m->mf_sock >= 0) { (void) close(m->mf_sock); m->mf_sock = -1; } if (m->mf_state != SMFS_ERROR) m->mf_state = SMFS_CLOSED; } /* ** MILTER_ABORT_FILTER -- tell filter to abort current message ** ** Parameters: ** m -- milter structure of filter to abort. ** e -- current envelope. ** ** Returns: ** none */ static void milter_abort_filter(m, e) struct milter *m; ENVELOPE *e; { if (tTd(64, 10)) sm_dprintf("milter_abort_filter(%s)\n", m->mf_name); if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): abort filter", m->mf_name); if (m->mf_sock < 0 || m->mf_state != SMFS_INMSG) return; (void) milter_write(m, SMFIC_ABORT, (char *) NULL, 0, m->mf_timeout[SMFTO_WRITE], e, "abort_filter"); if (m->mf_state != SMFS_ERROR) m->mf_state = SMFS_DONE; } /* ** MILTER_SEND_MACROS -- provide macros to the filters ** ** Parameters: ** m -- milter to send macros to. ** macros -- macros to send for filter smfi_getsymval(). ** cmd -- which command the macros are associated with. ** e -- current envelope (for macro access). ** ** Returns: ** none */ static void milter_send_macros(m, macros, cmd, e) struct milter *m; char **macros; int cmd; ENVELOPE *e; { int i; int mid; char command = (char) cmd; char *v; char *buf, *bp; char exp[MAXLINE]; ssize_t s; /* sanity check */ if (macros == NULL || macros[0] == NULL) return; /* put together data */ s = 1; /* for the command character */ for (i = 0; macros[i] != NULL; i++) { mid = macid(macros[i]); if (mid == 0) continue; v = macvalue(mid, e); if (v == NULL) continue; expand(v, exp, sizeof(exp), e); s += strlen(macros[i]) + 1 + strlen(exp) + 1; } if (s < 0) return; buf = (char *) xalloc(s); bp = buf; *bp++ = command; for (i = 0; macros[i] != NULL; i++) { mid = macid(macros[i]); if (mid == 0) continue; v = macvalue(mid, e); if (v == NULL) continue; expand(v, exp, sizeof(exp), e); if (tTd(64, 10)) sm_dprintf("milter_send_macros(%s, %c): %s=%s\n", m->mf_name, command, macros[i], exp); (void) sm_strlcpy(bp, macros[i], s - (bp - buf)); bp += strlen(bp) + 1; (void) sm_strlcpy(bp, exp, s - (bp - buf)); bp += strlen(bp) + 1; } (void) milter_write(m, SMFIC_MACRO, buf, s, m->mf_timeout[SMFTO_WRITE], e, "send_macros"); sm_free(buf); } /* ** MILTER_SEND_COMMAND -- send a command and return the response for a filter ** ** Parameters: ** m -- current milter filter ** cmd -- command to send. ** data -- optional command data. ** sz -- length of buf. ** e -- current envelope (for e->e_id). ** state -- return state word. ** ** Returns: ** response string (may be NULL) */ static char * milter_send_command(m, cmd, data, sz, e, state, where) struct milter *m; int cmd; void *data; ssize_t sz; ENVELOPE *e; char *state; const char *where; { char rcmd; ssize_t rlen; unsigned long skipflag; unsigned long norespflag = 0; char command = (char) cmd; char *action; char *defresponse; char *response; if (tTd(64, 10)) sm_dprintf("milter_send_command(%s): cmd %c len %ld\n", m->mf_name, (char) command, (long) sz); /* find skip flag and default failure */ switch (command) { case SMFIC_CONNECT: skipflag = SMFIP_NOCONNECT; norespflag = SMFIP_NR_CONN; action = "connect"; defresponse = "554 Command rejected"; break; case SMFIC_HELO: skipflag = SMFIP_NOHELO; norespflag = SMFIP_NR_HELO; action = "helo"; defresponse = "550 Command rejected"; break; case SMFIC_MAIL: skipflag = SMFIP_NOMAIL; norespflag = SMFIP_NR_MAIL; action = "mail"; defresponse = "550 5.7.1 Command rejected"; break; case SMFIC_RCPT: skipflag = SMFIP_NORCPT; norespflag = SMFIP_NR_RCPT; action = "rcpt"; defresponse = "550 5.7.1 Command rejected"; break; case SMFIC_HEADER: skipflag = SMFIP_NOHDRS; norespflag = SMFIP_NR_HDR; action = "header"; defresponse = "550 5.7.1 Command rejected"; break; case SMFIC_BODY: skipflag = SMFIP_NOBODY; norespflag = SMFIP_NR_BODY; action = "body"; defresponse = "554 5.7.1 Command rejected"; break; case SMFIC_EOH: skipflag = SMFIP_NOEOH; norespflag = SMFIP_NR_EOH; action = "eoh"; defresponse = "550 5.7.1 Command rejected"; break; case SMFIC_UNKNOWN: skipflag = SMFIP_NOUNKNOWN; norespflag = SMFIP_NR_UNKN; action = "unknown"; defresponse = "550 5.7.1 Command rejected"; break; case SMFIC_DATA: skipflag = SMFIP_NODATA; norespflag = SMFIP_NR_DATA; action = "data"; defresponse = "550 5.7.1 Command rejected"; break; case SMFIC_BODYEOB: case SMFIC_OPTNEG: case SMFIC_MACRO: case SMFIC_ABORT: case SMFIC_QUIT: /* NOTE: not handled by milter_send_command() */ /* FALLTHROUGH */ default: skipflag = 0; action = "default"; defresponse = "550 5.7.1 Command rejected"; break; } if (tTd(64, 10)) sm_dprintf("milter_send_command(%s): skip=%lx, pflags=%x\n", m->mf_name, skipflag, m->mf_pflags); /* check if filter wants this command */ if (skipflag != 0 && bitset(skipflag, m->mf_pflags)) return NULL; /* send the command to the filter */ (void) milter_write(m, command, data, sz, m->mf_timeout[SMFTO_WRITE], e, where); if (m->mf_state == SMFS_ERROR) { MILTER_CHECK_ERROR(false, return NULL); return NULL; } /* check if filter sends response to this command */ if (norespflag != 0 && bitset(norespflag, m->mf_pflags)) return NULL; /* get the response from the filter */ response = milter_read(m, &rcmd, &rlen, m->mf_timeout[SMFTO_READ], e, where); if (m->mf_state == SMFS_ERROR) { MILTER_CHECK_ERROR(false, return NULL); return NULL; } if (tTd(64, 10)) sm_dprintf("milter_send_command(%s): returned %c\n", m->mf_name, (char) rcmd); switch (rcmd) { case SMFIR_REPLYCODE: MILTER_CHECK_REPLYCODE(defresponse); if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "milter=%s, action=%s, reject=%s", m->mf_name, action, response); *state = rcmd; break; case SMFIR_REJECT: if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "milter=%s, action=%s, reject", m->mf_name, action); *state = rcmd; break; case SMFIR_DISCARD: if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "milter=%s, action=%s, discard", m->mf_name, action); *state = rcmd; break; case SMFIR_TEMPFAIL: if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "milter=%s, action=%s, tempfail", m->mf_name, action); *state = rcmd; break; case SMFIR_ACCEPT: /* this filter is done with message/connection */ if (command == SMFIC_HELO || command == SMFIC_CONNECT) m->mf_state = SMFS_CLOSABLE; else m->mf_state = SMFS_DONE; if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "milter=%s, action=%s, accepted", m->mf_name, action); break; case SMFIR_CONTINUE: /* if MAIL command is ok, filter is in message state */ if (command == SMFIC_MAIL) m->mf_state = SMFS_INMSG; if (MilterLogLevel > 12) sm_syslog(LOG_INFO, e->e_id, "milter=%s, action=%s, continue", m->mf_name, action); break; case SMFIR_SKIP: if (MilterLogLevel > 12) sm_syslog(LOG_INFO, e->e_id, "milter=%s, action=%s, skip", m->mf_name, action); m->mf_state = SMFS_SKIP; break; default: /* Invalid response to command */ if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_send_command(%s): action=%s returned bogus response %c", m->mf_name, action, rcmd); milter_error(m, e); /* NO ERROR CHECK? */ break; } if (*state != SMFIR_REPLYCODE && response != NULL) { sm_free(response); /* XXX */ response = NULL; } return response; } /* ** MILTER_COMMAND -- send a command and return the response for each filter ** ** Parameters: ** cmd -- command to send. ** data -- optional command data. ** sz -- length of buf. -** macros -- macros to send for filter smfi_getsymval(). +** stage -- index of macros to send for filter smfi_getsymval(). ** e -- current envelope (for macro access). ** state -- return state word. ** where -- description of calling function (logging). ** cmd_error -- did the SMTP command cause an error? ** ** Returns: ** response string (may be NULL) */ static char * milter_command(cmd, data, sz, stage, e, state, where, cmd_error) int cmd; void *data; ssize_t sz; int stage; ENVELOPE *e; char *state; const char *where; bool cmd_error; { int i; char command = (char) cmd; char *response = NULL; time_t tn = 0; if (tTd(64, 10)) sm_dprintf("milter_command: cmd %c len %ld\n", command, (long) sz); *state = SMFIR_CONTINUE; for (i = 0; InputFilters[i] != NULL; i++) { struct milter *m = InputFilters[i]; /* previous problem? */ if (m->mf_state == SMFS_ERROR) { MILTER_CHECK_ERROR(false, continue); break; } /* sanity check */ if (m->mf_sock < 0 || (m->mf_state != SMFS_OPEN && m->mf_state != SMFS_INMSG)) continue; if (stage >= SMFIM_FIRST && stage <= SMFIM_LAST) { int idx; char **macros; if ((m->mf_lflags & MI_LFLAGS_SYM(stage)) != 0) idx = m->mf_idx; else idx = 0; SM_ASSERT(idx >= 0 && idx <= MAXFILTERS); macros = MilterMacros[stage][idx]; /* send macros (regardless of whether we send cmd) */ if (macros != NULL && macros[0] != NULL) { milter_send_macros(m, macros, command, e); if (m->mf_state == SMFS_ERROR) { MILTER_CHECK_ERROR(false, continue); break; } } } if (MilterLogLevel > 21) tn = curtime(); /* ** send the command if ** there is no error ** or it's RCPT and the client asked for it: ** !cmd_error || ** where == "rcpt" && m->mf_pflags & SMFIP_RCPT_REJ != 0 ** negate that condition and use continue */ if (cmd_error && (strcmp(where, "rcpt") != 0 || (m->mf_pflags & SMFIP_RCPT_REJ) == 0)) continue; response = milter_send_command(m, command, data, sz, e, state, where); if (MilterLogLevel > 21) { /* log the time it took for the command per filter */ sm_syslog(LOG_INFO, e->e_id, "Milter (%s): time command (%c), %d", m->mf_name, command, (int) (tn - curtime())); } if (*state != SMFIR_CONTINUE) break; } return response; } static int milter_getsymlist __P((struct milter *, char *, int, int)); static int milter_getsymlist(m, buf, rlen, offset) struct milter *m; char *buf; int rlen; int offset; { int i, r, nummac; mi_int32 v; SM_ASSERT(m != NULL); SM_ASSERT(buf != NULL); while (offset + MILTER_LEN_BYTES < rlen) { size_t len; char **macros; nummac = 0; (void) memcpy((char *) &v, buf + offset, MILTER_LEN_BYTES); i = ntohl(v); if (i < SMFIM_FIRST || i > SMFIM_LAST) return -1; offset += MILTER_LEN_BYTES; macros = NULL; switch (i) { case SMFIM_CONNECT: case SMFIM_HELO: case SMFIM_ENVFROM: case SMFIM_ENVRCPT: case SMFIM_EOH: case SMFIM_EOM: case SMFIM_DATA: SM_ASSERT(m->mf_idx > 0 && m->mf_idx < MAXFILTERS); macros = MilterMacros[i][m->mf_idx]; - m->mf_lflags |= MI_LFLAGS_SYM(i); len = strlen(buf + offset); if (len > 0) { r = milter_set_macros(m->mf_name, macros, buf + offset, nummac); if (r >= 0) nummac = r; if (tTd(64, 5)) sm_dprintf("milter_getsymlist(%s, %s)=%d\n", m->mf_name, buf + offset, r); } break; default: return -1; } if (len == 0) return -1; offset += len + 1; } return 0; } /* ** MILTER_NEGOTIATE -- get version and flags from filter ** ** Parameters: ** m -- milter filter structure. ** e -- current envelope. ** milters -- milters structure. ** ** Returns: ** 0 on success, -1 otherwise */ static int milter_negotiate(m, e, milters) struct milter *m; ENVELOPE *e; milters_T *milters; { char rcmd; mi_int32 fvers, fflags, pflags; mi_int32 mta_prot_vers, mta_prot_flags, mta_actions; ssize_t rlen; char *response; char data[MILTER_OPTLEN]; /* sanity check */ if (m->mf_sock < 0 || m->mf_state != SMFS_OPEN) { if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): negotiate, impossible state", m->mf_name); milter_error(m, e); return -1; } #if _FFR_MILTER_CHECK mta_prot_vers = m->mf_mta_prot_version; mta_prot_flags = m->mf_mta_prot_flags; mta_actions = m->mf_mta_actions; #else /* _FFR_MILTER_CHECK */ mta_prot_vers = SMFI_PROT_VERSION; mta_prot_flags = SMFI_CURR_PROT; mta_actions = SMFI_CURR_ACTS; #endif /* _FFR_MILTER_CHECK */ #if _FFR_MDS_NEGOTIATE if (MilterMaxDataSize == MILTER_MDS_256K) mta_prot_flags |= SMFIP_MDS_256K; else if (MilterMaxDataSize == MILTER_MDS_1M) mta_prot_flags |= SMFIP_MDS_1M; #endif /* _FFR_MDS_NEGOTIATE */ fvers = htonl(mta_prot_vers); pflags = htonl(mta_prot_flags); fflags = htonl(mta_actions); (void) memcpy(data, (char *) &fvers, MILTER_LEN_BYTES); (void) memcpy(data + MILTER_LEN_BYTES, (char *) &fflags, MILTER_LEN_BYTES); (void) memcpy(data + (MILTER_LEN_BYTES * 2), (char *) &pflags, MILTER_LEN_BYTES); (void) milter_write(m, SMFIC_OPTNEG, data, sizeof(data), m->mf_timeout[SMFTO_WRITE], e, "negotiate"); if (m->mf_state == SMFS_ERROR) return -1; if (tTd(64, 5)) sm_dprintf("milter_negotiate(%s): send: version %lu, fflags 0x%lx, pflags 0x%lx\n", m->mf_name, ntohl(fvers), ntohl(fflags), ntohl(pflags)); response = milter_read(m, &rcmd, &rlen, m->mf_timeout[SMFTO_READ], e, "negotiate"); if (m->mf_state == SMFS_ERROR) return -1; if (rcmd != SMFIC_OPTNEG) { if (tTd(64, 5)) sm_dprintf("milter_negotiate(%s): returned %c instead of %c\n", m->mf_name, rcmd, SMFIC_OPTNEG); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): negotiate: returned %c instead of %c", m->mf_name, rcmd, SMFIC_OPTNEG); if (response != NULL) sm_free(response); /* XXX */ milter_error(m, e); return -1; } /* Make sure we have enough bytes for the version */ if (response == NULL || rlen < MILTER_LEN_BYTES) { if (tTd(64, 5)) sm_dprintf("milter_negotiate(%s): did not return valid info\n", m->mf_name); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): negotiate: did not return valid info", m->mf_name); if (response != NULL) sm_free(response); /* XXX */ milter_error(m, e); return -1; } /* extract information */ (void) memcpy((char *) &fvers, response, MILTER_LEN_BYTES); /* Now make sure we have enough for the feature bitmap */ if (rlen < MILTER_OPTLEN) { if (tTd(64, 5)) sm_dprintf("milter_negotiate(%s): did not return enough info\n", m->mf_name); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): negotiate: did not return enough info", m->mf_name); if (response != NULL) sm_free(response); /* XXX */ milter_error(m, e); return -1; } (void) memcpy((char *) &fflags, response + MILTER_LEN_BYTES, MILTER_LEN_BYTES); (void) memcpy((char *) &pflags, response + (MILTER_LEN_BYTES * 2), MILTER_LEN_BYTES); m->mf_fvers = ntohl(fvers); m->mf_fflags = ntohl(fflags); m->mf_pflags = ntohl(pflags); /* check for version compatibility */ if (m->mf_fvers == 1 || m->mf_fvers > SMFI_VERSION) { if (tTd(64, 5)) sm_dprintf("milter_negotiate(%s): version %d != MTA milter version %d\n", m->mf_name, m->mf_fvers, SMFI_VERSION); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): negotiate: version %d != MTA milter version %d", m->mf_name, m->mf_fvers, SMFI_VERSION); milter_error(m, e); goto error; } /* check for filter feature mismatch */ if ((m->mf_fflags & mta_actions) != m->mf_fflags) { if (tTd(64, 5)) sm_dprintf("milter_negotiate(%s): filter abilities 0x%x != MTA milter abilities 0x%lx\n", m->mf_name, m->mf_fflags, (unsigned long) mta_actions); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): negotiate: filter abilities 0x%x != MTA milter abilities 0x%lx", m->mf_name, m->mf_fflags, (unsigned long) mta_actions); milter_error(m, e); goto error; } #if _FFR_MDS_NEGOTIATE /* use a table instead of sequence? */ if (bitset(SMFIP_MDS_1M, m->mf_pflags)) { if (MilterMaxDataSize != MILTER_MDS_1M) { /* this should not happen... */ sm_syslog(LOG_WARNING, NOQID, "WARNING: Milter.maxdatasize: configured=%d, set by libmilter=%d", MilterMaxDataSize, MILTER_MDS_1M); MilterMaxDataSize = MILTER_MDS_1M; } } else if (bitset(SMFIP_MDS_256K, m->mf_pflags)) { if (MilterMaxDataSize != MILTER_MDS_256K) { sm_syslog(LOG_WARNING, NOQID, "WARNING: Milter.maxdatasize: configured=%d, set by libmilter=%d", MilterMaxDataSize, MILTER_MDS_256K); MilterMaxDataSize = MILTER_MDS_256K; } } else if (MilterMaxDataSize != MILTER_MDS_64K) { sm_syslog(LOG_WARNING, NOQID, "WARNING: Milter.maxdatasize: configured=%d, set by libmilter=%d", MilterMaxDataSize, MILTER_MDS_64K); MilterMaxDataSize = MILTER_MDS_64K; } m->mf_pflags &= ~SMFI_INTERNAL; #endif /* _FFR_MDS_NEGOTIATE */ /* check for protocol feature mismatch */ if ((m->mf_pflags & mta_prot_flags) != m->mf_pflags) { if (tTd(64, 5)) sm_dprintf("milter_negotiate(%s): protocol abilities 0x%x != MTA milter abilities 0x%lx\n", m->mf_name, m->mf_pflags, (unsigned long) mta_prot_flags); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): negotiate: protocol abilities 0x%x != MTA milter abilities 0x%lx", m->mf_name, m->mf_pflags, (unsigned long) mta_prot_flags); milter_error(m, e); goto error; } if (m->mf_fvers <= 2) m->mf_pflags |= SMFIP_NOUNKNOWN; if (m->mf_fvers <= 3) m->mf_pflags |= SMFIP_NODATA; if (rlen > MILTER_OPTLEN) { milter_getsymlist(m, response, rlen, MILTER_OPTLEN); } if (bitset(SMFIF_DELRCPT, m->mf_fflags)) milters->mis_flags |= MIS_FL_DEL_RCPT; if (!bitset(SMFIP_NORCPT, m->mf_pflags) && !bitset(SMFIP_NR_RCPT, m->mf_pflags)) milters->mis_flags |= MIS_FL_REJ_RCPT; if (tTd(64, 5)) sm_dprintf("milter_negotiate(%s): received: version %u, fflags 0x%x, pflags 0x%x\n", m->mf_name, m->mf_fvers, m->mf_fflags, m->mf_pflags); return 0; error: if (response != NULL) sm_free(response); /* XXX */ return -1; } /* ** MILTER_PER_CONNECTION_CHECK -- checks on per-connection commands ** ** Reduce code duplication by putting these checks in one place ** ** Parameters: ** e -- current envelope. ** ** Returns: ** none */ static void milter_per_connection_check(e) ENVELOPE *e; { int i; /* see if we are done with any of the filters */ for (i = 0; InputFilters[i] != NULL; i++) { struct milter *m = InputFilters[i]; if (m->mf_state == SMFS_CLOSABLE) milter_quit_filter(m, e); } } /* ** MILTER_ERROR -- Put a milter filter into error state ** ** Parameters: ** m -- the broken filter. ** e -- current envelope. ** ** Returns: ** none */ static void milter_error(m, e) struct milter *m; ENVELOPE *e; { /* ** We could send a quit here but we may have gotten here due to ** an I/O error so we don't want to try to make things worse. */ if (m->mf_sock >= 0) { (void) close(m->mf_sock); m->mf_sock = -1; } m->mf_state = SMFS_ERROR; if (MilterLogLevel > 0) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): to error state", m->mf_name); } /* ** MILTER_HEADERS -- send headers to a single milter filter ** ** Parameters: ** m -- current filter. ** e -- current envelope. ** state -- return state from response. ** ** Returns: ** response string (may be NULL) */ static char * milter_headers(m, e, state) struct milter *m; ENVELOPE *e; char *state; { char *response = NULL; HDR *h; if (MilterLogLevel > 17) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): headers, send", m->mf_name); for (h = e->e_header; h != NULL; h = h->h_link) { int len_n, len_v, len_t, len_f; char *buf, *hv; /* don't send over deleted headers */ if (h->h_value == NULL) { /* strip H_USER so not counted in milter_changeheader() */ h->h_flags &= ~H_USER; continue; } /* skip auto-generated */ if (!bitset(H_USER, h->h_flags)) continue; if (tTd(64, 10)) sm_dprintf("milter_headers: %s:%s\n", h->h_field, h->h_value); if (MilterLogLevel > 21) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): header, %s", m->mf_name, h->h_field); if (bitset(SMFIP_HDR_LEADSPC, m->mf_pflags) || *(h->h_value) != ' ') hv = h->h_value; else hv = h->h_value + 1; len_f = strlen(h->h_field) + 1; len_t = len_f + strlen(hv) + 1; if (len_t < 0) continue; buf = (char *) xalloc(len_t); /* ** Note: currently the call to dequote_internal_chars() ** is not required as h_field is supposed to be 7-bit US-ASCII. */ len_n = dequote_internal_chars(h->h_field, buf, len_f); SM_ASSERT(len_n < len_f); len_v = dequote_internal_chars(hv, buf + len_n + 1, len_t - len_n - 1); SM_ASSERT(len_t >= len_n + 1 + len_v + 1); len_t = len_n + 1 + len_v + 1; /* send it over */ response = milter_send_command(m, SMFIC_HEADER, buf, len_t, e, state, "header"); sm_free(buf); if (m->mf_state == SMFS_ERROR || m->mf_state == SMFS_DONE || *state != SMFIR_CONTINUE) break; } if (MilterLogLevel > 17) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): headers, sent", m->mf_name); return response; } /* ** MILTER_BODY -- send the body to a filter ** ** Parameters: ** m -- current filter. ** e -- current envelope. ** state -- return state from response. ** ** Returns: ** response string (may be NULL) */ static char * milter_body(m, e, state) struct milter *m; ENVELOPE *e; char *state; { char bufchar = '\0'; char prevchar = '\0'; int c; char *response = NULL; char *bp; char buf[MILTER_CHUNK_SIZE]; if (tTd(64, 10)) sm_dprintf("milter_body\n"); if (bfrewind(e->e_dfp) < 0) { ExitStat = EX_IOERR; *state = SMFIR_TEMPFAIL; syserr("milter_body: %s/%cf%s: rewind error", qid_printqueue(e->e_qgrp, e->e_qdir), DATAFL_LETTER, e->e_id); return NULL; } if (MilterLogLevel > 17) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): body, send", m->mf_name); bp = buf; while ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT)) != SM_IO_EOF) { /* Change LF to CRLF */ if (c == '\n') { #if !_FFR_MILTER_CONVERT_ALL_LF_TO_CRLF /* Not a CRLF already? */ if (prevchar != '\r') #endif /* !_FFR_MILTER_CONVERT_ALL_LF_TO_CRLF */ { /* Room for CR now? */ if (bp + 2 > &buf[sizeof(buf)]) { /* No room, buffer LF */ bufchar = c; /* and send CR now */ c = '\r'; } else { /* Room to do it now */ *bp++ = '\r'; prevchar = '\r'; } } } *bp++ = (char) c; prevchar = c; if (bp >= &buf[sizeof(buf)]) { /* send chunk */ response = milter_send_command(m, SMFIC_BODY, buf, bp - buf, e, state, "body chunk"); bp = buf; if (bufchar != '\0') { *bp++ = bufchar; bufchar = '\0'; prevchar = bufchar; } } if (m->mf_state == SMFS_ERROR || m->mf_state == SMFS_DONE || m->mf_state == SMFS_SKIP || *state != SMFIR_CONTINUE) break; } /* check for read errors */ if (sm_io_error(e->e_dfp)) { ExitStat = EX_IOERR; if (*state == SMFIR_CONTINUE || *state == SMFIR_ACCEPT || m->mf_state == SMFS_SKIP) { *state = SMFIR_TEMPFAIL; if (response != NULL) { sm_free(response); /* XXX */ response = NULL; } } syserr("milter_body: %s/%cf%s: read error", qid_printqueue(e->e_qgrp, e->e_qdir), DATAFL_LETTER, e->e_id); return response; } /* send last body chunk */ if (bp > buf && m->mf_state != SMFS_ERROR && m->mf_state != SMFS_DONE && m->mf_state != SMFS_SKIP && *state == SMFIR_CONTINUE) { /* send chunk */ response = milter_send_command(m, SMFIC_BODY, buf, bp - buf, e, state, "last body chunk"); bp = buf; } if (MilterLogLevel > 17) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): body, sent", m->mf_name); if (m->mf_state == SMFS_SKIP) { *state = SMFIR_CONTINUE; m->mf_state = SMFS_READY; } return response; } /* ** Actions */ /* ** ADDLEADINGSPACE -- Add a leading space to a string ** ** Parameters: ** str -- string ** rp -- resource pool for allocations ** ** Returns: ** pointer to new string */ static char *addleadingspace __P((char *, SM_RPOOL_T *)); static char * addleadingspace(str, rp) char *str; SM_RPOOL_T *rp; { size_t l; char *new; SM_ASSERT(str != NULL); l = strlen(str); SM_ASSERT(l + 2 > l); new = sm_rpool_malloc_x(rp, l + 2); new[0] = ' '; new[1] = '\0'; sm_strlcpy(new + 1, str, l + 1); return new; } /* ** MILTER_ADDHEADER -- Add the supplied header to the message ** ** Parameters: ** m -- current filter. ** response -- encoded form of header/value. ** rlen -- length of response. ** e -- current envelope. ** ** Returns: ** none */ static void milter_addheader(m, response, rlen, e) struct milter *m; char *response; ssize_t rlen; ENVELOPE *e; { int mh_v_len; char *val, *mh_value; HDR *h; if (tTd(64, 10)) sm_dprintf("milter_addheader: "); /* sanity checks */ if (response == NULL) { if (tTd(64, 10)) sm_dprintf("NULL response\n"); return; } if (rlen < 2 || strlen(response) + 1 >= (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n", (int) strlen(response), (int) (rlen - 1)); return; } /* Find separating NUL */ val = response + strlen(response) + 1; /* another sanity check */ if (strlen(response) + strlen(val) + 2 != (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (part len)\n"); return; } if (*response == '\0') { if (tTd(64, 10)) sm_dprintf("empty field name\n"); return; } for (h = e->e_header; h != NULL; h = h->h_link) { if (sm_strcasecmp(h->h_field, response) == 0 && !bitset(H_USER, h->h_flags) && !bitset(H_TRACE, h->h_flags)) break; } mh_v_len = 0; mh_value = quote_internal_chars(val, NULL, &mh_v_len); /* add to e_msgsize */ e->e_msgsize += strlen(response) + 2 + strlen(val); if (h != NULL) { if (tTd(64, 10)) sm_dprintf("Replace default header %s value with %s\n", h->h_field, mh_value); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter change: default header %s value with %s", h->h_field, mh_value); if (bitset(SMFIP_HDR_LEADSPC, m->mf_pflags)) h->h_value = mh_value; else { h->h_value = addleadingspace(mh_value, e->e_rpool); SM_FREE(mh_value); } h->h_flags |= H_USER; } else { if (tTd(64, 10)) sm_dprintf("Add %s: %s\n", response, mh_value); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter add: header: %s: %s", response, mh_value); addheader(newstr(response), mh_value, H_USER, e, !bitset(SMFIP_HDR_LEADSPC, m->mf_pflags)); SM_FREE(mh_value); } } /* ** MILTER_INSHEADER -- Insert the supplied header ** ** Parameters: ** m -- current filter. ** response -- encoded form of header/value. ** rlen -- length of response. ** e -- current envelope. ** ** Returns: ** none ** ** Notes: ** Unlike milter_addheader(), this does not attempt to determine ** if the header already exists in the envelope, even a ** deleted version. It just blindly inserts. */ static void milter_insheader(m, response, rlen, e) struct milter *m; char *response; ssize_t rlen; ENVELOPE *e; { mi_int32 idx, i; int mh_v_len; char *field, *val, *mh_value; if (tTd(64, 10)) sm_dprintf("milter_insheader: "); /* sanity checks */ if (response == NULL) { if (tTd(64, 10)) sm_dprintf("NULL response\n"); return; } if (rlen < 2 || strlen(response) + 1 >= (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (total len)\n"); return; } /* decode */ (void) memcpy((char *) &i, response, MILTER_LEN_BYTES); idx = ntohl(i); field = response + MILTER_LEN_BYTES; val = field + strlen(field) + 1; /* another sanity check */ if (MILTER_LEN_BYTES + strlen(field) + 1 + strlen(val) + 1 != (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (part len)\n"); return; } if (*field == '\0') { if (tTd(64, 10)) sm_dprintf("empty field name\n"); return; } /* add to e_msgsize */ e->e_msgsize += strlen(response) + 2 + strlen(val); if (tTd(64, 10)) sm_dprintf("Insert (%d) %s: %s\n", idx, field, val); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter insert (%d): header: %s: %s", idx, field, val); mh_v_len = 0; mh_value = quote_internal_chars(val, NULL, &mh_v_len); insheader(idx, newstr(field), mh_value, H_USER, e, !bitset(SMFIP_HDR_LEADSPC, m->mf_pflags)); SM_FREE(mh_value); } /* ** MILTER_CHANGEHEADER -- Change the supplied header in the message ** ** Parameters: ** m -- current filter. ** response -- encoded form of header/index/value. ** rlen -- length of response. ** e -- current envelope. ** ** Returns: ** none */ static void milter_changeheader(m, response, rlen, e) struct milter *m; char *response; ssize_t rlen; ENVELOPE *e; { mi_int32 i, index; int mh_v_len; char *field, *val, *mh_value; HDR *h, *sysheader; if (tTd(64, 10)) sm_dprintf("milter_changeheader: "); /* sanity checks */ if (response == NULL) { if (tTd(64, 10)) sm_dprintf("NULL response\n"); return; } if (rlen < 2 || strlen(response) + 1 >= (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (total len)\n"); return; } /* Find separating NUL */ (void) memcpy((char *) &i, response, MILTER_LEN_BYTES); index = ntohl(i); field = response + MILTER_LEN_BYTES; val = field + strlen(field) + 1; /* another sanity check */ if (MILTER_LEN_BYTES + strlen(field) + 1 + strlen(val) + 1 != (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (part len)\n"); return; } if (*field == '\0') { if (tTd(64, 10)) sm_dprintf("empty field name\n"); return; } mh_v_len = 0; mh_value = quote_internal_chars(val, NULL, &mh_v_len); sysheader = NULL; for (h = e->e_header; h != NULL; h = h->h_link) { if (sm_strcasecmp(h->h_field, field) == 0) { if (bitset(H_USER, h->h_flags) && --index <= 0) { sysheader = NULL; break; } else if (!bitset(H_USER, h->h_flags) && !bitset(H_TRACE, h->h_flags)) { /* ** DRUMS msg-fmt draft says can only have ** multiple occurences of trace fields, ** so make sure we replace any non-trace, ** non-user field. */ sysheader = h; } } } /* if not found as user-provided header at index, use sysheader */ if (h == NULL) h = sysheader; if (h == NULL) { if (*val == '\0') { if (tTd(64, 10)) sm_dprintf("Delete (noop) %s\n", field); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter delete (noop): header: %s" , field); } else { /* treat modify value with no existing header as add */ if (tTd(64, 10)) sm_dprintf("Add %s: %s\n", field, mh_value); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter change (add): header: %s: %s" , field, mh_value); addheader(newstr(field), mh_value, H_USER, e, !bitset(SMFIP_HDR_LEADSPC, m->mf_pflags)); } return; } if (tTd(64, 10)) { if (*val == '\0') { sm_dprintf("Delete%s %s:%s\n", h == sysheader ? " (default header)" : "", field, h->h_value == NULL ? "" : h->h_value); } else { sm_dprintf("Change%s %s: from %s to %s\n", h == sysheader ? " (default header)" : "", field, h->h_value == NULL ? "" : h->h_value, mh_value); } } if (MilterLogLevel > 8) { if (*val == '\0') { sm_syslog(LOG_INFO, e->e_id, "Milter delete: header%s %s:%s", h == sysheader ? " (default header)" : "", field, h->h_value == NULL ? "" : h->h_value); } else { sm_syslog(LOG_INFO, e->e_id, "Milter change: header%s %s: from %s to %s", h == sysheader ? " (default header)" : "", field, h->h_value == NULL ? "" : h->h_value, mh_value); } } if (h != sysheader && h->h_value != NULL) { size_t l; l = strlen(h->h_value); if (l > e->e_msgsize) e->e_msgsize = 0; else e->e_msgsize -= l; /* rpool, don't free: sm_free(h->h_value); XXX */ } if (*val == '\0') { /* Remove "Field: " from message size */ if (h != sysheader) { size_t l; l = strlen(h->h_field) + 2; if (l > e->e_msgsize) e->e_msgsize = 0; else e->e_msgsize -= l; } h->h_value = NULL; SM_FREE(mh_value); } else { if (bitset(SMFIP_HDR_LEADSPC, m->mf_pflags)) h->h_value = mh_value; else { h->h_value = addleadingspace(mh_value, e->e_rpool); SM_FREE(mh_value); } h->h_flags |= H_USER; e->e_msgsize += strlen(h->h_value); } } /* ** MILTER_SPLIT_RESPONSE -- Split response into fields. ** ** Parameters: ** response -- encoded repsonse. ** rlen -- length of response. ** pargc -- number of arguments (ouput) ** ** Returns: ** array of pointers to the individual strings */ static char **milter_split_response __P((char *, ssize_t, int *)); static char ** milter_split_response(response, rlen, pargc) char *response; ssize_t rlen; int *pargc; { char **s; size_t i; int elem, nelem; SM_ASSERT(response != NULL); SM_ASSERT(pargc != NULL); *pargc = 0; if (rlen < 2 || strlen(response) >= (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n", (int) strlen(response), (int) (rlen - 1)); return NULL; } nelem = 0; for (i = 0; i < rlen; i++) { if (response[i] == '\0') ++nelem; } if (nelem == 0) return NULL; /* last entry is only for the name */ s = (char **)malloc((nelem + 1) * (sizeof(*s))); if (s == NULL) return NULL; s[0] = response; for (i = 0, elem = 0; i < rlen && elem < nelem; i++) { if (response[i] == '\0') { ++elem; if (i + 1 >= rlen) s[elem] = NULL; else s[elem] = &(response[i + 1]); } } *pargc = nelem; if (tTd(64, 10)) { for (elem = 0; elem < nelem; elem++) sm_dprintf("argv[%d]=\"%s\"\n", elem, s[elem]); } /* overwrite last entry (already done above, just paranoia) */ s[elem] = NULL; return s; } /* ** MILTER_CHGFROM -- Change the envelope sender address ** ** Parameters: ** response -- encoded form of recipient address. ** rlen -- length of response. ** e -- current envelope. ** ** Returns: ** none */ static void milter_chgfrom(response, rlen, e) char *response; ssize_t rlen; ENVELOPE *e; { int olderrors, argc; char **argv; if (tTd(64, 10)) sm_dprintf("milter_chgfrom: "); /* sanity checks */ if (response == NULL) { if (tTd(64, 10)) sm_dprintf("NULL response\n"); return; } if (*response == '\0' || strlen(response) + 1 > (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n", (int) strlen(response), (int) (rlen - 1)); return; } if (tTd(64, 10)) sm_dprintf("%s\n", response); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter chgfrom: %s", response); argv = milter_split_response(response, rlen, &argc); if (argc < 1 || argc > 2) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol argc=%d\n", argc); return; } olderrors = Errors; setsender(argv[0], e, NULL, '\0', false); if (argc == 2) { reset_mail_esmtp_args(e); /* ** need "features" here: how to get those? via e? ** "fake" it for now: allow everything. */ parse_esmtp_args(e, NULL, argv[0], argv[1], "MAIL", NULL, mail_esmtp_args); } Errors = olderrors; return; } /* ** MILTER_ADDRCPT_PAR -- Add the supplied recipient to the message ** ** Parameters: ** response -- encoded form of recipient address. ** rlen -- length of response. ** e -- current envelope. ** ** Returns: ** none */ static void milter_addrcpt_par(response, rlen, e) char *response; ssize_t rlen; ENVELOPE *e; { int olderrors, argc; char *delimptr; char **argv; ADDRESS *a; if (tTd(64, 10)) sm_dprintf("milter_addrcpt_par: "); /* sanity checks */ if (response == NULL) { if (tTd(64, 10)) sm_dprintf("NULL response\n"); return; } if (tTd(64, 10)) sm_dprintf("%s\n", response); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter add: rcpt: %s", response); argv = milter_split_response(response, rlen, &argc); if (argc < 1 || argc > 2) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol argc=%d\n", argc); return; } olderrors = Errors; /* how to set ESMTP arguments? */ a = parseaddr(argv[0], NULLADDR, RF_COPYALL, ' ', &delimptr, e, true); if (a != NULL && olderrors == Errors) { parse_esmtp_args(e, a, argv[0], argv[1], "RCPT", NULL, rcpt_esmtp_args); if (olderrors == Errors) a = recipient(a, &e->e_sendqueue, 0, e); else sm_dprintf("olderrors=%d, Errors=%d\n", olderrors, Errors); } else { sm_dprintf("a=%p, olderrors=%d, Errors=%d\n", a, olderrors, Errors); } Errors = olderrors; return; } /* ** MILTER_ADDRCPT -- Add the supplied recipient to the message ** ** Parameters: ** response -- encoded form of recipient address. ** rlen -- length of response. ** e -- current envelope. ** ** Returns: ** none */ static void milter_addrcpt(response, rlen, e) char *response; ssize_t rlen; ENVELOPE *e; { int olderrors; if (tTd(64, 10)) sm_dprintf("milter_addrcpt: "); /* sanity checks */ if (response == NULL) { if (tTd(64, 10)) sm_dprintf("NULL response\n"); return; } if (*response == '\0' || strlen(response) + 1 != (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n", (int) strlen(response), (int) (rlen - 1)); return; } if (tTd(64, 10)) sm_dprintf("%s\n", response); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter add: rcpt: %s", response); olderrors = Errors; (void) sendtolist(response, NULLADDR, &e->e_sendqueue, 0, e); Errors = olderrors; return; } /* ** MILTER_DELRCPT -- Delete the supplied recipient from the message ** ** Parameters: ** response -- encoded form of recipient address. ** rlen -- length of response. ** e -- current envelope. ** ** Returns: ** none */ static void milter_delrcpt(response, rlen, e) char *response; ssize_t rlen; ENVELOPE *e; { if (tTd(64, 10)) sm_dprintf("milter_delrcpt: "); /* sanity checks */ if (response == NULL) { if (tTd(64, 10)) sm_dprintf("NULL response\n"); return; } if (*response == '\0' || strlen(response) + 1 != (size_t) rlen) { if (tTd(64, 10)) sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n", (int) strlen(response), (int) (rlen - 1)); return; } if (tTd(64, 10)) sm_dprintf("%s\n", response); if (MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter delete: rcpt %s", response); (void) removefromlist(response, &e->e_sendqueue, e); return; } /* ** MILTER_REPLBODY -- Replace the current data file with new body ** ** Parameters: ** response -- encoded form of new body. ** rlen -- length of response. ** newfilter -- if first time called by a new filter ** e -- current envelope. ** ** Returns: ** 0 upon success, -1 upon failure */ static int milter_replbody(response, rlen, newfilter, e) char *response; ssize_t rlen; bool newfilter; ENVELOPE *e; { static char prevchar; int i; if (tTd(64, 10)) sm_dprintf("milter_replbody\n"); /* If a new filter, reset previous character and truncate data file */ if (newfilter) { off_t prevsize; char dfname[MAXPATHLEN]; (void) sm_strlcpy(dfname, queuename(e, DATAFL_LETTER), sizeof(dfname)); /* Reset prevchar */ prevchar = '\0'; /* Get the current data file information */ prevsize = sm_io_getinfo(e->e_dfp, SM_IO_WHAT_SIZE, NULL); if (prevsize < 0) prevsize = 0; /* truncate current data file */ if (sm_io_getinfo(e->e_dfp, SM_IO_WHAT_ISTYPE, BF_FILE_TYPE)) { if (sm_io_setinfo(e->e_dfp, SM_BF_TRUNCATE, NULL) < 0) { MILTER_DF_ERROR("milter_replbody: sm_io truncate %s: %s"); return -1; } } else { int err; err = sm_io_error(e->e_dfp); (void) sm_io_flush(e->e_dfp, SM_TIME_DEFAULT); /* ** Clear error if tried to fflush() ** a read-only file pointer and ** there wasn't a previous error. */ if (err == 0) sm_io_clearerr(e->e_dfp); /* errno is set implicitly by fseek() before return */ err = sm_io_seek(e->e_dfp, SM_TIME_DEFAULT, 0, SEEK_SET); if (err < 0) { MILTER_DF_ERROR("milter_replbody: sm_io_seek %s: %s"); return -1; } # if NOFTRUNCATE /* XXX: Not much we can do except rewind it */ errno = EINVAL; MILTER_DF_ERROR("milter_replbody: ftruncate not available on this platform (%s:%s)"); return -1; # else /* NOFTRUNCATE */ err = ftruncate(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), 0); if (err < 0) { MILTER_DF_ERROR("milter_replbody: sm_io ftruncate %s: %s"); return -1; } # endif /* NOFTRUNCATE */ } if (prevsize > e->e_msgsize) e->e_msgsize = 0; else e->e_msgsize -= prevsize; } if (newfilter && MilterLogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "Milter message: body replaced"); if (response == NULL) { /* Flush the buffered '\r' */ if (prevchar == '\r') { (void) sm_io_putc(e->e_dfp, SM_TIME_DEFAULT, prevchar); e->e_msgsize++; } return 0; } for (i = 0; i < rlen; i++) { /* Buffered char from last chunk */ if (i == 0 && prevchar == '\r') { /* Not CRLF, output prevchar */ if (response[i] != '\n') { (void) sm_io_putc(e->e_dfp, SM_TIME_DEFAULT, prevchar); e->e_msgsize++; } prevchar = '\0'; } /* Turn CRLF into LF */ if (response[i] == '\r') { /* check if at end of chunk */ if (i + 1 < rlen) { /* If LF, strip CR */ if (response[i + 1] == '\n') i++; } else { /* check next chunk */ prevchar = '\r'; continue; } } (void) sm_io_putc(e->e_dfp, SM_TIME_DEFAULT, response[i]); e->e_msgsize++; } return 0; } /* ** MTA callouts */ /* ** MILTER_INIT -- open and negotiate with all of the filters ** ** Parameters: ** e -- current envelope. ** state -- return state from response. ** milters -- milters structure. ** ** Returns: ** true iff at least one filter is active */ /* ARGSUSED */ bool milter_init(e, state, milters) ENVELOPE *e; char *state; milters_T *milters; { int i; if (tTd(64, 10)) sm_dprintf("milter_init\n"); memset(milters, '\0', sizeof(*milters)); *state = SMFIR_CONTINUE; if (InputFilters[0] == NULL) { if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "Milter: no active filter"); return false; } for (i = 0; InputFilters[i] != NULL; i++) { struct milter *m = InputFilters[i]; m->mf_sock = milter_open(m, false, e); if (m->mf_state == SMFS_ERROR) { MILTER_CHECK_ERROR(true, continue); break; } if (m->mf_sock < 0 || milter_negotiate(m, e, milters) < 0 || m->mf_state == SMFS_ERROR) { if (tTd(64, 5)) sm_dprintf("milter_init(%s): failed to %s\n", m->mf_name, m->mf_sock < 0 ? "open" : "negotiate"); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "Milter (%s): init failed to %s", m->mf_name, m->mf_sock < 0 ? "open" : "negotiate"); /* if negotiation failure, close socket */ milter_error(m, e); MILTER_CHECK_ERROR(true, continue); continue; } if (MilterLogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "Milter (%s): init success to %s", m->mf_name, m->mf_sock < 0 ? "open" : "negotiate"); } /* ** If something temp/perm failed with one of the filters, ** we won't be using any of them, so clear any existing ** connections. */ if (*state != SMFIR_CONTINUE) milter_quit(e); return true; } /* ** MILTER_CONNECT -- send connection info to milter filters ** ** Parameters: ** hostname -- hostname of remote machine. ** addr -- address of remote machine. ** e -- current envelope. ** state -- return state from response. ** ** Returns: ** response string (may be NULL) */ char * milter_connect(hostname, addr, e, state) char *hostname; SOCKADDR addr; ENVELOPE *e; char *state; { char family; unsigned short port; char *buf, *bp; char *response; char *sockinfo = NULL; ssize_t s; # if NETINET6 char buf6[INET6_ADDRSTRLEN]; # endif /* NETINET6 */ if (tTd(64, 10)) sm_dprintf("milter_connect(%s)\n", hostname); if (MilterLogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "Milter: connect to filters"); /* gather data */ switch (addr.sa.sa_family) { # if NETUNIX case AF_UNIX: family = SMFIA_UNIX; port = htons(0); sockinfo = addr.sunix.sun_path; break; # endif /* NETUNIX */ # if NETINET case AF_INET: family = SMFIA_INET; port = addr.sin.sin_port; sockinfo = (char *) inet_ntoa(addr.sin.sin_addr); break; # endif /* NETINET */ # if NETINET6 case AF_INET6: if (IN6_IS_ADDR_V4MAPPED(&addr.sin6.sin6_addr)) family = SMFIA_INET; else family = SMFIA_INET6; port = addr.sin6.sin6_port; sockinfo = anynet_ntop(&addr.sin6.sin6_addr, buf6, sizeof(buf6)); if (sockinfo == NULL) sockinfo = ""; break; # endif /* NETINET6 */ default: family = SMFIA_UNKNOWN; break; } s = strlen(hostname) + 1 + sizeof(family); if (family != SMFIA_UNKNOWN) s += sizeof(port) + strlen(sockinfo) + 1; buf = (char *) xalloc(s); bp = buf; /* put together data */ (void) memcpy(bp, hostname, strlen(hostname)); bp += strlen(hostname); *bp++ = '\0'; (void) memcpy(bp, &family, sizeof(family)); bp += sizeof(family); if (family != SMFIA_UNKNOWN) { (void) memcpy(bp, &port, sizeof(port)); bp += sizeof(port); /* include trailing '\0' */ (void) memcpy(bp, sockinfo, strlen(sockinfo) + 1); } response = milter_command(SMFIC_CONNECT, buf, s, SMFIM_CONNECT, e, state, "connect", false); sm_free(buf); /* XXX */ /* ** If this message connection is done for, ** close the filters. */ if (*state != SMFIR_CONTINUE) { if (MilterLogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "Milter: connect, ending"); milter_quit(e); } else milter_per_connection_check(e); /* ** SMFIR_REPLYCODE can't work with connect due to ** the requirements of SMTP. Therefore, ignore the ** reply code text but keep the state it would reflect. */ if (*state == SMFIR_REPLYCODE) { if (response != NULL && *response == '4') { if (strncmp(response, "421 ", 4) == 0) *state = SMFIR_SHUTDOWN; else *state = SMFIR_TEMPFAIL; } else *state = SMFIR_REJECT; if (response != NULL) { sm_free(response); /* XXX */ response = NULL; } } return response; } /* ** MILTER_HELO -- send SMTP HELO/EHLO command info to milter filters ** ** Parameters: ** helo -- argument to SMTP HELO/EHLO command. ** e -- current envelope. ** state -- return state from response. ** ** Returns: ** response string (may be NULL) */ char * milter_helo(helo, e, state) char *helo; ENVELOPE *e; char *state; { int i; char *response; if (tTd(64, 10)) sm_dprintf("milter_helo(%s)\n", helo); /* HELO/EHLO can come at any point */ for (i = 0; InputFilters[i] != NULL; i++) { struct milter *m = InputFilters[i]; switch (m->mf_state) { case SMFS_INMSG: /* abort in message filters */ milter_abort_filter(m, e); /* FALLTHROUGH */ case SMFS_DONE: /* reset done filters */ m->mf_state = SMFS_OPEN; break; } } response = milter_command(SMFIC_HELO, helo, strlen(helo) + 1, SMFIM_HELO, e, state, "helo", false); milter_per_connection_check(e); return response; } /* ** MILTER_ENVFROM -- send SMTP MAIL command info to milter filters ** ** Parameters: ** args -- SMTP MAIL command args (args[0] == sender). ** e -- current envelope. ** state -- return state from response. ** ** Returns: ** response string (may be NULL) */ char * milter_envfrom(args, e, state) char **args; ENVELOPE *e; char *state; { int i; char *buf, *bp; char *response; ssize_t s; if (tTd(64, 10)) { sm_dprintf("milter_envfrom:"); for (i = 0; args[i] != NULL; i++) sm_dprintf(" %s", args[i]); sm_dprintf("\n"); } /* sanity check */ if (args[0] == NULL) { *state = SMFIR_REJECT; if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "Milter: reject, no sender"); return NULL; } /* new message, so ... */ for (i = 0; InputFilters[i] != NULL; i++) { struct milter *m = InputFilters[i]; switch (m->mf_state) { case SMFS_INMSG: /* abort in message filters */ milter_abort_filter(m, e); /* FALLTHROUGH */ case SMFS_DONE: /* reset done filters */ m->mf_state = SMFS_OPEN; break; } } /* put together data */ s = 0; for (i = 0; args[i] != NULL; i++) s += strlen(args[i]) + 1; if (s < 0) { *state = SMFIR_TEMPFAIL; return NULL; } buf = (char *) xalloc(s); bp = buf; for (i = 0; args[i] != NULL; i++) { (void) sm_strlcpy(bp, args[i], s - (bp - buf)); bp += strlen(bp) + 1; } if (MilterLogLevel > 14) sm_syslog(LOG_INFO, e->e_id, "Milter: sender: %s", buf); /* send it over */ response = milter_command(SMFIC_MAIL, buf, s, SMFIM_ENVFROM, e, state, "mail", false); sm_free(buf); /* XXX */ /* ** If filter rejects/discards a per message command, ** abort the other filters since we are done with the ** current message. */ MILTER_CHECK_DONE_MSG(); if (MilterLogLevel > 10 && *state == SMFIR_REJECT) sm_syslog(LOG_INFO, e->e_id, "Milter: reject, sender"); return response; } /* ** MILTER_ENVRCPT -- send SMTP RCPT command info to milter filters ** ** Parameters: ** args -- SMTP MAIL command args (args[0] == recipient). ** e -- current envelope. ** state -- return state from response. ** rcpt_error -- does RCPT have an error? ** ** Returns: ** response string (may be NULL) */ char * milter_envrcpt(args, e, state, rcpt_error) char **args; ENVELOPE *e; char *state; bool rcpt_error; { int i; char *buf, *bp; char *response; ssize_t s; if (tTd(64, 10)) { sm_dprintf("milter_envrcpt:"); for (i = 0; args[i] != NULL; i++) sm_dprintf(" %s", args[i]); sm_dprintf("\n"); } /* sanity check */ if (args[0] == NULL) { *state = SMFIR_REJECT; if (MilterLogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "Milter: reject, no rcpt"); return NULL; } /* put together data */ s = 0; for (i = 0; args[i] != NULL; i++) s += strlen(args[i]) + 1; if (s < 0) { *state = SMFIR_TEMPFAIL; return NULL; } buf = (char *) xalloc(s); bp = buf; for (i = 0; args[i] != NULL; i++) { (void) sm_strlcpy(bp, args[i], s - (bp - buf)); bp += strlen(bp) + 1; } if (MilterLogLevel > 14) sm_syslog(LOG_INFO, e->e_id, "Milter: rcpts: %s", buf); /* send it over */ response = milter_command(SMFIC_RCPT, buf, s, SMFIM_ENVRCPT, e, state, "rcpt", rcpt_error); sm_free(buf); /* XXX */ return response; } /* ** MILTER_DATA_CMD -- send SMTP DATA command info to milter filters ** ** Parameters: ** e -- current envelope. ** state -- return state from response. ** ** Returns: ** response string (may be NULL) */ char * milter_data_cmd(e, state) ENVELOPE *e; char *state; { if (tTd(64, 10)) sm_dprintf("milter_data_cmd\n"); /* send it over */ return milter_command(SMFIC_DATA, NULL, 0, SMFIM_DATA, e, state, "data", false); } /* ** MILTER_DATA -- send message headers/body and gather final message results ** ** Parameters: ** e -- current envelope. ** state -- return state from response. ** ** Returns: ** response string (may be NULL) ** ** Side effects: ** - Uses e->e_dfp for access to the body ** - Can call the various milter action routines to ** modify the envelope or message. */ /* flow through code using continue; don't wrap in do {} while */ # define MILTER_CHECK_RESULTS() \ if (m->mf_state == SMFS_ERROR && *state == SMFIR_CONTINUE) \ { \ MILTER_SET_STATE; \ } \ if (*state == SMFIR_ACCEPT || \ m->mf_state == SMFS_DONE || \ m->mf_state == SMFS_ERROR) \ { \ if (m->mf_state != SMFS_ERROR) \ m->mf_state = SMFS_DONE; \ continue; /* to next filter */ \ } \ if (*state != SMFIR_CONTINUE) \ { \ m->mf_state = SMFS_DONE; \ goto finishup; \ } char * milter_data(e, state) ENVELOPE *e; char *state; { bool replbody = false; /* milter_replbody() called? */ bool replfailed = false; /* milter_replbody() failed? */ bool rewind = false; /* rewind data file? */ bool dfopen = false; /* data file open for writing? */ bool newfilter; /* reset on each new filter */ char rcmd; int i; int save_errno; char *response = NULL; time_t eomsent; ssize_t rlen; if (tTd(64, 10)) sm_dprintf("milter_data\n"); *state = SMFIR_CONTINUE; /* ** XXX: Should actually send body chunks to each filter ** a chunk at a time instead of sending the whole body to ** each filter in turn. However, only if the filters don't ** change the body. */ for (i = 0; InputFilters[i] != NULL; i++) { int idx; char **macros; struct milter *m = InputFilters[i]; if (*state != SMFIR_CONTINUE && *state != SMFIR_ACCEPT) { /* ** A previous filter has dealt with the message, ** safe to stop processing the filters. */ break; } /* Now reset state for later evaluation */ *state = SMFIR_CONTINUE; newfilter = true; /* previous problem? */ if (m->mf_state == SMFS_ERROR) { MILTER_CHECK_ERROR(false, continue); break; } /* sanity checks */ if (m->mf_sock < 0 || (m->mf_state != SMFS_OPEN && m->mf_state != SMFS_INMSG)) continue; m->mf_state = SMFS_INMSG; /* check if filter wants the headers */ if (!bitset(SMFIP_NOHDRS, m->mf_pflags)) { response = milter_headers(m, e, state); MILTER_CHECK_RESULTS(); } /* check if filter wants EOH */ if (!bitset(SMFIP_NOEOH, m->mf_pflags)) { if (tTd(64, 10)) sm_dprintf("milter_data: eoh\n"); if ((m->mf_lflags & MI_LFLAGS_SYM(SMFIM_EOH)) != 0) idx = m->mf_idx; else idx = 0; SM_ASSERT(idx >= 0 && idx <= MAXFILTERS); macros = MilterMacros[SMFIM_EOH][idx]; if (macros != NULL) { milter_send_macros(m, macros, SMFIC_EOH, e); MILTER_CHECK_RESULTS(); } /* send it over */ response = milter_send_command(m, SMFIC_EOH, NULL, 0, e, state, "eoh"); MILTER_CHECK_RESULTS(); } /* check if filter wants the body */ if (!bitset(SMFIP_NOBODY, m->mf_pflags) && e->e_dfp != NULL) { rewind = true; response = milter_body(m, e, state); MILTER_CHECK_RESULTS(); } if ((m->mf_lflags & MI_LFLAGS_SYM(SMFIM_EOH)) != 0) idx = m->mf_idx; else idx = 0; SM_ASSERT(idx >= 0 && idx <= MAXFILTERS); macros = MilterMacros[SMFIM_EOM][idx]; if (macros != NULL) { milter_send_macros(m, macros, SMFIC_BODYEOB, e); MILTER_CHECK_RESULTS(); } /* send the final body chunk */ (void) milter_write(m, SMFIC_BODYEOB, NULL, 0, m->mf_timeout[SMFTO_WRITE], e, "eom"); /* Get time EOM sent for timeout */ eomsent = curtime(); /* deal with the possibility of multiple responses */ while (*state == SMFIR_CONTINUE) { /* Check total timeout from EOM to final ACK/NAK */ if (m->mf_timeout[SMFTO_EOM] > 0 && curtime() - eomsent >= m->mf_timeout[SMFTO_EOM]) { if (tTd(64, 5)) sm_dprintf("milter_data(%s): EOM ACK/NAK timeout\n", m->mf_name); if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_data(%s): EOM ACK/NAK timeout", m->mf_name); milter_error(m, e); MILTER_CHECK_ERROR(false, break); break; } response = milter_read(m, &rcmd, &rlen, m->mf_timeout[SMFTO_READ], e, "eom"); if (m->mf_state == SMFS_ERROR) break; if (tTd(64, 10)) sm_dprintf("milter_data(%s): state %c\n", m->mf_name, (char) rcmd); switch (rcmd) { case SMFIR_REPLYCODE: MILTER_CHECK_REPLYCODE("554 5.7.1 Command rejected"); if (MilterLogLevel > 12) sm_syslog(LOG_INFO, e->e_id, "milter=%s, reject=%s", m->mf_name, response); *state = rcmd; m->mf_state = SMFS_DONE; break; case SMFIR_REJECT: /* log msg at end of function */ if (MilterLogLevel > 12) sm_syslog(LOG_INFO, e->e_id, "milter=%s, reject", m->mf_name); *state = rcmd; m->mf_state = SMFS_DONE; break; case SMFIR_DISCARD: if (MilterLogLevel > 12) sm_syslog(LOG_INFO, e->e_id, "milter=%s, discard", m->mf_name); *state = rcmd; m->mf_state = SMFS_DONE; break; case SMFIR_TEMPFAIL: if (MilterLogLevel > 12) sm_syslog(LOG_INFO, e->e_id, "milter=%s, tempfail", m->mf_name); *state = rcmd; m->mf_state = SMFS_DONE; break; case SMFIR_CONTINUE: case SMFIR_ACCEPT: /* this filter is done with message */ if (replfailed) *state = SMFIR_TEMPFAIL; else *state = SMFIR_ACCEPT; m->mf_state = SMFS_DONE; break; case SMFIR_PROGRESS: break; case SMFIR_QUARANTINE: if (!bitset(SMFIF_QUARANTINE, m->mf_fflags)) { if (MilterLogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "milter_data(%s): lied about quarantining, honoring request anyway", m->mf_name); } if (response == NULL) response = newstr(""); if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "milter=%s, quarantine=%s", m->mf_name, response); e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, response); macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), e->e_quarmsg); break; case SMFIR_ADDHEADER: if (!bitset(SMFIF_ADDHDRS, m->mf_fflags)) { if (MilterLogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "milter_data(%s): lied about adding headers, honoring request anyway", m->mf_name); } milter_addheader(m, response, rlen, e); break; case SMFIR_INSHEADER: if (!bitset(SMFIF_ADDHDRS, m->mf_fflags)) { if (MilterLogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "milter_data(%s): lied about adding headers, honoring request anyway", m->mf_name); } milter_insheader(m, response, rlen, e); break; case SMFIR_CHGHEADER: if (!bitset(SMFIF_CHGHDRS, m->mf_fflags)) { if (MilterLogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "milter_data(%s): lied about changing headers, honoring request anyway", m->mf_name); } milter_changeheader(m, response, rlen, e); break; case SMFIR_CHGFROM: if (!bitset(SMFIF_CHGFROM, m->mf_fflags)) { if (MilterLogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "milter_data(%s) lied about changing sender, honoring request anyway", m->mf_name); } milter_chgfrom(response, rlen, e); break; case SMFIR_ADDRCPT: if (!bitset(SMFIF_ADDRCPT, m->mf_fflags)) { if (MilterLogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "milter_data(%s) lied about adding recipients, honoring request anyway", m->mf_name); } milter_addrcpt(response, rlen, e); break; case SMFIR_ADDRCPT_PAR: if (!bitset(SMFIF_ADDRCPT_PAR, m->mf_fflags)) { if (MilterLogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "milter_data(%s) lied about adding recipients with parameters, honoring request anyway", m->mf_name); } milter_addrcpt_par(response, rlen, e); break; case SMFIR_DELRCPT: if (!bitset(SMFIF_DELRCPT, m->mf_fflags)) { if (MilterLogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "milter_data(%s): lied about removing recipients, honoring request anyway", m->mf_name); } milter_delrcpt(response, rlen, e); break; case SMFIR_REPLBODY: if (!bitset(SMFIF_MODBODY, m->mf_fflags)) { if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_data(%s): lied about replacing body, rejecting request and tempfailing message", m->mf_name); replfailed = true; break; } /* already failed in attempt */ if (replfailed) break; if (!dfopen) { if (milter_reopen_df(e) < 0) { replfailed = true; break; } dfopen = true; rewind = true; } if (milter_replbody(response, rlen, newfilter, e) < 0) replfailed = true; newfilter = false; replbody = true; break; default: /* Invalid response to command */ if (MilterLogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "milter_data(%s): returned bogus response %c", m->mf_name, rcmd); milter_error(m, e); break; } if (rcmd != SMFIR_REPLYCODE && response != NULL) { sm_free(response); /* XXX */ response = NULL; } if (m->mf_state == SMFS_ERROR) break; } if (replbody && !replfailed) { /* flush possible buffered character */ milter_replbody(NULL, 0, !replbody, e); replbody = false; } if (m->mf_state == SMFS_ERROR) { MILTER_CHECK_ERROR(false, continue); goto finishup; } } finishup: /* leave things in the expected state if we touched it */ if (replfailed) { if (*state == SMFIR_CONTINUE || *state == SMFIR_ACCEPT) { *state = SMFIR_TEMPFAIL; SM_FREE_CLR(response); } if (dfopen) { (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT); e->e_dfp = NULL; e->e_flags &= ~EF_HAS_DF; dfopen = false; } rewind = false; } if ((dfopen && milter_reset_df(e) < 0) || (rewind && bfrewind(e->e_dfp) < 0)) { save_errno = errno; ExitStat = EX_IOERR; /* ** If filter told us to keep message but we had ** an error, we can't really keep it, tempfail it. */ if (*state == SMFIR_CONTINUE || *state == SMFIR_ACCEPT) { *state = SMFIR_TEMPFAIL; SM_FREE_CLR(response); } errno = save_errno; syserr("milter_data: %s/%cf%s: read error", qid_printqueue(e->e_qgrp, e->e_qdir), DATAFL_LETTER, e->e_id); } MILTER_CHECK_DONE_MSG(); if (MilterLogLevel > 10 && *state == SMFIR_REJECT) sm_syslog(LOG_INFO, e->e_id, "Milter: reject, data"); return response; } /* ** MILTER_UNKNOWN -- send any unrecognized or unimplemented command ** string to milter filters ** ** Parameters: ** smtpcmd -- the string itself. ** e -- current envelope. ** state -- return state from response. ** ** ** Returns: ** response string (may be NULL) */ char * milter_unknown(smtpcmd, e, state) char *smtpcmd; ENVELOPE *e; char *state; { if (tTd(64, 10)) sm_dprintf("milter_unknown(%s)\n", smtpcmd); return milter_command(SMFIC_UNKNOWN, smtpcmd, strlen(smtpcmd) + 1, SMFIM_NOMACROS, e, state, "unknown", false); } /* ** MILTER_QUIT -- informs the filter(s) we are done and closes connection(s) ** ** Parameters: ** e -- current envelope. ** ** Returns: ** none */ void milter_quit(e) ENVELOPE *e; { int i; if (tTd(64, 10)) sm_dprintf("milter_quit(%s)\n", e->e_id); for (i = 0; InputFilters[i] != NULL; i++) milter_quit_filter(InputFilters[i], e); } /* ** MILTER_ABORT -- informs the filter(s) that we are aborting current message ** ** Parameters: ** e -- current envelope. ** ** Returns: ** none */ void milter_abort(e) ENVELOPE *e; { int i; if (tTd(64, 10)) sm_dprintf("milter_abort\n"); for (i = 0; InputFilters[i] != NULL; i++) { struct milter *m = InputFilters[i]; /* sanity checks */ if (m->mf_sock < 0 || m->mf_state != SMFS_INMSG) continue; milter_abort_filter(m, e); } } #endif /* MILTER */ Index: head/contrib/sendmail/src/mime.c =================================================================== --- head/contrib/sendmail/src/mime.c (revision 249728) +++ head/contrib/sendmail/src/mime.c (revision 249729) @@ -1,1325 +1,1326 @@ /* - * Copyright (c) 1998-2003, 2006 Sendmail, Inc. and its suppliers. + * Copyright (c) 1998-2003, 2006, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1994, 1996-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1994 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include #include -SM_RCSID("@(#)$Id: mime.c,v 8.147 2007/09/26 23:29:11 ca Exp $") +SM_RCSID("@(#)$Id: mime.c,v 8.148 2013/03/12 15:24:53 ca Exp $") /* ** MIME support. ** ** I am indebted to John Beck of Hewlett-Packard, who contributed ** his code to me for inclusion. As it turns out, I did not use ** his code since he used a "minimum change" approach that used ** several temp files, and I wanted a "minimum impact" approach ** that would avoid copying. However, looking over his code ** helped me cement my understanding of the problem. ** ** I also looked at, but did not directly use, Nathaniel ** Borenstein's "code.c" module. Again, it functioned as ** a file-to-file translator, which did not fit within my ** design bounds, but it was a useful base for understanding ** the problem. */ /* use "old" mime 7 to 8 algorithm by default */ #ifndef MIME7TO8_OLD # define MIME7TO8_OLD 1 #endif /* ! MIME7TO8_OLD */ #if MIME8TO7 static int isboundary __P((char *, char **)); static int mimeboundary __P((char *, char **)); static int mime_getchar __P((SM_FILE_T *, char **, int *)); static int mime_getchar_crlf __P((SM_FILE_T *, char **, int *)); /* character set for hex and base64 encoding */ static char Base16Code[] = "0123456789ABCDEF"; static char Base64Code[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /* types of MIME boundaries */ # define MBT_SYNTAX 0 /* syntax error */ # define MBT_NOTSEP 1 /* not a boundary */ # define MBT_INTERMED 2 /* intermediate boundary (no trailing --) */ # define MBT_FINAL 3 /* final boundary (trailing -- included) */ static char *MimeBoundaryNames[] = { "SYNTAX", "NOTSEP", "INTERMED", "FINAL" }; static bool MapNLtoCRLF; /* ** MIME8TO7 -- output 8 bit body in 7 bit format ** ** The header has already been output -- this has to do the ** 8 to 7 bit conversion. It would be easy if we didn't have ** to deal with nested formats (multipart/xxx and message/rfc822). ** ** We won't be called if we don't have to do a conversion, and ** appropriate MIME-Version: and Content-Type: fields have been ** output. Any Content-Transfer-Encoding: field has not been ** output, and we can add it here. ** ** Parameters: ** mci -- mailer connection information. ** header -- the header for this body part. ** e -- envelope. ** boundaries -- the currently pending message boundaries. ** NULL if we are processing the outer portion. ** flags -- to tweak processing. ** level -- recursion level. ** ** Returns: ** An indicator of what terminated the message part: ** MBT_FINAL -- the final boundary ** MBT_INTERMED -- an intermediate boundary ** MBT_NOTSEP -- an end of file ** SM_IO_EOF -- I/O error occurred */ struct args { char *a_field; /* name of field */ char *a_value; /* value of that field */ }; int mime8to7(mci, header, e, boundaries, flags, level) register MCI *mci; HDR *header; register ENVELOPE *e; char **boundaries; int flags; int level; { register char *p; int linelen; + int blen; int bt; off_t offset; size_t sectionsize, sectionhighbits; int i; char *type; char *subtype; char *cte; char **pvp; int argc = 0; char *bp; bool use_qp = false; struct args argv[MAXMIMEARGS]; char bbuf[128]; char buf[MAXLINE]; char pvpbuf[MAXLINE]; extern unsigned char MimeTokenTab[256]; if (level > MAXMIMENESTING) { if (!bitset(EF_TOODEEP, e->e_flags)) { if (tTd(43, 4)) sm_dprintf("mime8to7: too deep, level=%d\n", level); usrerr("mime8to7: recursion level %d exceeded", level); e->e_flags |= EF_DONT_MIME|EF_TOODEEP; } } if (tTd(43, 1)) { sm_dprintf("mime8to7: flags = %x, boundaries =", flags); if (boundaries[0] == NULL) sm_dprintf(" "); else { for (i = 0; boundaries[i] != NULL; i++) sm_dprintf(" %s", boundaries[i]); } sm_dprintf("\n"); } MapNLtoCRLF = true; p = hvalue("Content-Transfer-Encoding", header); if (p == NULL || (pvp = prescan(p, '\0', pvpbuf, sizeof(pvpbuf), NULL, MimeTokenTab, false)) == NULL || pvp[0] == NULL) { cte = NULL; } else { cataddr(pvp, NULL, buf, sizeof(buf), '\0', false); cte = sm_rpool_strdup_x(e->e_rpool, buf); } type = subtype = NULL; p = hvalue("Content-Type", header); if (p == NULL) { if (bitset(M87F_DIGEST, flags)) p = "message/rfc822"; else p = "text/plain"; } if (p != NULL && (pvp = prescan(p, '\0', pvpbuf, sizeof(pvpbuf), NULL, MimeTokenTab, false)) != NULL && pvp[0] != NULL) { if (tTd(43, 40)) { for (i = 0; pvp[i] != NULL; i++) sm_dprintf("pvp[%d] = \"%s\"\n", i, pvp[i]); } type = *pvp++; if (*pvp != NULL && strcmp(*pvp, "/") == 0 && *++pvp != NULL) { subtype = *pvp++; } /* break out parameters */ while (*pvp != NULL && argc < MAXMIMEARGS) { /* skip to semicolon separator */ while (*pvp != NULL && strcmp(*pvp, ";") != 0) pvp++; if (*pvp++ == NULL || *pvp == NULL) break; /* complain about empty values */ if (strcmp(*pvp, ";") == 0) { usrerr("mime8to7: Empty parameter in Content-Type header"); /* avoid bounce loops */ e->e_flags |= EF_DONT_MIME; continue; } /* extract field name */ argv[argc].a_field = *pvp++; /* see if there is a value */ if (*pvp != NULL && strcmp(*pvp, "=") == 0 && (*++pvp == NULL || strcmp(*pvp, ";") != 0)) { argv[argc].a_value = *pvp; argc++; } } } /* check for disaster cases */ if (type == NULL) type = "-none-"; if (subtype == NULL) subtype = "-none-"; /* don't propagate some flags more than one level into the message */ flags &= ~M87F_DIGEST; /* ** Check for cases that can not be encoded. ** ** For example, you can't encode certain kinds of types ** or already-encoded messages. If we find this case, ** just copy it through. */ (void) sm_snprintf(buf, sizeof(buf), "%.100s/%.100s", type, subtype); if (wordinclass(buf, 'n') || (cte != NULL && !wordinclass(cte, 'e'))) flags |= M87F_NO8BIT; # ifdef USE_B_CLASS if (wordinclass(buf, 'b') || wordinclass(type, 'b')) MapNLtoCRLF = false; # endif /* USE_B_CLASS */ if (wordinclass(buf, 'q') || wordinclass(type, 'q')) use_qp = true; /* ** Multipart requires special processing. ** ** Do a recursive descent into the message. */ if (sm_strcasecmp(type, "multipart") == 0 && (!bitset(M87F_NO8BIT, flags) || bitset(M87F_NO8TO7, flags)) && !bitset(EF_TOODEEP, e->e_flags) ) { if (sm_strcasecmp(subtype, "digest") == 0) flags |= M87F_DIGEST; for (i = 0; i < argc; i++) { if (sm_strcasecmp(argv[i].a_field, "boundary") == 0) break; } if (i >= argc || argv[i].a_value == NULL) { usrerr("mime8to7: Content-Type: \"%s\": %s boundary", i >= argc ? "missing" : "bogus", p); p = "---"; /* avoid bounce loops */ e->e_flags |= EF_DONT_MIME; } else { p = argv[i].a_value; stripquotes(p); } if (sm_strlcpy(bbuf, p, sizeof(bbuf)) >= sizeof(bbuf)) { usrerr("mime8to7: multipart boundary \"%s\" too long", p); /* avoid bounce loops */ e->e_flags |= EF_DONT_MIME; } if (tTd(43, 1)) sm_dprintf("mime8to7: multipart boundary \"%s\"\n", bbuf); for (i = 0; i < MAXMIMENESTING; i++) { if (boundaries[i] == NULL) break; } if (i >= MAXMIMENESTING) { if (tTd(43, 4)) sm_dprintf("mime8to7: too deep, i=%d\n", i); if (!bitset(EF_TOODEEP, e->e_flags)) usrerr("mime8to7: multipart nesting boundary too deep"); /* avoid bounce loops */ e->e_flags |= EF_DONT_MIME|EF_TOODEEP; } else { boundaries[i] = bbuf; boundaries[i + 1] = NULL; } mci->mci_flags |= MCIF_INMIME; /* skip the early "comment" prologue */ if (!putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; bt = MBT_FINAL; - while (sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, sizeof(buf)) - != NULL) + while ((blen = sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, + sizeof(buf))) >= 0) { bt = mimeboundary(buf, boundaries); if (bt != MBT_NOTSEP) break; - if (!putxline(buf, strlen(buf), mci, + if (!putxline(buf, blen, mci, PXLF_MAPFROM|PXLF_STRIP8BIT)) goto writeerr; if (tTd(43, 99)) sm_dprintf(" ...%s", buf); } if (sm_io_eof(e->e_dfp)) bt = MBT_FINAL; while (bt != MBT_FINAL) { auto HDR *hdr = NULL; (void) sm_strlcpyn(buf, sizeof(buf), 2, "--", bbuf); if (!putline(buf, mci)) goto writeerr; if (tTd(43, 35)) sm_dprintf(" ...%s\n", buf); collect(e->e_dfp, false, &hdr, e, false); if (tTd(43, 101)) putline("+++after collect", mci); if (!putheader(mci, hdr, e, flags)) goto writeerr; if (tTd(43, 101)) putline("+++after putheader", mci); bt = mime8to7(mci, hdr, e, boundaries, flags, level + 1); if (bt == SM_IO_EOF) goto writeerr; } (void) sm_strlcpyn(buf, sizeof(buf), 3, "--", bbuf, "--"); if (!putline(buf, mci)) goto writeerr; if (tTd(43, 35)) sm_dprintf(" ...%s\n", buf); boundaries[i] = NULL; mci->mci_flags &= ~MCIF_INMIME; /* skip the late "comment" epilogue */ - while (sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, sizeof(buf)) - != NULL) + while ((blen = sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, + sizeof(buf))) >= 0) { bt = mimeboundary(buf, boundaries); if (bt != MBT_NOTSEP) break; - if (!putxline(buf, strlen(buf), mci, + if (!putxline(buf, blen, mci, PXLF_MAPFROM|PXLF_STRIP8BIT)) goto writeerr; if (tTd(43, 99)) sm_dprintf(" ...%s", buf); } if (sm_io_eof(e->e_dfp)) bt = MBT_FINAL; if (tTd(43, 3)) sm_dprintf("\t\t\tmime8to7=>%s (multipart)\n", MimeBoundaryNames[bt]); return bt; } /* ** Message/xxx types -- recurse exactly once. ** ** Class 's' is predefined to have "rfc822" only. */ if (sm_strcasecmp(type, "message") == 0) { if (!wordinclass(subtype, 's') || bitset(EF_TOODEEP, e->e_flags)) { flags |= M87F_NO8BIT; } else { auto HDR *hdr = NULL; if (!putline("", mci)) goto writeerr; mci->mci_flags |= MCIF_INMIME; collect(e->e_dfp, false, &hdr, e, false); if (tTd(43, 101)) putline("+++after collect", mci); if (!putheader(mci, hdr, e, flags)) goto writeerr; if (tTd(43, 101)) putline("+++after putheader", mci); if (hvalue("MIME-Version", hdr) == NULL && !bitset(M87F_NO8TO7, flags) && !putline("MIME-Version: 1.0", mci)) goto writeerr; bt = mime8to7(mci, hdr, e, boundaries, flags, level + 1); mci->mci_flags &= ~MCIF_INMIME; return bt; } } /* ** Non-compound body type ** ** Compute the ratio of seven to eight bit characters; ** use that as a heuristic to decide how to do the ** encoding. */ sectionsize = sectionhighbits = 0; if (!bitset(M87F_NO8BIT|M87F_NO8TO7, flags)) { /* remember where we were */ offset = sm_io_tell(e->e_dfp, SM_TIME_DEFAULT); if (offset == -1) syserr("mime8to7: cannot sm_io_tell on %cf%s", DATAFL_LETTER, e->e_id); /* do a scan of this body type to count character types */ - while (sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, sizeof(buf)) - != NULL) + while ((blen = sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, + sizeof(buf))) >= 0) { if (mimeboundary(buf, boundaries) != MBT_NOTSEP) break; - for (p = buf; *p != '\0'; p++) + for (i = 0; i < blen; i++) { /* count bytes with the high bit set */ sectionsize++; - if (bitset(0200, *p)) + if (bitset(0200, buf[i])) sectionhighbits++; } /* ** Heuristic: if 1/4 of the first 4K bytes are 8-bit, ** assume base64. This heuristic avoids double-reading ** large graphics or video files. */ if (sectionsize >= 4096 && sectionhighbits > sectionsize / 4) break; } /* return to the original offset for processing */ /* XXX use relative seeks to handle >31 bit file sizes? */ if (sm_io_seek(e->e_dfp, SM_TIME_DEFAULT, offset, SEEK_SET) < 0) syserr("mime8to7: cannot sm_io_fseek on %cf%s", DATAFL_LETTER, e->e_id); else sm_io_clearerr(e->e_dfp); } /* ** Heuristically determine encoding method. ** If more than 1/8 of the total characters have the ** eighth bit set, use base64; else use quoted-printable. ** However, only encode binary encoded data as base64, ** since otherwise the NL=>CRLF mapping will be a problem. */ if (tTd(43, 8)) { sm_dprintf("mime8to7: %ld high bit(s) in %ld byte(s), cte=%s, type=%s/%s\n", (long) sectionhighbits, (long) sectionsize, cte == NULL ? "[none]" : cte, type == NULL ? "[none]" : type, subtype == NULL ? "[none]" : subtype); } if (cte != NULL && sm_strcasecmp(cte, "binary") == 0) sectionsize = sectionhighbits; linelen = 0; bp = buf; if (sectionhighbits == 0) { /* no encoding necessary */ if (cte != NULL && bitset(MCIF_CVT8TO7|MCIF_CVT7TO8|MCIF_INMIME, mci->mci_flags) && !bitset(M87F_NO8TO7, flags)) { /* ** Skip _unless_ in MIME mode and potentially ** converting from 8 bit to 7 bit MIME. See ** putheader() for the counterpart where the ** CTE header is skipped in the opposite ** situation. */ (void) sm_snprintf(buf, sizeof(buf), "Content-Transfer-Encoding: %.200s", cte); if (!putline(buf, mci)) goto writeerr; if (tTd(43, 36)) sm_dprintf(" ...%s\n", buf); } if (!putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; - while (sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, sizeof(buf)) - != NULL) + while ((blen = sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, + sizeof(buf))) >= 0) { if (!bitset(MCIF_INLONGLINE, mci->mci_flags)) { bt = mimeboundary(buf, boundaries); if (bt != MBT_NOTSEP) break; } - if (!putxline(buf, strlen(buf), mci, + if (!putxline(buf, blen, mci, PXLF_MAPFROM|PXLF_NOADDEOL)) goto writeerr; } if (sm_io_eof(e->e_dfp)) bt = MBT_FINAL; } else if (!MapNLtoCRLF || (sectionsize / 8 < sectionhighbits && !use_qp)) { /* use base64 encoding */ int c1, c2; if (tTd(43, 36)) sm_dprintf(" ...Content-Transfer-Encoding: base64\n"); if (!putline("Content-Transfer-Encoding: base64", mci)) goto writeerr; (void) sm_snprintf(buf, sizeof(buf), "X-MIME-Autoconverted: from 8bit to base64 by %s id %s", MyHostName, e->e_id); if (!putline(buf, mci) || !putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; while ((c1 = mime_getchar_crlf(e->e_dfp, boundaries, &bt)) != SM_IO_EOF) { if (linelen > 71) { *bp = '\0'; if (!putline(buf, mci)) goto writeerr; linelen = 0; bp = buf; } linelen += 4; *bp++ = Base64Code[(c1 >> 2)]; c1 = (c1 & 0x03) << 4; c2 = mime_getchar_crlf(e->e_dfp, boundaries, &bt); if (c2 == SM_IO_EOF) { *bp++ = Base64Code[c1]; *bp++ = '='; *bp++ = '='; break; } c1 |= (c2 >> 4) & 0x0f; *bp++ = Base64Code[c1]; c1 = (c2 & 0x0f) << 2; c2 = mime_getchar_crlf(e->e_dfp, boundaries, &bt); if (c2 == SM_IO_EOF) { *bp++ = Base64Code[c1]; *bp++ = '='; break; } c1 |= (c2 >> 6) & 0x03; *bp++ = Base64Code[c1]; *bp++ = Base64Code[c2 & 0x3f]; } *bp = '\0'; if (!putline(buf, mci)) goto writeerr; } else { /* use quoted-printable encoding */ int c1, c2; int fromstate; BITMAP256 badchars; /* set up map of characters that must be mapped */ clrbitmap(badchars); for (c1 = 0x00; c1 < 0x20; c1++) setbitn(c1, badchars); clrbitn('\t', badchars); for (c1 = 0x7f; c1 < 0x100; c1++) setbitn(c1, badchars); setbitn('=', badchars); if (bitnset(M_EBCDIC, mci->mci_mailer->m_flags)) for (p = "!\"#$@[\\]^`{|}~"; *p != '\0'; p++) setbitn(*p, badchars); if (tTd(43, 36)) sm_dprintf(" ...Content-Transfer-Encoding: quoted-printable\n"); if (!putline("Content-Transfer-Encoding: quoted-printable", mci)) goto writeerr; (void) sm_snprintf(buf, sizeof(buf), "X-MIME-Autoconverted: from 8bit to quoted-printable by %s id %s", MyHostName, e->e_id); if (!putline(buf, mci) || !putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; fromstate = 0; c2 = '\n'; while ((c1 = mime_getchar(e->e_dfp, boundaries, &bt)) != SM_IO_EOF) { if (c1 == '\n') { if (c2 == ' ' || c2 == '\t') { *bp++ = '='; *bp++ = Base16Code[(c2 >> 4) & 0x0f]; *bp++ = Base16Code[c2 & 0x0f]; } if (buf[0] == '.' && bp == &buf[1]) { buf[0] = '='; *bp++ = Base16Code[('.' >> 4) & 0x0f]; *bp++ = Base16Code['.' & 0x0f]; } *bp = '\0'; if (!putline(buf, mci)) goto writeerr; linelen = fromstate = 0; bp = buf; c2 = c1; continue; } if (c2 == ' ' && linelen == 4 && fromstate == 4 && bitnset(M_ESCFROM, mci->mci_mailer->m_flags)) { *bp++ = '='; *bp++ = '2'; *bp++ = '0'; linelen += 3; } else if (c2 == ' ' || c2 == '\t') { *bp++ = c2; linelen++; } if (linelen > 72 && (linelen > 75 || c1 != '.' || (linelen > 73 && c2 == '.'))) { if (linelen > 73 && c2 == '.') bp--; else c2 = '\n'; *bp++ = '='; *bp = '\0'; if (!putline(buf, mci)) goto writeerr; linelen = fromstate = 0; bp = buf; if (c2 == '.') { *bp++ = '.'; linelen++; } } if (bitnset(bitidx(c1), badchars)) { *bp++ = '='; *bp++ = Base16Code[(c1 >> 4) & 0x0f]; *bp++ = Base16Code[c1 & 0x0f]; linelen += 3; } else if (c1 != ' ' && c1 != '\t') { if (linelen < 4 && c1 == "From"[linelen]) fromstate++; *bp++ = c1; linelen++; } c2 = c1; } /* output any saved character */ if (c2 == ' ' || c2 == '\t') { *bp++ = '='; *bp++ = Base16Code[(c2 >> 4) & 0x0f]; *bp++ = Base16Code[c2 & 0x0f]; linelen += 3; } if (linelen > 0 || boundaries[0] != NULL) { *bp = '\0'; if (!putline(buf, mci)) goto writeerr; } } if (tTd(43, 3)) sm_dprintf("\t\t\tmime8to7=>%s (basic)\n", MimeBoundaryNames[bt]); return bt; writeerr: return SM_IO_EOF; } /* ** MIME_GETCHAR -- get a character for MIME processing ** ** Treats boundaries as SM_IO_EOF. ** ** Parameters: ** fp -- the input file. ** boundaries -- the current MIME boundaries. ** btp -- if the return value is SM_IO_EOF, *btp is set to ** the type of the boundary. ** ** Returns: ** The next character in the input stream. */ static int mime_getchar(fp, boundaries, btp) register SM_FILE_T *fp; char **boundaries; int *btp; { int c; static unsigned char *bp = NULL; static int buflen = 0; static bool atbol = true; /* at beginning of line */ static int bt = MBT_SYNTAX; /* boundary type of next SM_IO_EOF */ static unsigned char buf[128]; /* need not be a full line */ int start = 0; /* indicates position of - in buffer */ if (buflen == 1 && *bp == '\n') { /* last \n in buffer may be part of next MIME boundary */ c = *bp; } else if (buflen > 0) { buflen--; return *bp++; } else c = sm_io_getc(fp, SM_TIME_DEFAULT); bp = buf; buflen = 0; if (c == '\n') { /* might be part of a MIME boundary */ *bp++ = c; atbol = true; c = sm_io_getc(fp, SM_TIME_DEFAULT); if (c == '\n') { (void) sm_io_ungetc(fp, SM_TIME_DEFAULT, c); return c; } start = 1; } if (c != SM_IO_EOF) *bp++ = c; else bt = MBT_FINAL; if (atbol && c == '-') { /* check for a message boundary */ c = sm_io_getc(fp, SM_TIME_DEFAULT); if (c != '-') { if (c != SM_IO_EOF) *bp++ = c; else bt = MBT_FINAL; buflen = bp - buf - 1; bp = buf; return *bp++; } /* got "--", now check for rest of separator */ *bp++ = '-'; while (bp < &buf[sizeof(buf) - 2] && (c = sm_io_getc(fp, SM_TIME_DEFAULT)) != SM_IO_EOF && c != '\n') { *bp++ = c; } *bp = '\0'; /* XXX simply cut off? */ bt = mimeboundary((char *) &buf[start], boundaries); switch (bt) { case MBT_FINAL: case MBT_INTERMED: /* we have a message boundary */ buflen = 0; *btp = bt; return SM_IO_EOF; } if (bp < &buf[sizeof(buf) - 2] && c != SM_IO_EOF) *bp++ = c; } atbol = c == '\n'; buflen = bp - buf - 1; if (buflen < 0) { *btp = bt; return SM_IO_EOF; } bp = buf; return *bp++; } /* ** MIME_GETCHAR_CRLF -- do mime_getchar, but translate NL => CRLF ** ** Parameters: ** fp -- the input file. ** boundaries -- the current MIME boundaries. ** btp -- if the return value is SM_IO_EOF, *btp is set to ** the type of the boundary. ** ** Returns: ** The next character in the input stream. */ static int mime_getchar_crlf(fp, boundaries, btp) register SM_FILE_T *fp; char **boundaries; int *btp; { static bool sendlf = false; int c; if (sendlf) { sendlf = false; return '\n'; } c = mime_getchar(fp, boundaries, btp); if (c == '\n' && MapNLtoCRLF) { sendlf = true; return '\r'; } return c; } /* ** MIMEBOUNDARY -- determine if this line is a MIME boundary & its type ** ** Parameters: ** line -- the input line. ** boundaries -- the set of currently pending boundaries. ** ** Returns: ** MBT_NOTSEP -- if this is not a separator line ** MBT_INTERMED -- if this is an intermediate separator ** MBT_FINAL -- if this is a final boundary ** MBT_SYNTAX -- if this is a boundary for the wrong ** enclosure -- i.e., a syntax error. */ static int mimeboundary(line, boundaries) register char *line; char **boundaries; { int type = MBT_NOTSEP; int i; int savec; if (line[0] != '-' || line[1] != '-' || boundaries == NULL) return MBT_NOTSEP; i = strlen(line); if (i > 0 && line[i - 1] == '\n') i--; /* strip off trailing whitespace */ while (i > 0 && (line[i - 1] == ' ' || line[i - 1] == '\t' #if _FFR_MIME_CR_OK || line[i - 1] == '\r' #endif /* _FFR_MIME_CR_OK */ )) i--; savec = line[i]; line[i] = '\0'; if (tTd(43, 5)) sm_dprintf("mimeboundary: line=\"%s\"... ", line); /* check for this as an intermediate boundary */ if (isboundary(&line[2], boundaries) >= 0) type = MBT_INTERMED; else if (i > 2 && strncmp(&line[i - 2], "--", 2) == 0) { /* check for a final boundary */ line[i - 2] = '\0'; if (isboundary(&line[2], boundaries) >= 0) type = MBT_FINAL; line[i - 2] = '-'; } line[i] = savec; if (tTd(43, 5)) sm_dprintf("%s\n", MimeBoundaryNames[type]); return type; } /* ** DEFCHARSET -- return default character set for message ** ** The first choice for character set is for the mailer ** corresponding to the envelope sender. If neither that ** nor the global configuration file has a default character ** set defined, return "unknown-8bit" as recommended by ** RFC 1428 section 3. ** ** Parameters: ** e -- the envelope for this message. ** ** Returns: ** The default character set for that mailer. */ char * defcharset(e) register ENVELOPE *e; { if (e != NULL && e->e_from.q_mailer != NULL && e->e_from.q_mailer->m_defcharset != NULL) return e->e_from.q_mailer->m_defcharset; if (DefaultCharSet != NULL) return DefaultCharSet; return "unknown-8bit"; } /* ** ISBOUNDARY -- is a given string a currently valid boundary? ** ** Parameters: ** line -- the current input line. ** boundaries -- the list of valid boundaries. ** ** Returns: ** The index number in boundaries if the line is found. ** -1 -- otherwise. ** */ static int isboundary(line, boundaries) char *line; char **boundaries; { register int i; for (i = 0; i <= MAXMIMENESTING && boundaries[i] != NULL; i++) { if (strcmp(line, boundaries[i]) == 0) return i; } return -1; } #endif /* MIME8TO7 */ #if MIME7TO8 static int mime_fromqp __P((unsigned char *, unsigned char **, int)); /* ** MIME7TO8 -- output 7 bit encoded MIME body in 8 bit format ** ** This is a hack. Supports translating the two 7-bit body-encodings ** (quoted-printable and base64) to 8-bit coded bodies. ** ** There is not much point in supporting multipart here, as the UA ** will be able to deal with encoded MIME bodies if it can parse MIME ** multipart messages. ** ** Note also that we won't be called unless it is a text/plain MIME ** message, encoded base64 or QP and mailer flag '9' has been defined ** on mailer. ** ** Contributed by Marius Olaffson . ** ** Parameters: ** mci -- mailer connection information. ** header -- the header for this body part. ** e -- envelope. ** ** Returns: ** true iff body was written successfully */ static char index_64[128] = { -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 }; # define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) bool mime7to8(mci, header, e) register MCI *mci; HDR *header; register ENVELOPE *e; { - int pxflags; + int pxflags, blen; register char *p; char *cte; char **pvp; unsigned char *fbufp; char buf[MAXLINE]; unsigned char fbuf[MAXLINE + 1]; char pvpbuf[MAXLINE]; extern unsigned char MimeTokenTab[256]; p = hvalue("Content-Transfer-Encoding", header); if (p == NULL || (pvp = prescan(p, '\0', pvpbuf, sizeof(pvpbuf), NULL, MimeTokenTab, false)) == NULL || pvp[0] == NULL) { /* "can't happen" -- upper level should have caught this */ syserr("mime7to8: unparsable CTE %s", p == NULL ? "" : p); /* avoid bounce loops */ e->e_flags |= EF_DONT_MIME; /* cheap failsafe algorithm -- should work on text/plain */ if (p != NULL) { (void) sm_snprintf(buf, sizeof(buf), "Content-Transfer-Encoding: %s", p); if (!putline(buf, mci)) goto writeerr; } if (!putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; - while (sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, sizeof(buf)) - != NULL) + while ((blen = sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, + sizeof(buf))) >= 0) { - if (!putline(buf, mci)) + if (!putxline(buf, blen, mci, PXLF_MAPFROM)) goto writeerr; } return true; } cataddr(pvp, NULL, buf, sizeof(buf), '\0', false); cte = sm_rpool_strdup_x(e->e_rpool, buf); mci->mci_flags |= MCIF_INHEADER; if (!putline("Content-Transfer-Encoding: 8bit", mci)) goto writeerr; (void) sm_snprintf(buf, sizeof(buf), "X-MIME-Autoconverted: from %.200s to 8bit by %s id %s", cte, MyHostName, e->e_id); if (!putline(buf, mci) || !putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; /* ** Translate body encoding to 8-bit. Supports two types of ** encodings; "base64" and "quoted-printable". Assume qp if ** it is not base64. */ pxflags = PXLF_MAPFROM; if (sm_strcasecmp(cte, "base64") == 0) { int c1, c2, c3, c4; fbufp = fbuf; while ((c1 = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT)) != SM_IO_EOF) { if (isascii(c1) && isspace(c1)) continue; do { c2 = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT); } while (isascii(c2) && isspace(c2)); if (c2 == SM_IO_EOF) break; do { c3 = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT); } while (isascii(c3) && isspace(c3)); if (c3 == SM_IO_EOF) break; do { c4 = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT); } while (isascii(c4) && isspace(c4)); if (c4 == SM_IO_EOF) break; if (c1 == '=' || c2 == '=') continue; c1 = CHAR64(c1); c2 = CHAR64(c2); #if MIME7TO8_OLD #define CHK_EOL if (*--fbufp != '\n' || (fbufp > fbuf && *--fbufp != '\r')) \ ++fbufp; #else /* MIME7TO8_OLD */ #define CHK_EOL if (*--fbufp != '\n' || (fbufp > fbuf && *--fbufp != '\r')) \ { \ ++fbufp; \ pxflags |= PXLF_NOADDEOL; \ } #endif /* MIME7TO8_OLD */ #define PUTLINE64 \ do \ { \ if (*fbufp++ == '\n' || fbufp >= &fbuf[MAXLINE]) \ { \ CHK_EOL; \ if (!putxline((char *) fbuf, fbufp - fbuf, mci, pxflags)) \ goto writeerr; \ pxflags &= ~PXLF_NOADDEOL; \ fbufp = fbuf; \ } \ } while (0) *fbufp = (c1 << 2) | ((c2 & 0x30) >> 4); PUTLINE64; if (c3 == '=') continue; c3 = CHAR64(c3); *fbufp = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2); PUTLINE64; if (c4 == '=') continue; c4 = CHAR64(c4); *fbufp = ((c3 & 0x03) << 6) | c4; PUTLINE64; } } else { int off; /* quoted-printable */ pxflags |= PXLF_NOADDEOL; fbufp = fbuf; while (sm_io_fgets(e->e_dfp, SM_TIME_DEFAULT, buf, - sizeof(buf)) != NULL) + sizeof(buf)) >= 0) { off = mime_fromqp((unsigned char *) buf, &fbufp, &fbuf[MAXLINE] - fbufp); again: if (off < -1) continue; if (fbufp - fbuf > 0) { if (!putxline((char *) fbuf, fbufp - fbuf - 1, mci, pxflags)) goto writeerr; } fbufp = fbuf; if (off >= 0 && buf[off] != '\0') { off = mime_fromqp((unsigned char *) (buf + off), &fbufp, &fbuf[MAXLINE] - fbufp); goto again; } } } /* force out partial last line */ if (fbufp > fbuf) { *fbufp = '\0'; if (!putxline((char *) fbuf, fbufp - fbuf, mci, pxflags)) goto writeerr; } /* ** The decoded text may end without an EOL. Since this function ** is only called for text/plain MIME messages, it is safe to ** add an extra one at the end just in case. This is a hack, ** but so is auto-converting MIME in the first place. */ if (!putline("", mci)) goto writeerr; if (tTd(43, 3)) sm_dprintf("\t\t\tmime7to8 => %s to 8bit done\n", cte); return true; writeerr: return false; } /* ** The following is based on Borenstein's "codes.c" module, with simplifying ** changes as we do not deal with multipart, and to do the translation in-core, ** with an attempt to prevent overrun of output buffers. ** ** What is needed here are changes to defend this code better against ** bad encodings. Questionable to always return 0xFF for bad mappings. */ static char index_hex[128] = { -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1, -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1 }; # define HEXCHAR(c) (((c) < 0 || (c) > 127) ? -1 : index_hex[(c)]) /* ** MIME_FROMQP -- decode quoted printable string ** ** Parameters: ** infile -- input (encoded) string ** outfile -- output string ** maxlen -- size of output buffer ** ** Returns: ** -2 if decoding failure ** -1 if infile completely decoded into outfile ** >= 0 is the position in infile decoding ** reached before maxlen was reached */ static int mime_fromqp(infile, outfile, maxlen) unsigned char *infile; unsigned char **outfile; int maxlen; /* Max # of chars allowed in outfile */ { int c1, c2; int nchar = 0; unsigned char *b; /* decrement by one for trailing '\0', at least one other char */ if (--maxlen < 1) return 0; b = infile; while ((c1 = *infile++) != '\0' && nchar < maxlen) { if (c1 == '=') { if ((c1 = *infile++) == '\0') break; if (c1 == '\n' || (c1 = HEXCHAR(c1)) == -1) { /* ignore it and the rest of the buffer */ return -2; } else { do { if ((c2 = *infile++) == '\0') { c2 = -1; break; } } while ((c2 = HEXCHAR(c2)) == -1); if (c2 == -1) break; nchar++; *(*outfile)++ = c1 << 4 | c2; } } else { nchar++; *(*outfile)++ = c1; if (c1 == '\n') break; } } *(*outfile)++ = '\0'; if (nchar >= maxlen) return (infile - b - 1); return -1; } #endif /* MIME7TO8 */ Index: head/contrib/sendmail/src/parseaddr.c =================================================================== --- head/contrib/sendmail/src/parseaddr.c (revision 249728) +++ head/contrib/sendmail/src/parseaddr.c (revision 249729) @@ -1,3364 +1,3372 @@ /* * Copyright (c) 1998-2006 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: parseaddr.c,v 8.405 2012/02/27 22:49:08 ca Exp $") +SM_RCSID("@(#)$Id: parseaddr.c,v 8.406 2013/04/17 16:53:01 ca Exp $") #include #include "map.h" static void allocaddr __P((ADDRESS *, int, char *, ENVELOPE *)); static int callsubr __P((char**, int, ENVELOPE *)); static char *map_lookup __P((STAB *, char *, char **, int *, ENVELOPE *)); static ADDRESS *buildaddr __P((char **, ADDRESS *, int, ENVELOPE *)); static bool hasctrlchar __P((register char *, bool, bool)); /* replacement for illegal characters in addresses */ #define BAD_CHAR_REPLACEMENT '?' /* ** PARSEADDR -- Parse an address ** ** Parses an address and breaks it up into three parts: a ** net to transmit the message on, the host to transmit it ** to, and a user on that host. These are loaded into an ** ADDRESS header with the values squirreled away if necessary. ** The "user" part may not be a real user; the process may ** just reoccur on that machine. For example, on a machine ** with an arpanet connection, the address ** csvax.bill@berkeley ** will break up to a "user" of 'csvax.bill' and a host ** of 'berkeley' -- to be transmitted over the arpanet. ** ** Parameters: ** addr -- the address to parse. ** a -- a pointer to the address descriptor buffer. ** If NULL, an address will be created. ** flags -- describe detail for parsing. See RF_ definitions ** in sendmail.h. ** delim -- the character to terminate the address, passed ** to prescan. ** delimptr -- if non-NULL, set to the location of the ** delim character that was found. ** e -- the envelope that will contain this address. ** isrcpt -- true if the address denotes a recipient; false ** indicates a sender. ** ** Returns: ** A pointer to the address descriptor header (`a' if ** `a' is non-NULL). ** NULL on error. ** ** Side Effects: ** e->e_to = addr */ /* following delimiters are inherent to the internal algorithms */ #define DELIMCHARS "()<>,;\r\n" /* default word delimiters */ ADDRESS * parseaddr(addr, a, flags, delim, delimptr, e, isrcpt) char *addr; register ADDRESS *a; int flags; int delim; char **delimptr; register ENVELOPE *e; bool isrcpt; { char **pvp; auto char *delimptrbuf; bool qup; char pvpbuf[PSBUFSIZE]; /* ** Initialize and prescan address. */ e->e_to = addr; if (tTd(20, 1)) sm_dprintf("\n--parseaddr(%s)\n", addr); if (delimptr == NULL) delimptr = &delimptrbuf; pvp = prescan(addr, delim, pvpbuf, sizeof(pvpbuf), delimptr, ExtTokenTab, false); if (pvp == NULL) { if (tTd(20, 1)) sm_dprintf("parseaddr-->NULL\n"); return NULL; } if (invalidaddr(addr, delim == '\0' ? NULL : *delimptr, isrcpt)) { if (tTd(20, 1)) sm_dprintf("parseaddr-->bad address\n"); return NULL; } /* ** Save addr if we are going to have to. ** ** We have to do this early because there is a chance that ** the map lookups in the rewriting rules could clobber ** static memory somewhere. */ if (bitset(RF_COPYPADDR, flags) && addr != NULL) { char savec = **delimptr; if (savec != '\0') **delimptr = '\0'; e->e_to = addr = sm_rpool_strdup_x(e->e_rpool, addr); if (savec != '\0') **delimptr = savec; } /* ** Apply rewriting rules. ** Ruleset 0 does basic parsing. It must resolve. */ qup = false; if (REWRITE(pvp, 3, e) == EX_TEMPFAIL) qup = true; if (REWRITE(pvp, 0, e) == EX_TEMPFAIL) qup = true; /* ** Build canonical address from pvp. */ a = buildaddr(pvp, a, flags, e); if (hasctrlchar(a->q_user, isrcpt, true)) { if (tTd(20, 1)) sm_dprintf("parseaddr-->bad q_user\n"); /* ** Just mark the address as bad so DSNs work. ** hasctrlchar() has to make sure that the address ** has been sanitized, e.g., shortened. */ a->q_state = QS_BADADDR; } /* ** Make local copies of the host & user and then ** transport them out. */ allocaddr(a, flags, addr, e); if (QS_IS_BADADDR(a->q_state)) { /* weed out bad characters in the printable address too */ (void) hasctrlchar(a->q_paddr, isrcpt, false); return a; } /* ** Select a queue directory for recipient addresses. ** This is done here and in split_across_queue_groups(), ** but the latter applies to addresses after aliasing, ** and only if splitting is done. */ if ((a->q_qgrp == NOAQGRP || a->q_qgrp == ENVQGRP) && !bitset(RF_SENDERADDR|RF_HEADERADDR|RF_RM_ADDR, flags) && OpMode != MD_INITALIAS) { int r; /* call ruleset which should return a queue group name */ r = rscap(RS_QUEUEGROUP, a->q_user, NULL, e, &pvp, pvpbuf, sizeof(pvpbuf)); if (r == EX_OK && pvp != NULL && pvp[0] != NULL && (pvp[0][0] & 0377) == CANONNET && pvp[1] != NULL && pvp[1][0] != '\0') { r = name2qid(pvp[1]); if (r == NOQGRP && LogLevel > 10) sm_syslog(LOG_INFO, NOQID, "can't find queue group name %s, selection ignored", pvp[1]); if (tTd(20, 4) && r != NOQGRP) sm_syslog(LOG_INFO, NOQID, "queue group name %s -> %d", pvp[1], r); a->q_qgrp = r == NOQGRP ? ENVQGRP : r; } } /* ** If there was a parsing failure, mark it for queueing. */ if (qup && OpMode != MD_INITALIAS) { char *msg = "Transient parse error -- message queued for future delivery"; if (e->e_sendmode == SM_DEFER) msg = "Deferring message until queue run"; if (tTd(20, 1)) sm_dprintf("parseaddr: queueing message\n"); message(msg); if (e->e_message == NULL && e->e_sendmode != SM_DEFER) e->e_message = sm_rpool_strdup_x(e->e_rpool, msg); a->q_state = QS_QUEUEUP; a->q_status = "4.4.3"; } /* ** Compute return value. */ if (tTd(20, 1)) { sm_dprintf("parseaddr-->"); printaddr(sm_debug_file(), a, false); } return a; } /* ** INVALIDADDR -- check for address containing characters used for macros ** ** Parameters: ** addr -- the address to check. ** note: this is the complete address (including display part) ** delimptr -- if non-NULL: end of address to check, i.e., ** a pointer in the address string. ** isrcpt -- true iff the address is for a recipient. ** ** Returns: ** true -- if the address has characters that are reservered ** for macros or is too long. ** false -- otherwise. */ bool invalidaddr(addr, delimptr, isrcpt) register char *addr; char *delimptr; bool isrcpt; { bool result = false; char savedelim = '\0'; char *b = addr; int len = 0; if (delimptr != NULL) { /* delimptr points to the end of the address to test */ savedelim = *delimptr; if (savedelim != '\0') /* if that isn't '\0' already: */ *delimptr = '\0'; /* set it */ } for (; *addr != '\0'; addr++) { if (!EightBitAddrOK && (*addr & 0340) == 0200) { setstat(EX_USAGE); result = true; *addr = BAD_CHAR_REPLACEMENT; } if (++len > MAXNAME - 1) { char saved = *addr; *addr = '\0'; usrerr("553 5.1.0 Address \"%s\" too long (%d bytes max)", b, MAXNAME - 1); *addr = saved; result = true; goto delim; } } if (result) { if (isrcpt) usrerr("501 5.1.3 8-bit character in mailbox address \"%s\"", b); else usrerr("501 5.1.7 8-bit character in mailbox address \"%s\"", b); } delim: if (delimptr != NULL && savedelim != '\0') *delimptr = savedelim; /* restore old character at delimptr */ return result; } /* ** HASCTRLCHAR -- check for address containing meta-characters ** ** Checks that the address contains no meta-characters, and contains ** no "non-printable" characters unless they are quoted or escaped. ** Quoted or escaped characters are literals. ** ** Parameters: ** addr -- the address to check. ** isrcpt -- true if the address is for a recipient; false ** indicates a from. ** complain -- true if an error should issued if the address ** is invalid and should be "repaired". ** ** Returns: ** true -- if the address has any "weird" characters or ** non-printable characters or if a quote is unbalanced. ** false -- otherwise. */ static bool hasctrlchar(addr, isrcpt, complain) register char *addr; bool isrcpt, complain; { bool quoted = false; int len = 0; char *result = NULL; char *b = addr; if (addr == NULL) return false; for (; *addr != '\0'; addr++) { if (++len > MAXNAME - 1) { if (complain) { (void) shorten_rfc822_string(b, MAXNAME - 1); usrerr("553 5.1.0 Address \"%s\" too long (%d bytes max)", b, MAXNAME - 1); return true; } result = "too long"; } if (!EightBitAddrOK && !quoted && (*addr < 32 || *addr == 127)) { result = "non-printable character"; *addr = BAD_CHAR_REPLACEMENT; continue; } if (*addr == '"') quoted = !quoted; else if (*addr == '\\') { /* XXX Generic problem: no '\0' in strings. */ if (*++addr == '\0') { result = "trailing \\ character"; *--addr = BAD_CHAR_REPLACEMENT; break; } } if (!EightBitAddrOK && (*addr & 0340) == 0200) { setstat(EX_USAGE); result = "8-bit character"; *addr = BAD_CHAR_REPLACEMENT; continue; } } if (quoted) result = "unbalanced quote"; /* unbalanced quote */ if (result != NULL && complain) { if (isrcpt) usrerr("501 5.1.3 Syntax error in mailbox address \"%s\" (%s)", b, result); else usrerr("501 5.1.7 Syntax error in mailbox address \"%s\" (%s)", b, result); } return result != NULL; } /* ** ALLOCADDR -- do local allocations of address on demand. ** ** Also lowercases the host name if requested. ** ** Parameters: ** a -- the address to reallocate. ** flags -- the copy flag (see RF_ definitions in sendmail.h ** for a description). ** paddr -- the printname of the address. ** e -- envelope ** ** Returns: ** none. ** ** Side Effects: ** Copies portions of a into local buffers as requested. */ static void allocaddr(a, flags, paddr, e) register ADDRESS *a; int flags; char *paddr; ENVELOPE *e; { if (tTd(24, 4)) sm_dprintf("allocaddr(flags=%x, paddr=%s)\n", flags, paddr); a->q_paddr = paddr; if (a->q_user == NULL) a->q_user = ""; if (a->q_host == NULL) a->q_host = ""; if (bitset(RF_COPYPARSE, flags)) { a->q_host = sm_rpool_strdup_x(e->e_rpool, a->q_host); if (a->q_user != a->q_paddr) a->q_user = sm_rpool_strdup_x(e->e_rpool, a->q_user); } if (a->q_paddr == NULL) a->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_user); a->q_qgrp = NOAQGRP; } /* ** PRESCAN -- Prescan name and make it canonical ** ** Scans a name and turns it into a set of tokens. This process ** deletes blanks and comments (in parentheses) (if the token type ** for left paren is SPC). ** ** This routine knows about quoted strings and angle brackets. ** ** There are certain subtleties to this routine. The one that ** comes to mind now is that backslashes on the ends of names ** are silently stripped off; this is intentional. The problem ** is that some versions of sndmsg (like at LBL) set the kill ** character to something other than @ when reading addresses; ** so people type "csvax.eric\@berkeley" -- which screws up the ** berknet mailer. ** ** Parameters: ** addr -- the name to chomp. ** delim -- the delimiter for the address, normally ** '\0' or ','; \0 is accepted in any case. ** If '\t' then we are reading the .cf file. ** pvpbuf -- place to put the saved text -- note that ** the pointers are static. ** pvpbsize -- size of pvpbuf. ** delimptr -- if non-NULL, set to the location of the ** terminating delimiter. ** toktab -- if set, a token table to use for parsing. ** If NULL, use the default table. ** ignore -- if true, ignore unbalanced addresses ** ** Returns: ** A pointer to a vector of tokens. ** NULL on error. */ /* states and character types */ #define OPR 0 /* operator */ #define ATM 1 /* atom */ #define QST 2 /* in quoted string */ #define SPC 3 /* chewing up spaces */ #define ONE 4 /* pick up one character */ #define ILL 5 /* illegal character */ #define NSTATES 6 /* number of states */ #define TYPE 017 /* mask to select state type */ /* meta bits for table */ #define M 020 /* meta character; don't pass through */ #define B 040 /* cause a break */ #define MB M|B /* meta-break */ static short StateTab[NSTATES][NSTATES] = { /* oldst chtype> OPR ATM QST SPC ONE ILL */ /*OPR*/ { OPR|B, ATM|B, QST|B, SPC|MB, ONE|B, ILL|MB }, /*ATM*/ { OPR|B, ATM, QST|B, SPC|MB, ONE|B, ILL|MB }, /*QST*/ { QST, QST, OPR, QST, QST, QST }, /*SPC*/ { OPR, ATM, QST, SPC|M, ONE, ILL|MB }, /*ONE*/ { OPR, OPR, OPR, OPR, OPR, ILL|MB }, /*ILL*/ { OPR|B, ATM|B, QST|B, SPC|MB, ONE|B, ILL|M } }; /* these all get modified with the OperatorChars */ /* token type table for external strings */ unsigned char ExtTokenTab[256] = { /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* sp ! " # $ % & ' ( ) * + , - . / */ SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, SPC,SPC,ATM,ATM,ATM,ATM,ATM,ATM, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* @ A B C D E F G H I J K L M N O */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* ` a b c d e f g h i j k l m n o */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* p q r s t u v w x y z { | } ~ del */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* sp ! " # $ % & ' ( ) * + , - . / */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* @ A B C D E F G H I J K L M N O */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* ` a b c d e f g h i j k l m n o */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* p q r s t u v w x y z { | } ~ del */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM }; /* token type table for internal strings */ unsigned char IntTokenTab[256] = { /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* sp ! " # $ % & ' ( ) * + , - . / */ SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, SPC,SPC,ATM,ATM,ATM,ATM,ATM,ATM, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* @ A B C D E F G H I J K L M N O */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* ` a b c d e f g h i j k l m n o */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* p q r s t u v w x y z { | } ~ del */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ OPR,OPR,ONE,OPR,OPR,OPR,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ OPR,OPR,OPR,ONE,ONE,ONE,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR, /* sp ! " # $ % & ' ( ) * + , - . / */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* @ A B C D E F G H I J K L M N O */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* ` a b c d e f g h i j k l m n o */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* p q r s t u v w x y z { | } ~ del */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ONE }; /* token type table for MIME parsing */ unsigned char MimeTokenTab[256] = { /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,SPC,SPC,SPC,SPC,SPC,ILL,ILL, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* sp ! " # $ % & ' ( ) * + , - . / */ SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, SPC,SPC,ATM,ATM,OPR,ATM,ATM,OPR, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,OPR,OPR,OPR,OPR,OPR,OPR, /* @ A B C D E F G H I J K L M N O */ OPR,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,OPR,OPR,OPR,ATM,ATM, /* ` a b c d e f g h i j k l m n o */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* p q r s t u v w x y z { | } ~ del */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* sp ! " # $ % & ' ( ) * + , - . / */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* @ A B C D E F G H I J K L M N O */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* ` a b c d e f g h i j k l m n o */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* p q r s t u v w x y z { | } ~ del */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ONE }; /* token type table: don't strip comments */ unsigned char TokTypeNoC[256] = { /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* sp ! " # $ % & ' ( ) * + , - . / */ SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, OPR,OPR,ATM,ATM,ATM,ATM,ATM,ATM, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* @ A B C D E F G H I J K L M N O */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* ` a b c d e f g h i j k l m n o */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* p q r s t u v w x y z { | } ~ del */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ OPR,OPR,ONE,OPR,OPR,OPR,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ OPR,OPR,OPR,ONE,ONE,ONE,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR, /* sp ! " # $ % & ' ( ) * + , - . / */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* @ A B C D E F G H I J K L M N O */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* ` a b c d e f g h i j k l m n o */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, /* p q r s t u v w x y z { | } ~ del */ ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ONE }; #define NOCHAR (-1) /* signal nothing in lookahead token */ char ** prescan(addr, delim, pvpbuf, pvpbsize, delimptr, toktab, ignore) char *addr; int delim; char pvpbuf[]; int pvpbsize; char **delimptr; unsigned char *toktab; bool ignore; { register char *p; register char *q; register int c; char **avp; bool bslashmode; bool route_syntax; int cmntcnt; int anglecnt; char *tok; int state; int newstate; char *saveto = CurEnv->e_to; static char *av[MAXATOM + 1]; static bool firsttime = true; if (firsttime) { /* initialize the token type table */ char obuf[50]; firsttime = false; if (OperatorChars == NULL) { if (ConfigLevel < 7) OperatorChars = macvalue('o', CurEnv); if (OperatorChars == NULL) OperatorChars = ".:@[]"; } expand(OperatorChars, obuf, sizeof(obuf) - sizeof(DELIMCHARS), CurEnv); (void) sm_strlcat(obuf, DELIMCHARS, sizeof(obuf)); for (p = obuf; *p != '\0'; p++) { if (IntTokenTab[*p & 0xff] == ATM) IntTokenTab[*p & 0xff] = OPR; if (ExtTokenTab[*p & 0xff] == ATM) ExtTokenTab[*p & 0xff] = OPR; if (TokTypeNoC[*p & 0xff] == ATM) TokTypeNoC[*p & 0xff] = OPR; } } if (toktab == NULL) toktab = ExtTokenTab; /* make sure error messages don't have garbage on them */ errno = 0; q = pvpbuf; bslashmode = false; route_syntax = false; cmntcnt = 0; anglecnt = 0; avp = av; state = ATM; c = NOCHAR; p = addr; CurEnv->e_to = p; if (tTd(22, 11)) { sm_dprintf("prescan: "); xputs(sm_debug_file(), p); sm_dprintf("\n"); } do { /* read a token */ tok = q; for (;;) { /* store away any old lookahead character */ if (c != NOCHAR && !bslashmode) { /* see if there is room */ if (q >= &pvpbuf[pvpbsize - 5]) { addrtoolong: usrerr("553 5.1.1 Address too long"); if (strlen(addr) > MAXNAME) addr[MAXNAME] = '\0'; returnnull: if (delimptr != NULL) { if (p > addr) --p; *delimptr = p; } CurEnv->e_to = saveto; return NULL; } /* squirrel it away */ #if !ALLOW_255 if ((char) c == (char) -1 && !tTd(82, 101) && !EightBitAddrOK) c &= 0x7f; #endif /* !ALLOW_255 */ *q++ = c; } /* read a new input character */ c = (*p++) & 0x00ff; if (c == '\0') { /* diagnose and patch up bad syntax */ if (ignore) break; else if (state == QST) { usrerr("553 Unbalanced '\"'"); c = '"'; } else if (cmntcnt > 0) { usrerr("553 Unbalanced '('"); c = ')'; } else if (anglecnt > 0) { c = '>'; usrerr("553 Unbalanced '<'"); } else break; p--; } else if (c == delim && cmntcnt <= 0 && state != QST) { if (anglecnt <= 0) break; /* special case for better error management */ if (delim == ',' && !route_syntax && !ignore) { usrerr("553 Unbalanced '<'"); c = '>'; p--; } } if (tTd(22, 101)) sm_dprintf("c=%c, s=%d; ", c, state); /* chew up special characters */ *q = '\0'; if (bslashmode) { bslashmode = false; /* kludge \! for naive users */ if (cmntcnt > 0) { c = NOCHAR; continue; } else if (c != '!' || state == QST) { /* see if there is room */ if (q >= &pvpbuf[pvpbsize - 5]) goto addrtoolong; *q++ = '\\'; continue; } } if (c == '\\') { bslashmode = true; } else if (state == QST) { /* EMPTY */ /* do nothing, just avoid next clauses */ } else if (c == '(' && toktab['('] == SPC) { cmntcnt++; c = NOCHAR; } else if (c == ')' && toktab['('] == SPC) { if (cmntcnt <= 0) { if (!ignore) { usrerr("553 Unbalanced ')'"); c = NOCHAR; } } else cmntcnt--; } else if (cmntcnt > 0) { c = NOCHAR; } else if (c == '<') { char *ptr = p; anglecnt++; while (isascii(*ptr) && isspace(*ptr)) ptr++; if (*ptr == '@') route_syntax = true; } else if (c == '>') { if (anglecnt <= 0) { if (!ignore) { usrerr("553 Unbalanced '>'"); c = NOCHAR; } } else anglecnt--; route_syntax = false; } else if (delim == ' ' && isascii(c) && isspace(c)) c = ' '; if (c == NOCHAR) continue; /* see if this is end of input */ if (c == delim && anglecnt <= 0 && state != QST) break; newstate = StateTab[state][toktab[c & 0xff]]; if (tTd(22, 101)) sm_dprintf("ns=%02o\n", newstate); state = newstate & TYPE; if (state == ILL) { if (isascii(c) && isprint(c)) usrerr("553 Illegal character %c", c); else usrerr("553 Illegal character 0x%02x", c & 0x0ff); } if (bitset(M, newstate)) c = NOCHAR; if (bitset(B, newstate)) break; } /* new token */ if (tok != q) { /* see if there is room */ if (q >= &pvpbuf[pvpbsize - 5]) goto addrtoolong; *q++ = '\0'; if (tTd(22, 36)) { sm_dprintf("tok="); xputs(sm_debug_file(), tok); sm_dprintf("\n"); } if (avp >= &av[MAXATOM]) { usrerr("553 5.1.0 prescan: too many tokens"); goto returnnull; } if (q - tok > MAXNAME) { usrerr("553 5.1.0 prescan: token too long"); goto returnnull; } *avp++ = tok; } } while (c != '\0' && (c != delim || anglecnt > 0)); *avp = NULL; if (delimptr != NULL) { if (p > addr) p--; *delimptr = p; } if (tTd(22, 12)) { sm_dprintf("prescan==>"); printav(sm_debug_file(), av); } CurEnv->e_to = saveto; if (av[0] == NULL) { if (tTd(22, 1)) sm_dprintf("prescan: null leading token\n"); return NULL; } return av; } /* ** REWRITE -- apply rewrite rules to token vector. ** ** This routine is an ordered production system. Each rewrite ** rule has a LHS (called the pattern) and a RHS (called the ** rewrite); 'rwr' points the the current rewrite rule. ** ** For each rewrite rule, 'avp' points the address vector we ** are trying to match against, and 'pvp' points to the pattern. ** If pvp points to a special match value (MATCHZANY, MATCHANY, ** MATCHONE, MATCHCLASS, MATCHNCLASS) then the address in avp ** matched is saved away in the match vector (pointed to by 'mvp'). ** ** When a match between avp & pvp does not match, we try to ** back out. If we back up over MATCHONE, MATCHCLASS, or MATCHNCLASS ** we must also back out the match in mvp. If we reach a ** MATCHANY or MATCHZANY we just extend the match and start ** over again. ** ** When we finally match, we rewrite the address vector ** and try over again. ** ** Parameters: ** pvp -- pointer to token vector. ** ruleset -- the ruleset to use for rewriting. ** reclevel -- recursion level (to catch loops). ** e -- the current envelope. ** maxatom -- maximum length of buffer (usually MAXATOM) ** ** Returns: ** A status code. If EX_TEMPFAIL, higher level code should ** attempt recovery. ** ** Side Effects: ** pvp is modified. */ struct match { char **match_first; /* first token matched */ char **match_last; /* last token matched */ char **match_pattern; /* pointer to pattern */ }; int rewrite(pvp, ruleset, reclevel, e, maxatom) char **pvp; int ruleset; int reclevel; register ENVELOPE *e; int maxatom; { register char *ap; /* address pointer */ register char *rp; /* rewrite pointer */ register char *rulename; /* ruleset name */ register char *prefix; register char **avp; /* address vector pointer */ register char **rvp; /* rewrite vector pointer */ register struct match *mlp; /* cur ptr into mlist */ register struct rewrite *rwr; /* pointer to current rewrite rule */ int ruleno; /* current rule number */ int rstat = EX_OK; /* return status */ int loopcount; struct match mlist[MAXMATCH]; /* stores match on LHS */ char *npvp[MAXATOM + 1]; /* temporary space for rebuild */ char buf[MAXLINE]; char name[6]; /* ** mlp will not exceed mlist[] because readcf enforces ** the upper limit of entries when reading rulesets. */ if (ruleset < 0 || ruleset >= MAXRWSETS) { syserr("554 5.3.5 rewrite: illegal ruleset number %d", ruleset); return EX_CONFIG; } rulename = RuleSetNames[ruleset]; if (rulename == NULL) { (void) sm_snprintf(name, sizeof(name), "%d", ruleset); rulename = name; } if (OpMode == MD_TEST) prefix = ""; else prefix = "rewrite: ruleset "; if (OpMode == MD_TEST) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s%-16.16s input:", prefix, rulename); printav(smioout, pvp); } else if (tTd(21, 1)) { sm_dprintf("%s%-16.16s input:", prefix, rulename); printav(sm_debug_file(), pvp); } if (reclevel++ > MaxRuleRecursion) { syserr("rewrite: excessive recursion (max %d), ruleset %s", MaxRuleRecursion, rulename); return EX_CONFIG; } if (pvp == NULL) return EX_USAGE; if (maxatom <= 0) return EX_USAGE; /* ** Run through the list of rewrite rules, applying ** any that match. */ ruleno = 1; loopcount = 0; for (rwr = RewriteRules[ruleset]; rwr != NULL; ) { int status; /* if already canonical, quit now */ if (pvp[0] != NULL && (pvp[0][0] & 0377) == CANONNET) break; if (tTd(21, 12)) { if (tTd(21, 15)) sm_dprintf("-----trying rule (line %d):", rwr->r_line); else sm_dprintf("-----trying rule:"); printav(sm_debug_file(), rwr->r_lhs); } /* try to match on this rule */ mlp = mlist; rvp = rwr->r_lhs; avp = pvp; if (++loopcount > 100) { syserr("554 5.3.5 Infinite loop in ruleset %s, rule %d", rulename, ruleno); if (tTd(21, 1)) { sm_dprintf("workspace: "); printav(sm_debug_file(), pvp); } break; } while ((ap = *avp) != NULL || *rvp != NULL) { rp = *rvp; if (tTd(21, 35)) { sm_dprintf("ADVANCE rp="); xputs(sm_debug_file(), rp); sm_dprintf(", ap="); xputs(sm_debug_file(), ap); sm_dprintf("\n"); } if (rp == NULL) { /* end-of-pattern before end-of-address */ goto backup; } if (ap == NULL && (rp[0] & 0377) != MATCHZANY && (rp[0] & 0377) != MATCHZERO) { /* end-of-input with patterns left */ goto backup; } switch (rp[0] & 0377) { case MATCHCLASS: /* match any phrase in a class */ mlp->match_pattern = rvp; mlp->match_first = avp; extendclass: ap = *avp; if (ap == NULL) goto backup; mlp->match_last = avp++; cataddr(mlp->match_first, mlp->match_last, buf, sizeof(buf), '\0', true); if (!wordinclass(buf, rp[1])) { if (tTd(21, 36)) { sm_dprintf("EXTEND rp="); xputs(sm_debug_file(), rp); sm_dprintf(", ap="); xputs(sm_debug_file(), ap); sm_dprintf("\n"); } goto extendclass; } if (tTd(21, 36)) sm_dprintf("CLMATCH\n"); mlp++; break; case MATCHNCLASS: /* match any token not in a class */ if (wordinclass(ap, rp[1])) goto backup; /* FALLTHROUGH */ case MATCHONE: case MATCHANY: /* match exactly one token */ mlp->match_pattern = rvp; mlp->match_first = avp; mlp->match_last = avp++; mlp++; break; case MATCHZANY: /* match zero or more tokens */ mlp->match_pattern = rvp; mlp->match_first = avp; mlp->match_last = avp - 1; mlp++; break; case MATCHZERO: /* match zero tokens */ break; case MACRODEXPAND: /* ** Match against run-time macro. ** This algorithm is broken for the ** general case (no recursive macros, ** improper tokenization) but should ** work for the usual cases. */ ap = macvalue(rp[1], e); mlp->match_first = avp; if (tTd(21, 2)) sm_dprintf("rewrite: LHS $&{%s} => \"%s\"\n", macname(rp[1]), ap == NULL ? "(NULL)" : ap); if (ap == NULL) break; while (*ap != '\0') { if (*avp == NULL || sm_strncasecmp(ap, *avp, strlen(*avp)) != 0) { /* no match */ avp = mlp->match_first; goto backup; } ap += strlen(*avp++); } /* match */ break; default: /* must have exact match */ if (sm_strcasecmp(rp, ap)) goto backup; avp++; break; } /* successful match on this token */ rvp++; continue; backup: /* match failed -- back up */ while (--mlp >= mlist) { rvp = mlp->match_pattern; rp = *rvp; avp = mlp->match_last + 1; ap = *avp; if (tTd(21, 36)) { sm_dprintf("BACKUP rp="); xputs(sm_debug_file(), rp); sm_dprintf(", ap="); xputs(sm_debug_file(), ap); sm_dprintf("\n"); } if (ap == NULL) { /* run off the end -- back up again */ continue; } if ((rp[0] & 0377) == MATCHANY || (rp[0] & 0377) == MATCHZANY) { /* extend binding and continue */ mlp->match_last = avp++; rvp++; mlp++; break; } if ((rp[0] & 0377) == MATCHCLASS) { /* extend binding and try again */ mlp->match_last = avp; goto extendclass; } } if (mlp < mlist) { /* total failure to match */ break; } } /* ** See if we successfully matched */ if (mlp < mlist || *rvp != NULL) { if (tTd(21, 10)) sm_dprintf("----- rule fails\n"); rwr = rwr->r_next; ruleno++; loopcount = 0; continue; } rvp = rwr->r_rhs; if (tTd(21, 12)) { sm_dprintf("-----rule matches:"); printav(sm_debug_file(), rvp); } rp = *rvp; if (rp != NULL) { if ((rp[0] & 0377) == CANONUSER) { rvp++; rwr = rwr->r_next; ruleno++; loopcount = 0; } else if ((rp[0] & 0377) == CANONHOST) { rvp++; rwr = NULL; } } /* substitute */ for (avp = npvp; *rvp != NULL; rvp++) { register struct match *m; register char **pp; rp = *rvp; if ((rp[0] & 0377) == MATCHREPL) { /* substitute from LHS */ m = &mlist[rp[1] - '1']; if (m < mlist || m >= mlp) { syserr("554 5.3.5 rewrite: ruleset %s: replacement $%c out of bounds", rulename, rp[1]); return EX_CONFIG; } if (tTd(21, 15)) { sm_dprintf("$%c:", rp[1]); pp = m->match_first; while (pp <= m->match_last) { sm_dprintf(" %p=\"", *pp); sm_dflush(); sm_dprintf("%s\"", *pp++); } sm_dprintf("\n"); } pp = m->match_first; while (pp <= m->match_last) { if (avp >= &npvp[maxatom]) goto toolong; *avp++ = *pp++; } } else { /* some sort of replacement */ if (avp >= &npvp[maxatom]) { toolong: syserr("554 5.3.0 rewrite: expansion too long"); if (LogLevel > 9) sm_syslog(LOG_ERR, e->e_id, "rewrite: expansion too long, ruleset=%s, ruleno=%d", rulename, ruleno); return EX_DATAERR; } if ((rp[0] & 0377) != MACRODEXPAND) { /* vanilla replacement from RHS */ *avp++ = rp; } else { /* $&{x} replacement */ char *mval = macvalue(rp[1], e); char **xpvp; size_t trsize = 0; static size_t pvpb1_size = 0; static char **pvpb1 = NULL; char pvpbuf[PSBUFSIZE]; if (tTd(21, 2)) sm_dprintf("rewrite: RHS $&{%s} => \"%s\"\n", macname(rp[1]), mval == NULL ? "(NULL)" : mval); if (mval == NULL || *mval == '\0') continue; /* save the remainder of the input */ for (xpvp = pvp; *xpvp != NULL; xpvp++) trsize += sizeof(*xpvp); if (trsize > pvpb1_size) { if (pvpb1 != NULL) sm_free(pvpb1); pvpb1 = (char **) sm_pmalloc_x(trsize); pvpb1_size = trsize; } memmove((char *) pvpb1, (char *) pvp, trsize); /* scan the new replacement */ xpvp = prescan(mval, '\0', pvpbuf, sizeof(pvpbuf), NULL, NULL, false); if (xpvp == NULL) { /* prescan pre-printed error */ return EX_DATAERR; } /* insert it into the output stream */ while (*xpvp != NULL) { if (tTd(21, 19)) sm_dprintf(" ... %s\n", *xpvp); *avp++ = sm_rpool_strdup_x( e->e_rpool, *xpvp); if (avp >= &npvp[maxatom]) goto toolong; xpvp++; } if (tTd(21, 19)) sm_dprintf(" ... DONE\n"); /* restore the old trailing input */ memmove((char *) pvp, (char *) pvpb1, trsize); } } } *avp++ = NULL; /* ** Check for any hostname/keyword lookups. */ for (rvp = npvp; *rvp != NULL; rvp++) { char **hbrvp; char **xpvp; size_t trsize; char *replac; int endtoken; bool external; STAB *map; char *mapname; char **key_rvp; char **arg_rvp; char **default_rvp; char cbuf[MAXKEY]; char *pvpb1[MAXATOM + 1]; char *argvect[MAX_MAP_ARGS]; char pvpbuf[PSBUFSIZE]; char *nullpvp[1]; hbrvp = rvp; if ((rvp[0][0] & 0377) == HOSTBEGIN) { endtoken = HOSTEND; mapname = "host"; } else if ((rvp[0][0] & 0377) == LOOKUPBEGIN) { endtoken = LOOKUPEND; mapname = *++rvp; if (mapname == NULL) { syserr("554 5.3.0 rewrite: missing mapname"); /* NOTREACHED */ SM_ASSERT(0); } } else continue; /* ** Got a hostname/keyword lookup. ** ** This could be optimized fairly easily. */ map = stab(mapname, ST_MAP, ST_FIND); if (map == NULL) syserr("554 5.3.0 rewrite: map %s not found", mapname); /* extract the match part */ key_rvp = ++rvp; if (key_rvp == NULL) { syserr("554 5.3.0 rewrite: missing key for map %s", mapname); /* NOTREACHED */ SM_ASSERT(0); } default_rvp = NULL; arg_rvp = argvect; xpvp = NULL; replac = pvpbuf; while (*rvp != NULL && ((rvp[0][0] & 0377) != endtoken)) { int nodetype = rvp[0][0] & 0377; if (nodetype != CANONHOST && nodetype != CANONUSER) { rvp++; continue; } *rvp++ = NULL; if (xpvp != NULL) { cataddr(xpvp, NULL, replac, &pvpbuf[sizeof(pvpbuf)] - replac, '\0', false); if (arg_rvp < &argvect[MAX_MAP_ARGS - 1]) *++arg_rvp = replac; replac += strlen(replac) + 1; xpvp = NULL; } switch (nodetype) { case CANONHOST: xpvp = rvp; break; case CANONUSER: default_rvp = rvp; break; } } if (*rvp != NULL) *rvp++ = NULL; if (xpvp != NULL) { cataddr(xpvp, NULL, replac, &pvpbuf[sizeof(pvpbuf)] - replac, '\0', false); if (arg_rvp < &argvect[MAX_MAP_ARGS - 1]) *++arg_rvp = replac; } if (arg_rvp >= &argvect[MAX_MAP_ARGS - 1]) argvect[MAX_MAP_ARGS - 1] = NULL; else *++arg_rvp = NULL; /* save the remainder of the input string */ trsize = (avp - rvp + 1) * sizeof(*rvp); memmove((char *) pvpb1, (char *) rvp, trsize); /* look it up */ cataddr(key_rvp, NULL, cbuf, sizeof(cbuf), map == NULL ? '\0' : map->s_map.map_spacesub, true); argvect[0] = cbuf; replac = map_lookup(map, cbuf, argvect, &rstat, e); external = replac != NULL; /* if no replacement, use default */ if (replac == NULL && default_rvp != NULL) { /* create the default */ cataddr(default_rvp, NULL, cbuf, sizeof(cbuf), '\0', false); replac = cbuf; } if (replac == NULL) { xpvp = key_rvp; } else if (*replac == '\0') { /* null replacement */ nullpvp[0] = NULL; xpvp = nullpvp; } else { /* scan the new replacement */ xpvp = prescan(replac, '\0', pvpbuf, sizeof(pvpbuf), NULL, external ? NULL : IntTokenTab, false); if (xpvp == NULL) { /* prescan already printed error */ return EX_DATAERR; } } /* append it to the token list */ for (avp = hbrvp; *xpvp != NULL; xpvp++) { *avp++ = sm_rpool_strdup_x(e->e_rpool, *xpvp); if (avp >= &npvp[maxatom]) goto toolong; } /* restore the old trailing information */ rvp = avp - 1; for (xpvp = pvpb1; (*avp++ = *xpvp++) != NULL; ) if (avp >= &npvp[maxatom]) goto toolong; } /* ** Check for subroutine calls. */ status = callsubr(npvp, reclevel, e); if (rstat == EX_OK || status == EX_TEMPFAIL) rstat = status; /* copy vector back into original space. */ for (avp = npvp; *avp++ != NULL;) continue; memmove((char *) pvp, (char *) npvp, (int) (avp - npvp) * sizeof(*avp)); if (tTd(21, 4)) { sm_dprintf("rewritten as:"); printav(sm_debug_file(), pvp); } } if (OpMode == MD_TEST) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s%-16.16s returns:", prefix, rulename); printav(smioout, pvp); } else if (tTd(21, 1)) { sm_dprintf("%s%-16.16s returns:", prefix, rulename); printav(sm_debug_file(), pvp); } return rstat; } /* ** CALLSUBR -- call subroutines in rewrite vector ** ** Parameters: ** pvp -- pointer to token vector. ** reclevel -- the current recursion level. ** e -- the current envelope. ** ** Returns: ** The status from the subroutine call. ** ** Side Effects: ** pvp is modified. */ static int callsubr(pvp, reclevel, e) char **pvp; int reclevel; ENVELOPE *e; { char **avp; register int i; int subr, j; int nsubr; int status; int rstat = EX_OK; #define MAX_SUBR 16 int subrnumber[MAX_SUBR]; int subrindex[MAX_SUBR]; nsubr = 0; /* ** Look for subroutine calls in pvp, collect them into subr*[] ** We will perform the calls in the next loop, because we will ** call the "last" subroutine first to avoid recursive calls ** and too much copying. */ for (avp = pvp, j = 0; *avp != NULL; avp++, j++) { if ((avp[0][0] & 0377) == CALLSUBR && avp[1] != NULL) { stripquotes(avp[1]); subr = strtorwset(avp[1], NULL, ST_FIND); if (subr < 0) { syserr("554 5.3.5 Unknown ruleset %s", avp[1]); return EX_CONFIG; } /* ** XXX instead of doing this we could optimize ** the rules after reading them: just remove ** calls to empty rulesets */ /* subroutine is an empty ruleset? don't call it */ if (RewriteRules[subr] == NULL) { if (tTd(21, 3)) sm_dprintf("-----skip subr %s (%d)\n", avp[1], subr); for (i = 2; avp[i] != NULL; i++) avp[i - 2] = avp[i]; avp[i - 2] = NULL; continue; } if (++nsubr >= MAX_SUBR) { syserr("554 5.3.0 Too many subroutine calls (%d max)", MAX_SUBR); return EX_CONFIG; } subrnumber[nsubr] = subr; subrindex[nsubr] = j; } } /* ** Perform the actual subroutines calls, "last" one first, i.e., ** go from the right to the left through all calls, ** do the rewriting in place. */ for (; nsubr > 0; nsubr--) { subr = subrnumber[nsubr]; avp = pvp + subrindex[nsubr]; /* remove the subroutine call and name */ for (i = 2; avp[i] != NULL; i++) avp[i - 2] = avp[i]; avp[i - 2] = NULL; /* ** Now we need to call the ruleset specified for ** the subroutine. We can do this in place since ** we call the "last" subroutine first. */ status = rewrite(avp, subr, reclevel, e, MAXATOM - subrindex[nsubr]); if (status != EX_OK && status != EX_TEMPFAIL) return status; if (rstat == EX_OK || status == EX_TEMPFAIL) rstat = status; } return rstat; } /* ** MAP_LOOKUP -- do lookup in map ** ** Parameters: ** smap -- the map to use for the lookup. ** key -- the key to look up. ** argvect -- arguments to pass to the map lookup. ** pstat -- a pointer to an integer in which to store the ** status from the lookup. ** e -- the current envelope. ** ** Returns: ** The result of the lookup. ** NULL -- if there was no data for the given key. */ static char * map_lookup(smap, key, argvect, pstat, e) STAB *smap; char key[]; char **argvect; int *pstat; ENVELOPE *e; { auto int status = EX_OK; MAP *map; char *replac; if (smap == NULL) return NULL; map = &smap->s_map; DYNOPENMAP(map); if (e->e_sendmode == SM_DEFER && bitset(MF_DEFER, map->map_mflags)) { /* don't do any map lookups */ if (tTd(60, 1)) sm_dprintf("map_lookup(%s, %s) => DEFERRED\n", smap->s_name, key); *pstat = EX_TEMPFAIL; return NULL; } if (!bitset(MF_KEEPQUOTES, map->map_mflags)) stripquotes(key); if (tTd(60, 1)) { sm_dprintf("map_lookup(%s, ", smap->s_name); xputs(sm_debug_file(), key); if (tTd(60, 5)) { int i; for (i = 0; argvect[i] != NULL; i++) sm_dprintf(", %%%d=%s", i, argvect[i]); } sm_dprintf(") => "); } replac = (*map->map_class->map_lookup)(map, key, argvect, &status); if (tTd(60, 1)) sm_dprintf("%s (%d)\n", replac != NULL ? replac : "NOT FOUND", status); /* should recover if status == EX_TEMPFAIL */ if (status == EX_TEMPFAIL && !bitset(MF_NODEFER, map->map_mflags)) { *pstat = EX_TEMPFAIL; if (tTd(60, 1)) sm_dprintf("map_lookup(%s, %s) tempfail: errno=%d\n", smap->s_name, key, errno); if (e->e_message == NULL) { char mbuf[320]; (void) sm_snprintf(mbuf, sizeof(mbuf), "%.80s map: lookup (%s): deferred", smap->s_name, shortenstring(key, MAXSHORTSTR)); e->e_message = sm_rpool_strdup_x(e->e_rpool, mbuf); } } if (status == EX_TEMPFAIL && map->map_tapp != NULL) { size_t i = strlen(key) + strlen(map->map_tapp) + 1; static char *rwbuf = NULL; static size_t rwbuflen = 0; if (i > rwbuflen) { if (rwbuf != NULL) sm_free(rwbuf); rwbuflen = i; rwbuf = (char *) sm_pmalloc_x(rwbuflen); } (void) sm_strlcpyn(rwbuf, rwbuflen, 2, key, map->map_tapp); if (tTd(60, 4)) sm_dprintf("map_lookup tempfail: returning \"%s\"\n", rwbuf); return rwbuf; } return replac; } /* ** INITERRMAILERS -- initialize error and discard mailers ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** initializes error and discard mailers. */ static MAILER discardmailer; static MAILER errormailer; static char *discardargv[] = { "DISCARD", NULL }; static char *errorargv[] = { "ERROR", NULL }; void initerrmailers() { if (discardmailer.m_name == NULL) { /* initialize the discard mailer */ discardmailer.m_name = "*discard*"; discardmailer.m_mailer = "DISCARD"; discardmailer.m_argv = discardargv; } if (errormailer.m_name == NULL) { /* initialize the bogus mailer */ errormailer.m_name = "*error*"; errormailer.m_mailer = "ERROR"; errormailer.m_argv = errorargv; } } /* ** BUILDADDR -- build address from token vector. ** ** Parameters: ** tv -- token vector. ** a -- pointer to address descriptor to fill. ** If NULL, one will be allocated. ** flags -- info regarding whether this is a sender or ** a recipient. ** e -- the current envelope. ** ** Returns: ** NULL if there was an error. ** 'a' otherwise. ** ** Side Effects: ** fills in 'a' */ static struct errcodes { char *ec_name; /* name of error code */ int ec_code; /* numeric code */ } ErrorCodes[] = { { "usage", EX_USAGE }, { "nouser", EX_NOUSER }, { "nohost", EX_NOHOST }, { "unavailable", EX_UNAVAILABLE }, { "software", EX_SOFTWARE }, { "tempfail", EX_TEMPFAIL }, { "protocol", EX_PROTOCOL }, { "config", EX_CONFIG }, { NULL, EX_UNAVAILABLE } }; static ADDRESS * buildaddr(tv, a, flags, e) register char **tv; register ADDRESS *a; int flags; register ENVELOPE *e; { bool tempfail = false; int maxatom; struct mailer **mp; register struct mailer *m; register char *p; char *mname; char **hostp; char hbuf[MAXNAME + 1]; static char ubuf[MAXNAME + 2]; if (tTd(24, 5)) { sm_dprintf("buildaddr, flags=%x, tv=", flags); printav(sm_debug_file(), tv); } maxatom = MAXATOM; if (a == NULL) a = (ADDRESS *) sm_rpool_malloc_x(e->e_rpool, sizeof(*a)); memset((char *) a, '\0', sizeof(*a)); hbuf[0] = '\0'; /* set up default error return flags */ a->q_flags |= DefaultNotify; /* figure out what net/mailer to use */ if (*tv == NULL || (**tv & 0377) != CANONNET) { syserr("554 5.3.5 buildaddr: no mailer in parsed address"); badaddr: /* ** ExitStat may have been set by an earlier map open ** failure (to a permanent error (EX_OSERR) in syserr()) ** so we also need to check if this particular $#error ** return wanted a 4XX failure. ** ** XXX the real fix is probably to set ExitStat correctly, ** i.e., to EX_TEMPFAIL if the map open is just a temporary ** error. */ if (ExitStat == EX_TEMPFAIL || tempfail) a->q_state = QS_QUEUEUP; else { a->q_state = QS_BADADDR; a->q_mailer = &errormailer; } return a; } mname = *++tv; --maxatom; /* extract host and user portions */ if (*++tv != NULL && (**tv & 0377) == CANONHOST) { hostp = ++tv; --maxatom; } else hostp = NULL; --maxatom; while (*tv != NULL && (**tv & 0377) != CANONUSER) { tv++; --maxatom; } if (*tv == NULL) { syserr("554 5.3.5 buildaddr: no user"); goto badaddr; } if (tv == hostp) hostp = NULL; else if (hostp != NULL) cataddr(hostp, tv - 1, hbuf, sizeof(hbuf), '\0', false); cataddr(++tv, NULL, ubuf, sizeof(ubuf), ' ', false); --maxatom; /* save away the host name */ if (sm_strcasecmp(mname, "error") == 0) { /* Set up triplet for use by -bv */ a->q_mailer = &errormailer; a->q_user = sm_rpool_strdup_x(e->e_rpool, ubuf); /* XXX wrong place? */ if (hostp != NULL) { register struct errcodes *ep; a->q_host = sm_rpool_strdup_x(e->e_rpool, hbuf); if (strchr(hbuf, '.') != NULL) { a->q_status = sm_rpool_strdup_x(e->e_rpool, hbuf); setstat(dsntoexitstat(hbuf)); } else if (isascii(hbuf[0]) && isdigit(hbuf[0])) { setstat(atoi(hbuf)); } else { for (ep = ErrorCodes; ep->ec_name != NULL; ep++) if (sm_strcasecmp(ep->ec_name, hbuf) == 0) break; setstat(ep->ec_code); } } else { a->q_host = NULL; setstat(EX_UNAVAILABLE); } stripquotes(ubuf); if (ISSMTPCODE(ubuf) && ubuf[3] == ' ') { char fmt[16]; int off; if ((off = isenhsc(ubuf + 4, ' ')) > 0) { ubuf[off + 4] = '\0'; off += 5; } else { off = 4; ubuf[3] = '\0'; } (void) sm_strlcpyn(fmt, sizeof(fmt), 2, ubuf, " %s"); if (off > 4) usrerr(fmt, ubuf + off); else if (isenhsc(hbuf, '\0') > 0) usrerrenh(hbuf, fmt, ubuf + off); else usrerr(fmt, ubuf + off); /* XXX ubuf[off - 1] = ' '; */ if (ubuf[0] == '4') tempfail = true; } else { usrerr("553 5.3.0 %s", ubuf); } goto badaddr; } for (mp = Mailer; (m = *mp++) != NULL; ) { if (sm_strcasecmp(m->m_name, mname) == 0) break; } if (m == NULL) { syserr("554 5.3.5 buildaddr: unknown mailer %s", mname); goto badaddr; } a->q_mailer = m; /* figure out what host (if any) */ if (hostp == NULL) { if (!bitnset(M_LOCALMAILER, m->m_flags)) { syserr("554 5.3.5 buildaddr: no host"); goto badaddr; } a->q_host = NULL; } else a->q_host = sm_rpool_strdup_x(e->e_rpool, hbuf); /* figure out the user */ p = ubuf; if (bitnset(M_CHECKUDB, m->m_flags) && *p == '@') { p++; tv++; --maxatom; a->q_flags |= QNOTREMOTE; } /* do special mapping for local mailer */ if (*p == '"') p++; if (*p == '|' && bitnset(M_CHECKPROG, m->m_flags)) a->q_mailer = m = ProgMailer; else if (*p == '/' && bitnset(M_CHECKFILE, m->m_flags)) a->q_mailer = m = FileMailer; else if (*p == ':' && bitnset(M_CHECKINCLUDE, m->m_flags)) { /* may be :include: */ stripquotes(ubuf); if (sm_strncasecmp(ubuf, ":include:", 9) == 0) { /* if :include:, don't need further rewriting */ a->q_mailer = m = InclMailer; a->q_user = sm_rpool_strdup_x(e->e_rpool, &ubuf[9]); return a; } } /* rewrite according recipient mailer rewriting rules */ macdefine(&e->e_macro, A_PERM, 'h', a->q_host); if (ConfigLevel >= 10 || !bitset(RF_SENDERADDR|RF_HEADERADDR, flags)) { /* sender addresses done later */ (void) rewrite(tv, 2, 0, e, maxatom); if (m->m_re_rwset > 0) (void) rewrite(tv, m->m_re_rwset, 0, e, maxatom); } (void) rewrite(tv, 4, 0, e, maxatom); /* save the result for the command line/RCPT argument */ cataddr(tv, NULL, ubuf, sizeof(ubuf), '\0', true); a->q_user = sm_rpool_strdup_x(e->e_rpool, ubuf); /* ** Do mapping to lower case as requested by mailer */ if (a->q_host != NULL && !bitnset(M_HST_UPPER, m->m_flags)) makelower(a->q_host); if (!bitnset(M_USR_UPPER, m->m_flags)) makelower(a->q_user); if (tTd(24, 6)) { sm_dprintf("buildaddr => "); printaddr(sm_debug_file(), a, false); } return a; } /* ** CATADDR -- concatenate pieces of addresses (putting in subs) ** ** Parameters: ** pvp -- parameter vector to rebuild. ** evp -- last parameter to include. Can be NULL to ** use entire pvp. ** buf -- buffer to build the string into. ** sz -- size of buf. ** spacesub -- the space separator character; if '\0', ** use SpaceSub. ** external -- convert to external form? ** (no metacharacters; METAQUOTEs removed, see below) ** ** Returns: ** none. ** ** Side Effects: ** Destroys buf. ** ** Notes: ** There are two formats for strings: internal and external. ** The external format is just an eight-bit clean string (no ** null bytes, everything else OK). The internal format can ** include sendmail metacharacters. The special character ** METAQUOTE essentially quotes the character following, stripping ** it of all special semantics. ** ** The cataddr routine needs to be aware of whether it is producing ** an internal or external form as output (it only takes internal ** form as input). ** ** The parseaddr routine has a similar issue on input, but that ** is flagged on the basis of which token table is passed in. */ void cataddr(pvp, evp, buf, sz, spacesub, external) char **pvp; char **evp; char *buf; register int sz; int spacesub; bool external; { bool oatomtok, natomtok; char *p; oatomtok = natomtok = false; if (tTd(59, 14)) { sm_dprintf("cataddr(%d) <==", external); printav(sm_debug_file(), pvp); } if (sz <= 0) return; if (spacesub == '\0') spacesub = SpaceSub; if (pvp == NULL) { *buf = '\0'; return; } p = buf; sz -= 2; while (*pvp != NULL && sz > 0) { char *q; natomtok = (IntTokenTab[**pvp & 0xff] == ATM); if (oatomtok && natomtok) { *p++ = spacesub; if (--sz <= 0) break; } for (q = *pvp; *q != '\0'; ) { int c; if (--sz <= 0) break; *p++ = c = *q++; /* ** If the current character (c) is METAQUOTE and we ** want the "external" form and the next character ** is not NUL, then overwrite METAQUOTE with that ** character (i.e., METAQUOTE ch is changed to ** ch). p[-1] is used because p is advanced (above). */ if ((c & 0377) == METAQUOTE && external && *q != '\0') p[-1] = *q++; } if (sz <= 0) break; oatomtok = natomtok; if (pvp++ == evp) break; } #if 0 /* ** Silently truncate long strings: even though this doesn't ** seem like a good idea it is necessary because header checks ** send the whole header value to rscheck() and hence rewrite(). ** The latter however sometimes uses a "short" buffer (e.g., ** cbuf[MAXNAME + 1]) to call cataddr() which then triggers this ** error function. One possible fix to the problem is to pass ** flags to rscheck() and rewrite() to distinguish the various ** calls and only trigger the error if necessary. For now just ** undo the change from 8.13.0. */ if (sz <= 0) usrerr("cataddr: string too long"); #endif *p = '\0'; if (tTd(59, 14)) sm_dprintf(" cataddr => %s\n", str2prt(buf)); } /* ** SAMEADDR -- Determine if two addresses are the same ** ** This is not just a straight comparison -- if the mailer doesn't ** care about the host we just ignore it, etc. ** ** Parameters: ** a, b -- pointers to the internal forms to compare. ** ** Returns: ** true -- they represent the same mailbox. ** false -- they don't. ** ** Side Effects: ** none. */ bool sameaddr(a, b) register ADDRESS *a; register ADDRESS *b; { register ADDRESS *ca, *cb; /* if they don't have the same mailer, forget it */ if (a->q_mailer != b->q_mailer) + return false; + + /* + ** Addresses resolving to error mailer + ** should not be considered identical + */ + + if (a->q_mailer == &errormailer) return false; /* if the user isn't the same, we can drop out */ if (strcmp(a->q_user, b->q_user) != 0) return false; /* if we have good uids for both but they differ, these are different */ if (a->q_mailer == ProgMailer) { ca = getctladdr(a); cb = getctladdr(b); if (ca != NULL && cb != NULL && bitset(QGOODUID, ca->q_flags & cb->q_flags) && ca->q_uid != cb->q_uid) return false; } /* otherwise compare hosts (but be careful for NULL ptrs) */ if (a->q_host == b->q_host) { /* probably both null pointers */ return true; } if (a->q_host == NULL || b->q_host == NULL) { /* only one is a null pointer */ return false; } if (strcmp(a->q_host, b->q_host) != 0) return false; return true; } /* ** PRINTADDR -- print address (for debugging) ** ** Parameters: ** a -- the address to print ** follow -- follow the q_next chain. ** ** Returns: ** none. ** ** Side Effects: ** none. */ struct qflags { char *qf_name; unsigned long qf_bit; }; static struct qflags AddressFlags[] = { { "QGOODUID", QGOODUID }, { "QPRIMARY", QPRIMARY }, { "QNOTREMOTE", QNOTREMOTE }, { "QSELFREF", QSELFREF }, { "QBOGUSSHELL", QBOGUSSHELL }, { "QUNSAFEADDR", QUNSAFEADDR }, { "QPINGONSUCCESS", QPINGONSUCCESS }, { "QPINGONFAILURE", QPINGONFAILURE }, { "QPINGONDELAY", QPINGONDELAY }, { "QHASNOTIFY", QHASNOTIFY }, { "QRELAYED", QRELAYED }, { "QEXPANDED", QEXPANDED }, { "QDELIVERED", QDELIVERED }, { "QDELAYED", QDELAYED }, { "QTHISPASS", QTHISPASS }, { "QRCPTOK", QRCPTOK }, { NULL, 0 } }; void printaddr(fp, a, follow) SM_FILE_T *fp; register ADDRESS *a; bool follow; { register MAILER *m; MAILER pseudomailer; register struct qflags *qfp; bool firstone; if (a == NULL) { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "[NULL]\n"); return; } while (a != NULL) { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%p=", a); (void) sm_io_flush(fp, SM_TIME_DEFAULT); /* find the mailer -- carefully */ m = a->q_mailer; if (m == NULL) { m = &pseudomailer; m->m_mno = -1; m->m_name = "NULL"; } (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s:\n\tmailer %d (%s), host `%s'\n", a->q_paddr == NULL ? "" : a->q_paddr, m->m_mno, m->m_name, a->q_host == NULL ? "" : a->q_host); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\tuser `%s', ruser `%s'\n", a->q_user, a->q_ruser == NULL ? "" : a->q_ruser); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\tstate="); switch (a->q_state) { case QS_OK: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "OK"); break; case QS_DONTSEND: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "DONTSEND"); break; case QS_BADADDR: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "BADADDR"); break; case QS_QUEUEUP: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "QUEUEUP"); break; case QS_RETRY: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "RETRY"); break; case QS_SENT: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "SENT"); break; case QS_VERIFIED: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "VERIFIED"); break; case QS_EXPANDED: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "EXPANDED"); break; case QS_SENDER: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "SENDER"); break; case QS_CLONED: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "CLONED"); break; case QS_DISCARDED: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "DISCARDED"); break; case QS_REPLACED: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "REPLACED"); break; case QS_REMOVED: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "REMOVED"); break; case QS_DUPLICATE: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "DUPLICATE"); break; case QS_INCLUDED: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "INCLUDED"); break; default: (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d", a->q_state); break; } (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, ", next=%p, alias %p, uid %d, gid %d\n", a->q_next, a->q_alias, (int) a->q_uid, (int) a->q_gid); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\tflags=%lx<", a->q_flags); firstone = true; for (qfp = AddressFlags; qfp->qf_name != NULL; qfp++) { if (!bitset(qfp->qf_bit, a->q_flags)) continue; if (!firstone) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, ","); firstone = false; (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s", qfp->qf_name); } (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, ">\n"); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\towner=%s, home=\"%s\", fullname=\"%s\"\n", a->q_owner == NULL ? "(none)" : a->q_owner, a->q_home == NULL ? "(none)" : a->q_home, a->q_fullname == NULL ? "(none)" : a->q_fullname); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\torcpt=\"%s\", statmta=%s, status=%s\n", a->q_orcpt == NULL ? "(none)" : a->q_orcpt, a->q_statmta == NULL ? "(none)" : a->q_statmta, a->q_status == NULL ? "(none)" : a->q_status); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\tfinalrcpt=\"%s\"\n", a->q_finalrcpt == NULL ? "(none)" : a->q_finalrcpt); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\trstatus=\"%s\"\n", a->q_rstatus == NULL ? "(none)" : a->q_rstatus); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\tstatdate=%s\n", a->q_statdate == 0 ? "(none)" : ctime(&a->q_statdate)); if (!follow) return; a = a->q_next; } } /* ** EMPTYADDR -- return true if this address is empty (``<>'') ** ** Parameters: ** a -- pointer to the address ** ** Returns: ** true -- if this address is "empty" (i.e., no one should ** ever generate replies to it. ** false -- if it is a "regular" (read: replyable) address. */ bool emptyaddr(a) register ADDRESS *a; { return a->q_paddr == NULL || strcmp(a->q_paddr, "<>") == 0 || a->q_user == NULL || strcmp(a->q_user, "<>") == 0; } /* ** REMOTENAME -- return the name relative to the current mailer ** ** Parameters: ** name -- the name to translate. ** m -- the mailer that we want to do rewriting relative to. ** flags -- fine tune operations. ** pstat -- pointer to status word. ** e -- the current envelope. ** ** Returns: ** the text string representing this address relative to ** the receiving mailer. ** ** Side Effects: ** none. ** ** Warnings: ** The text string returned is tucked away locally; ** copy it if you intend to save it. */ char * remotename(name, m, flags, pstat, e) char *name; struct mailer *m; int flags; int *pstat; register ENVELOPE *e; { register char **pvp; char *SM_NONVOLATILE fancy; char *oldg; int rwset; static char buf[MAXNAME + 1]; char lbuf[MAXNAME + 1]; char pvpbuf[PSBUFSIZE]; char addrtype[4]; if (tTd(12, 1)) { sm_dprintf("remotename("); xputs(sm_debug_file(), name); sm_dprintf(")\n"); } /* don't do anything if we are tagging it as special */ if (bitset(RF_SENDERADDR, flags)) { rwset = bitset(RF_HEADERADDR, flags) ? m->m_sh_rwset : m->m_se_rwset; addrtype[2] = 's'; } else { rwset = bitset(RF_HEADERADDR, flags) ? m->m_rh_rwset : m->m_re_rwset; addrtype[2] = 'r'; } if (rwset < 0) return name; addrtype[1] = ' '; addrtype[3] = '\0'; addrtype[0] = bitset(RF_HEADERADDR, flags) ? 'h' : 'e'; macdefine(&e->e_macro, A_TEMP, macid("{addr_type}"), addrtype); /* ** Do a heuristic crack of this name to extract any comment info. ** This will leave the name as a comment and a $g macro. */ if (bitset(RF_CANONICAL, flags) || bitnset(M_NOCOMMENT, m->m_flags)) fancy = "\201g"; else fancy = crackaddr(name, e); /* ** Turn the name into canonical form. ** Normally this will be RFC 822 style, i.e., "user@domain". ** If this only resolves to "user", and the "C" flag is ** specified in the sending mailer, then the sender's ** domain will be appended. */ pvp = prescan(name, '\0', pvpbuf, sizeof(pvpbuf), NULL, NULL, false); if (pvp == NULL) return name; if (REWRITE(pvp, 3, e) == EX_TEMPFAIL) *pstat = EX_TEMPFAIL; if (bitset(RF_ADDDOMAIN, flags) && e->e_fromdomain != NULL) { /* append from domain to this address */ register char **pxp = pvp; int l = MAXATOM; /* size of buffer for pvp */ /* see if there is an "@domain" in the current name */ while (*pxp != NULL && strcmp(*pxp, "@") != 0) { pxp++; --l; } if (*pxp == NULL) { /* no.... append the "@domain" from the sender */ register char **qxq = e->e_fromdomain; while ((*pxp++ = *qxq++) != NULL) { if (--l <= 0) { *--pxp = NULL; usrerr("553 5.1.0 remotename: too many tokens"); *pstat = EX_UNAVAILABLE; break; } } if (REWRITE(pvp, 3, e) == EX_TEMPFAIL) *pstat = EX_TEMPFAIL; } } /* ** Do more specific rewriting. ** Rewrite using ruleset 1 or 2 depending on whether this is ** a sender address or not. ** Then run it through any receiving-mailer-specific rulesets. */ if (bitset(RF_SENDERADDR, flags)) { if (REWRITE(pvp, 1, e) == EX_TEMPFAIL) *pstat = EX_TEMPFAIL; } else { if (REWRITE(pvp, 2, e) == EX_TEMPFAIL) *pstat = EX_TEMPFAIL; } if (rwset > 0) { if (REWRITE(pvp, rwset, e) == EX_TEMPFAIL) *pstat = EX_TEMPFAIL; } /* ** Do any final sanitation the address may require. ** This will normally be used to turn internal forms ** (e.g., user@host.LOCAL) into external form. This ** may be used as a default to the above rules. */ if (REWRITE(pvp, 4, e) == EX_TEMPFAIL) *pstat = EX_TEMPFAIL; /* ** Now restore the comment information we had at the beginning. */ cataddr(pvp, NULL, lbuf, sizeof(lbuf), '\0', false); oldg = macget(&e->e_macro, 'g'); macset(&e->e_macro, 'g', lbuf); SM_TRY /* need to make sure route-addrs have */ if (bitset(RF_CANONICAL, flags) && lbuf[0] == '@') expand("<\201g>", buf, sizeof(buf), e); else expand(fancy, buf, sizeof(buf), e); SM_FINALLY macset(&e->e_macro, 'g', oldg); SM_END_TRY if (tTd(12, 1)) { sm_dprintf("remotename => `"); xputs(sm_debug_file(), buf); sm_dprintf("'\n"); } return buf; } /* ** MAPLOCALUSER -- run local username through ruleset 5 for final redirection ** ** Parameters: ** a -- the address to map (but just the user name part). ** sendq -- the sendq in which to install any replacement ** addresses. ** aliaslevel -- the alias nesting depth. ** e -- the envelope. ** ** Returns: ** none. */ #define Q_COPYFLAGS (QPRIMARY|QBOGUSSHELL|QUNSAFEADDR|\ Q_PINGFLAGS|QHASNOTIFY|\ QRELAYED|QEXPANDED|QDELIVERED|QDELAYED|\ QBYTRACE|QBYNDELAY|QBYNRELAY) void maplocaluser(a, sendq, aliaslevel, e) register ADDRESS *a; ADDRESS **sendq; int aliaslevel; ENVELOPE *e; { register char **pvp; register ADDRESS *SM_NONVOLATILE a1 = NULL; char pvpbuf[PSBUFSIZE]; if (tTd(29, 1)) { sm_dprintf("maplocaluser: "); printaddr(sm_debug_file(), a, false); } pvp = prescan(a->q_user, '\0', pvpbuf, sizeof(pvpbuf), NULL, NULL, false); if (pvp == NULL) { if (tTd(29, 9)) sm_dprintf("maplocaluser: cannot prescan %s\n", a->q_user); return; } macdefine(&e->e_macro, A_PERM, 'h', a->q_host); macdefine(&e->e_macro, A_PERM, 'u', a->q_user); macdefine(&e->e_macro, A_PERM, 'z', a->q_home); macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r"); if (REWRITE(pvp, 5, e) == EX_TEMPFAIL) { if (tTd(29, 9)) sm_dprintf("maplocaluser: rewrite tempfail\n"); a->q_state = QS_QUEUEUP; a->q_status = "4.4.3"; return; } if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET) { if (tTd(29, 9)) sm_dprintf("maplocaluser: doesn't resolve\n"); return; } SM_TRY a1 = buildaddr(pvp, NULL, 0, e); SM_EXCEPT(exc, "E:mta.quickabort") /* ** mark address as bad, S5 returned an error ** and we gave that back to the SMTP client. */ a->q_state = QS_DONTSEND; sm_exc_raisenew_x(&EtypeQuickAbort, 2); SM_END_TRY /* if non-null, mailer destination specified -- has it changed? */ if (a1 == NULL || sameaddr(a, a1)) { if (tTd(29, 9)) sm_dprintf("maplocaluser: address unchanged\n"); return; } /* make new address take on flags and print attributes of old */ a1->q_flags &= ~Q_COPYFLAGS; a1->q_flags |= a->q_flags & Q_COPYFLAGS; a1->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_paddr); a1->q_finalrcpt = a->q_finalrcpt; a1->q_orcpt = a->q_orcpt; /* mark old address as dead; insert new address */ a->q_state = QS_REPLACED; if (tTd(29, 5)) { sm_dprintf("maplocaluser: QS_REPLACED "); printaddr(sm_debug_file(), a, false); } a1->q_alias = a; allocaddr(a1, RF_COPYALL, sm_rpool_strdup_x(e->e_rpool, a->q_paddr), e); (void) recipient(a1, sendq, aliaslevel, e); } /* ** DEQUOTE_INIT -- initialize dequote map ** ** Parameters: ** map -- the internal map structure. ** args -- arguments. ** ** Returns: ** true. */ bool dequote_init(map, args) MAP *map; char *args; { register char *p = args; /* there is no check whether there is really an argument */ map->map_mflags |= MF_KEEPQUOTES; for (;;) { while (isascii(*p) && isspace(*p)) p++; if (*p != '-') break; switch (*++p) { case 'a': map->map_app = ++p; break; case 'D': map->map_mflags |= MF_DEFER; break; case 'S': case 's': map->map_spacesub = *++p; break; } while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p = '\0'; } if (map->map_app != NULL) map->map_app = newstr(map->map_app); return true; } /* ** DEQUOTE_MAP -- unquote an address ** ** Parameters: ** map -- the internal map structure (ignored). ** name -- the name to dequote. ** av -- arguments (ignored). ** statp -- pointer to status out-parameter. ** ** Returns: ** NULL -- if there were no quotes, or if the resulting ** unquoted buffer would not be acceptable to prescan. ** else -- The dequoted buffer. */ /* ARGSUSED2 */ char * dequote_map(map, name, av, statp) MAP *map; char *name; char **av; int *statp; { register char *p; register char *q; register char c; int anglecnt = 0; int cmntcnt = 0; int quotecnt = 0; int spacecnt = 0; bool quotemode = false; bool bslashmode = false; char spacesub = map->map_spacesub; for (p = q = name; (c = *p++) != '\0'; ) { if (bslashmode) { bslashmode = false; *q++ = c; continue; } if (c == ' ' && spacesub != '\0') c = spacesub; switch (c) { case '\\': bslashmode = true; break; case '(': cmntcnt++; break; case ')': if (cmntcnt-- <= 0) return NULL; break; case ' ': case '\t': spacecnt++; break; } if (cmntcnt > 0) { *q++ = c; continue; } switch (c) { case '"': quotemode = !quotemode; quotecnt++; continue; case '<': anglecnt++; break; case '>': if (anglecnt-- <= 0) return NULL; break; } *q++ = c; } if (anglecnt != 0 || cmntcnt != 0 || bslashmode || quotemode || quotecnt <= 0 || spacecnt != 0) return NULL; *q++ = '\0'; return map_rewrite(map, name, strlen(name), NULL); } /* ** RSCHECK -- check string(s) for validity using rewriting sets ** ** Parameters: ** rwset -- the rewriting set to use. ** p1 -- the first string to check. ** p2 -- the second string to check -- may be null. ** e -- the current envelope. ** flags -- control some behavior, see RSF_ in sendmail.h ** logl -- logging level. ** host -- NULL or relay host. ** logid -- id for sm_syslog. ** addr -- if not NULL and ruleset returns $#error: ** store mailer triple here. ** ** Returns: ** EX_OK -- if the rwset doesn't resolve to $#error ** else -- the failure status (message printed) */ int rscheck(rwset, p1, p2, e, flags, logl, host, logid, addr) char *rwset; char *p1; char *p2; ENVELOPE *e; int flags; int logl; char *host; char *logid; ADDRESS *addr; { char *volatile buf; size_t bufsize; int saveexitstat; int volatile rstat = EX_OK; char **pvp; int rsno; bool volatile discard = false; bool saveQuickAbort = QuickAbort; bool saveSuprErrs = SuprErrs; bool quarantine = false; char ubuf[BUFSIZ * 2]; char buf0[MAXLINE]; char pvpbuf[PSBUFSIZE]; extern char MsgBuf[]; if (tTd(48, 2)) sm_dprintf("rscheck(%s, %s, %s)\n", rwset, p1, p2 == NULL ? "(NULL)" : p2); rsno = strtorwset(rwset, NULL, ST_FIND); if (rsno < 0) return EX_OK; if (p2 != NULL) { bufsize = strlen(p1) + strlen(p2) + 2; if (bufsize > sizeof(buf0)) buf = sm_malloc_x(bufsize); else { buf = buf0; bufsize = sizeof(buf0); } (void) sm_snprintf(buf, bufsize, "%s%c%s", p1, CONDELSE, p2); } else { bufsize = strlen(p1) + 1; if (bufsize > sizeof(buf0)) buf = sm_malloc_x(bufsize); else { buf = buf0; bufsize = sizeof(buf0); } (void) sm_strlcpy(buf, p1, bufsize); } SM_TRY { SuprErrs = true; QuickAbort = false; pvp = prescan(buf, '\0', pvpbuf, sizeof(pvpbuf), NULL, bitset(RSF_RMCOMM, flags) ? IntTokenTab : TokTypeNoC, bitset(RSF_RMCOMM, flags) ? false : true); SuprErrs = saveSuprErrs; if (pvp == NULL) { if (tTd(48, 2)) sm_dprintf("rscheck: cannot prescan input\n"); /* syserr("rscheck: cannot prescan input: \"%s\"", shortenstring(buf, MAXSHORTSTR)); rstat = EX_DATAERR; */ goto finis; } if (bitset(RSF_UNSTRUCTURED, flags)) SuprErrs = true; (void) REWRITE(pvp, rsno, e); if (bitset(RSF_UNSTRUCTURED, flags)) SuprErrs = saveSuprErrs; if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET || pvp[1] == NULL || (strcmp(pvp[1], "error") != 0 && strcmp(pvp[1], "discard") != 0)) { goto finis; } if (strcmp(pvp[1], "discard") == 0) { if (tTd(48, 2)) sm_dprintf("rscheck: discard mailer selected\n"); e->e_flags |= EF_DISCARD; discard = true; } else if (strcmp(pvp[1], "error") == 0 && pvp[2] != NULL && (pvp[2][0] & 0377) == CANONHOST && pvp[3] != NULL && strcmp(pvp[3], "quarantine") == 0) { if (pvp[4] == NULL || (pvp[4][0] & 0377) != CANONUSER || pvp[5] == NULL) e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, rwset); else { cataddr(&(pvp[5]), NULL, ubuf, sizeof(ubuf), ' ', true); e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, ubuf); } macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), e->e_quarmsg); quarantine = true; } else { auto ADDRESS a1; int savelogusrerrs = LogUsrErrs; static bool logged = false; /* got an error -- process it */ saveexitstat = ExitStat; LogUsrErrs = false; (void) buildaddr(pvp, &a1, 0, e); if (addr != NULL) { addr->q_mailer = a1.q_mailer; addr->q_user = a1.q_user; addr->q_host = a1.q_host; } LogUsrErrs = savelogusrerrs; rstat = ExitStat; ExitStat = saveexitstat; if (!logged) { if (bitset(RSF_COUNT, flags)) markstats(e, &a1, STATS_REJECT); logged = true; } } if (LogLevel > logl) { char *relay; char *p; char lbuf[MAXLINE]; p = lbuf; if (p2 != NULL) { (void) sm_snprintf(p, SPACELEFT(lbuf, p), ", arg2=%s", p2); p += strlen(p); } if (host != NULL) relay = host; else relay = macvalue('_', e); if (relay != NULL) { (void) sm_snprintf(p, SPACELEFT(lbuf, p), ", relay=%s", relay); p += strlen(p); } *p = '\0'; if (discard) sm_syslog(LOG_NOTICE, logid, "ruleset=%s, arg1=%s%s, discard", rwset, p1, lbuf); else if (quarantine) sm_syslog(LOG_NOTICE, logid, "ruleset=%s, arg1=%s%s, quarantine=%s", rwset, p1, lbuf, ubuf); else sm_syslog(LOG_NOTICE, logid, "ruleset=%s, arg1=%s%s, reject=%s", rwset, p1, lbuf, MsgBuf); } finis: ; } SM_FINALLY { /* clean up */ if (buf != buf0) sm_free(buf); QuickAbort = saveQuickAbort; } SM_END_TRY setstat(rstat); /* rulesets don't set errno */ errno = 0; if (rstat != EX_OK && QuickAbort) sm_exc_raisenew_x(&EtypeQuickAbort, 2); return rstat; } /* ** RSCAP -- call rewriting set to return capabilities ** ** Parameters: ** rwset -- the rewriting set to use. ** p1 -- the first string to check. ** p2 -- the second string to check -- may be null. ** e -- the current envelope. ** pvp -- pointer to token vector. ** pvpbuf -- buffer space. ** size -- size of buffer space. ** ** Returns: ** EX_UNAVAILABLE -- ruleset doesn't exist. ** EX_DATAERR -- prescan() failed. ** EX_OK -- rewrite() was successful. ** else -- return status from rewrite(). */ int rscap(rwset, p1, p2, e, pvp, pvpbuf, size) char *rwset; char *p1; char *p2; ENVELOPE *e; char ***pvp; char *pvpbuf; int size; { char *volatile buf; size_t bufsize; int volatile rstat = EX_OK; int rsno; bool saveQuickAbort = QuickAbort; bool saveSuprErrs = SuprErrs; char buf0[MAXLINE]; extern char MsgBuf[]; if (tTd(48, 2)) sm_dprintf("rscap(%s, %s, %s)\n", rwset, p1, p2 == NULL ? "(NULL)" : p2); SM_REQUIRE(pvp != NULL); rsno = strtorwset(rwset, NULL, ST_FIND); if (rsno < 0) return EX_UNAVAILABLE; if (p2 != NULL) { bufsize = strlen(p1) + strlen(p2) + 2; if (bufsize > sizeof(buf0)) buf = sm_malloc_x(bufsize); else { buf = buf0; bufsize = sizeof(buf0); } (void) sm_snprintf(buf, bufsize, "%s%c%s", p1, CONDELSE, p2); } else { bufsize = strlen(p1) + 1; if (bufsize > sizeof(buf0)) buf = sm_malloc_x(bufsize); else { buf = buf0; bufsize = sizeof(buf0); } (void) sm_strlcpy(buf, p1, bufsize); } SM_TRY { SuprErrs = true; QuickAbort = false; *pvp = prescan(buf, '\0', pvpbuf, size, NULL, IntTokenTab, false); if (*pvp != NULL) rstat = rewrite(*pvp, rsno, 0, e, size); else { if (tTd(48, 2)) sm_dprintf("rscap: cannot prescan input\n"); rstat = EX_DATAERR; } } SM_FINALLY { /* clean up */ if (buf != buf0) sm_free(buf); SuprErrs = saveSuprErrs; QuickAbort = saveQuickAbort; /* prevent information leak, this may contain rewrite error */ MsgBuf[0] = '\0'; } SM_END_TRY return rstat; } Index: head/contrib/sendmail/src/queue.c =================================================================== --- head/contrib/sendmail/src/queue.c (revision 249728) +++ head/contrib/sendmail/src/queue.c (revision 249729) @@ -1,8954 +1,8954 @@ /* * Copyright (c) 1998-2009, 2011, 2012 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include #include -SM_RCSID("@(#)$Id: queue.c,v 8.997 2012/06/14 23:54:03 ca Exp $") +SM_RCSID("@(#)$Id: queue.c,v 8.998 2013/03/12 15:24:53 ca Exp $") #include # define RELEASE_QUEUE (void) 0 # define ST_INODE(st) (st).st_ino # define sm_file_exists(errno) ((errno) == EEXIST) # if HASFLOCK && defined(O_EXLOCK) # define SM_OPEN_EXLOCK 1 # define TF_OPEN_FLAGS (O_CREAT|O_WRONLY|O_EXCL|O_EXLOCK) # else /* HASFLOCK && defined(O_EXLOCK) */ # define TF_OPEN_FLAGS (O_CREAT|O_WRONLY|O_EXCL) # endif /* HASFLOCK && defined(O_EXLOCK) */ #ifndef SM_OPEN_EXLOCK # define SM_OPEN_EXLOCK 0 #endif /* ! SM_OPEN_EXLOCK */ /* ** Historical notes: ** QF_VERSION == 4 was sendmail 8.10/8.11 without _FFR_QUEUEDELAY ** QF_VERSION == 5 was sendmail 8.10/8.11 with _FFR_QUEUEDELAY ** QF_VERSION == 6 was sendmail 8.12 without _FFR_QUEUEDELAY ** QF_VERSION == 7 was sendmail 8.12 with _FFR_QUEUEDELAY ** QF_VERSION == 8 is sendmail 8.13 */ #define QF_VERSION 8 /* version number of this queue format */ static char queue_letter __P((ENVELOPE *, int)); static bool quarantine_queue_item __P((int, int, ENVELOPE *, char *)); /* Naming convention: qgrp: index of queue group, qg: QUEUEGROUP */ /* ** Work queue. */ struct work { char *w_name; /* name of control file */ char *w_host; /* name of recipient host */ bool w_lock; /* is message locked? */ bool w_tooyoung; /* is it too young to run? */ long w_pri; /* priority of message, see below */ time_t w_ctime; /* creation time */ time_t w_mtime; /* modification time */ int w_qgrp; /* queue group located in */ int w_qdir; /* queue directory located in */ struct work *w_next; /* next in queue */ }; typedef struct work WORK; static WORK *WorkQ; /* queue of things to be done */ static int NumWorkGroups; /* number of work groups */ static time_t Current_LA_time = 0; /* Get new load average every 30 seconds. */ #define GET_NEW_LA_TIME 30 #define SM_GET_LA(now) \ do \ { \ now = curtime(); \ if (Current_LA_time < now - GET_NEW_LA_TIME) \ { \ sm_getla(); \ Current_LA_time = now; \ } \ } while (0) /* ** DoQueueRun indicates that a queue run is needed. ** Notice: DoQueueRun is modified in a signal handler! */ static bool volatile DoQueueRun; /* non-interrupt time queue run needed */ /* ** Work group definition structure. ** Each work group contains one or more queue groups. This is done ** to manage the number of queue group runners active at the same time ** to be within the constraints of MaxQueueChildren (if it is set). ** The number of queue groups that can be run on the next work run ** is kept track of. The queue groups are run in a round robin. */ struct workgrp { int wg_numqgrp; /* number of queue groups in work grp */ int wg_runners; /* total runners */ int wg_curqgrp; /* current queue group */ QUEUEGRP **wg_qgs; /* array of queue groups */ int wg_maxact; /* max # of active runners */ time_t wg_lowqintvl; /* lowest queue interval */ int wg_restart; /* needs restarting? */ int wg_restartcnt; /* count of times restarted */ }; typedef struct workgrp WORKGRP; static WORKGRP volatile WorkGrp[MAXWORKGROUPS + 1]; /* work groups */ #if SM_HEAP_CHECK static SM_DEBUG_T DebugLeakQ = SM_DEBUG_INITIALIZER("leak_q", "@(#)$Debug: leak_q - trace memory leaks during queue processing $"); #endif /* SM_HEAP_CHECK */ /* ** We use EmptyString instead of "" to avoid ** 'zero-length format string' warnings from gcc */ static const char EmptyString[] = ""; static void grow_wlist __P((int, int)); static int multiqueue_cache __P((char *, int, QUEUEGRP *, int, unsigned int *)); static int gatherq __P((int, int, bool, bool *, bool *, int *)); static int sortq __P((int)); static void printctladdr __P((ADDRESS *, SM_FILE_T *)); static bool readqf __P((ENVELOPE *, bool)); static void restart_work_group __P((int)); static void runner_work __P((ENVELOPE *, int, bool, int, int)); static void schedule_queue_runs __P((bool, int, bool)); static char *strrev __P((char *)); static ADDRESS *setctluser __P((char *, int, ENVELOPE *)); #if _FFR_RHS static int sm_strshufflecmp __P((char *, char *)); static void init_shuffle_alphabet __P(()); #endif /* _FFR_RHS */ /* ** Note: workcmpf?() don't use a prototype because it will cause a conflict ** with the qsort() call (which expects something like ** int (*compar)(const void *, const void *), not (WORK *, WORK *)) */ static int workcmpf0(); static int workcmpf1(); static int workcmpf2(); static int workcmpf3(); static int workcmpf4(); static int randi = 3; /* index for workcmpf5() */ static int workcmpf5(); static int workcmpf6(); #if _FFR_RHS static int workcmpf7(); #endif /* _FFR_RHS */ #if RANDOMSHIFT # define get_rand_mod(m) ((get_random() >> RANDOMSHIFT) % (m)) #else /* RANDOMSHIFT */ # define get_rand_mod(m) (get_random() % (m)) #endif /* RANDOMSHIFT */ /* ** File system definition. ** Used to keep track of how much free space is available ** on a file system in which one or more queue directories reside. */ typedef struct filesys_shared FILESYS; struct filesys_shared { dev_t fs_dev; /* unique device id */ long fs_avail; /* number of free blocks available */ long fs_blksize; /* block size, in bytes */ }; /* probably kept in shared memory */ static FILESYS FileSys[MAXFILESYS]; /* queue file systems */ static const char *FSPath[MAXFILESYS]; /* pathnames for file systems */ #if SM_CONF_SHM /* ** Shared memory data ** ** Current layout: ** size -- size of shared memory segment ** pid -- pid of owner, should be a unique id to avoid misinterpretations ** by other processes. ** tag -- should be a unique id to avoid misinterpretations by others. ** idea: hash over configuration data that will be stored here. ** NumFileSys -- number of file systems. ** FileSys -- (array of) structure for used file systems. ** RSATmpCnt -- counter for number of uses of ephemeral RSA key. ** QShm -- (array of) structure for information about queue directories. */ /* ** Queue data in shared memory */ typedef struct queue_shared QUEUE_SHM_T; struct queue_shared { int qs_entries; /* number of entries */ /* XXX more to follow? */ }; static void *Pshm; /* pointer to shared memory */ static FILESYS *PtrFileSys; /* pointer to queue file system array */ int ShmId = SM_SHM_NO_ID; /* shared memory id */ static QUEUE_SHM_T *QShm; /* pointer to shared queue data */ static size_t shms; # define SHM_OFF_PID(p) (((char *) (p)) + sizeof(int)) # define SHM_OFF_TAG(p) (((char *) (p)) + sizeof(pid_t) + sizeof(int)) # define SHM_OFF_HEAD (sizeof(pid_t) + sizeof(int) * 2) /* how to access FileSys */ # define FILE_SYS(i) (PtrFileSys[i]) /* first entry is a tag, for now just the size */ # define OFF_FILE_SYS(p) (((char *) (p)) + SHM_OFF_HEAD) /* offset for PNumFileSys */ # define OFF_NUM_FILE_SYS(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys)) /* offset for PRSATmpCnt */ # define OFF_RSA_TMP_CNT(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int)) int *PRSATmpCnt; /* offset for queue_shm */ # define OFF_QUEUE_SHM(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int) * 2) # define QSHM_ENTRIES(i) QShm[i].qs_entries /* basic size of shared memory segment */ # define SM_T_SIZE (SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int) * 2) static unsigned int hash_q __P((char *, unsigned int)); /* ** HASH_Q -- simple hash function ** ** Parameters: ** p -- string to hash. ** h -- hash start value (from previous run). ** ** Returns: ** hash value. */ static unsigned int hash_q(p, h) char *p; unsigned int h; { int c, d; while (*p != '\0') { d = *p++; c = d; c ^= c<<6; h += (c<<11) ^ (c>>1); h ^= (d<<14) + (d<<7) + (d<<4) + d; } return h; } #else /* SM_CONF_SHM */ # define FILE_SYS(i) FileSys[i] #endif /* SM_CONF_SHM */ /* access to the various components of file system data */ #define FILE_SYS_NAME(i) FSPath[i] #define FILE_SYS_AVAIL(i) FILE_SYS(i).fs_avail #define FILE_SYS_BLKSIZE(i) FILE_SYS(i).fs_blksize #define FILE_SYS_DEV(i) FILE_SYS(i).fs_dev /* ** Current qf file field assignments: ** ** A AUTH= parameter ** B body type ** C controlling user ** D data file name ** d data file directory name (added in 8.12) ** E error recipient ** F flag bits ** G free (was: queue delay algorithm if _FFR_QUEUEDELAY) ** H header ** I data file's inode number ** K time of last delivery attempt ** L Solaris Content-Length: header (obsolete) ** M message ** N number of delivery attempts ** P message priority ** q quarantine reason ** Q original recipient (ORCPT=) ** r final recipient (Final-Recipient: DSN field) ** R recipient ** S sender ** T init time ** V queue file version ** X free (was: character set if _FFR_SAVE_CHARSET) ** Y free (was: current delay if _FFR_QUEUEDELAY) ** Z original envelope id from ESMTP ** ! deliver by (added in 8.12) ** $ define macro ** . terminate file */ /* ** QUEUEUP -- queue a message up for future transmission. ** ** Parameters: ** e -- the envelope to queue up. ** announce -- if true, tell when you are queueing up. ** msync -- if true, then fsync() if SuperSafe interactive mode. ** ** Returns: ** none. ** ** Side Effects: ** The current request is saved in a control file. ** The queue file is left locked. */ void queueup(e, announce, msync) register ENVELOPE *e; bool announce; bool msync; { register SM_FILE_T *tfp; register HDR *h; register ADDRESS *q; int tfd = -1; int i; bool newid; register char *p; MAILER nullmailer; MCI mcibuf; char qf[MAXPATHLEN]; char tf[MAXPATHLEN]; char df[MAXPATHLEN]; char buf[MAXLINE]; /* ** Create control file. */ #define OPEN_TF do \ { \ MODE_T oldumask = 0; \ \ if (bitset(S_IWGRP, QueueFileMode)) \ oldumask = umask(002); \ tfd = open(tf, TF_OPEN_FLAGS, QueueFileMode); \ if (bitset(S_IWGRP, QueueFileMode)) \ (void) umask(oldumask); \ } while (0) newid = (e->e_id == NULL) || !bitset(EF_INQUEUE, e->e_flags); (void) sm_strlcpy(tf, queuename(e, NEWQFL_LETTER), sizeof(tf)); tfp = e->e_lockfp; if (tfp == NULL && newid) { /* ** open qf file directly: this will give an error if the file ** already exists and hence prevent problems if a queue-id ** is reused (e.g., because the clock is set back). */ (void) sm_strlcpy(tf, queuename(e, ANYQFL_LETTER), sizeof(tf)); OPEN_TF; if (tfd < 0 || #if !SM_OPEN_EXLOCK !lockfile(tfd, tf, NULL, LOCK_EX|LOCK_NB) || #endif /* !SM_OPEN_EXLOCK */ (tfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &tfd, SM_IO_WRONLY, NULL)) == NULL) { int save_errno = errno; printopenfds(true); errno = save_errno; syserr("!queueup: cannot create queue file %s, euid=%d, fd=%d, fp=%p", tf, (int) geteuid(), tfd, tfp); /* NOTREACHED */ } e->e_lockfp = tfp; upd_qs(e, 1, 0, "queueup"); } /* if newid, write the queue file directly (instead of temp file) */ if (!newid) { /* get a locked tf file */ for (i = 0; i < 128; i++) { if (tfd < 0) { OPEN_TF; if (tfd < 0) { if (errno != EEXIST) break; if (LogLevel > 0 && (i % 32) == 0) sm_syslog(LOG_ALERT, e->e_id, "queueup: cannot create %s, euid=%d: %s", tf, (int) geteuid(), sm_errstring(errno)); } #if SM_OPEN_EXLOCK else break; #endif /* SM_OPEN_EXLOCK */ } if (tfd >= 0) { #if SM_OPEN_EXLOCK /* file is locked by open() */ break; #else /* SM_OPEN_EXLOCK */ if (lockfile(tfd, tf, NULL, LOCK_EX|LOCK_NB)) break; else #endif /* SM_OPEN_EXLOCK */ if (LogLevel > 0 && (i % 32) == 0) sm_syslog(LOG_ALERT, e->e_id, "queueup: cannot lock %s: %s", tf, sm_errstring(errno)); if ((i % 32) == 31) { (void) close(tfd); tfd = -1; } } if ((i % 32) == 31) { /* save the old temp file away */ (void) rename(tf, queuename(e, TEMPQF_LETTER)); } else (void) sleep(i % 32); } if (tfd < 0 || (tfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &tfd, SM_IO_WRONLY_B, NULL)) == NULL) { int save_errno = errno; printopenfds(true); errno = save_errno; syserr("!queueup: cannot create queue temp file %s, uid=%d", tf, (int) geteuid()); } } if (tTd(40, 1)) sm_dprintf("\n>>>>> queueing %s/%s%s >>>>>\n", qid_printqueue(e->e_qgrp, e->e_qdir), queuename(e, ANYQFL_LETTER), newid ? " (new id)" : ""); if (tTd(40, 3)) { sm_dprintf(" e_flags="); printenvflags(e); } if (tTd(40, 32)) { sm_dprintf(" sendq="); printaddr(sm_debug_file(), e->e_sendqueue, true); } if (tTd(40, 9)) { sm_dprintf(" tfp="); dumpfd(sm_io_getinfo(tfp, SM_IO_WHAT_FD, NULL), true, false); sm_dprintf(" lockfp="); if (e->e_lockfp == NULL) sm_dprintf("NULL\n"); else dumpfd(sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL), true, false); } /* ** If there is no data file yet, create one. */ (void) sm_strlcpy(df, queuename(e, DATAFL_LETTER), sizeof(df)); if (bitset(EF_HAS_DF, e->e_flags)) { if (e->e_dfp != NULL && SuperSafe != SAFE_REALLY && SuperSafe != SAFE_REALLY_POSTMILTER && sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 && errno != EINVAL) { syserr("!queueup: cannot commit data file %s, uid=%d", queuename(e, DATAFL_LETTER), (int) geteuid()); } if (e->e_dfp != NULL && SuperSafe == SAFE_INTERACTIVE && msync) { if (tTd(40,32)) sm_syslog(LOG_INFO, e->e_id, "queueup: fsync(e->e_dfp)"); if (fsync(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL)) < 0) { if (newid) syserr("!552 Error writing data file %s", df); else syserr("!452 Error writing data file %s", df); } } } else { int dfd; MODE_T oldumask = 0; register SM_FILE_T *dfp = NULL; struct stat stbuf; if (e->e_dfp != NULL && sm_io_getinfo(e->e_dfp, SM_IO_WHAT_ISTYPE, BF_FILE_TYPE)) syserr("committing over bf file"); if (bitset(S_IWGRP, QueueFileMode)) oldumask = umask(002); dfd = open(df, O_WRONLY|O_CREAT|O_TRUNC|QF_O_EXTRA, QueueFileMode); if (bitset(S_IWGRP, QueueFileMode)) (void) umask(oldumask); if (dfd < 0 || (dfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &dfd, SM_IO_WRONLY_B, NULL)) == NULL) syserr("!queueup: cannot create data temp file %s, uid=%d", df, (int) geteuid()); if (fstat(dfd, &stbuf) < 0) e->e_dfino = -1; else { e->e_dfdev = stbuf.st_dev; e->e_dfino = ST_INODE(stbuf); } e->e_flags |= EF_HAS_DF; memset(&mcibuf, '\0', sizeof(mcibuf)); mcibuf.mci_out = dfp; mcibuf.mci_mailer = FileMailer; (*e->e_putbody)(&mcibuf, e, NULL); if (SuperSafe == SAFE_REALLY || SuperSafe == SAFE_REALLY_POSTMILTER || (SuperSafe == SAFE_INTERACTIVE && msync)) { if (tTd(40,32)) sm_syslog(LOG_INFO, e->e_id, "queueup: fsync(dfp)"); if (fsync(sm_io_getinfo(dfp, SM_IO_WHAT_FD, NULL)) < 0) { if (newid) syserr("!552 Error writing data file %s", df); else syserr("!452 Error writing data file %s", df); } } if (sm_io_close(dfp, SM_TIME_DEFAULT) < 0) syserr("!queueup: cannot save data temp file %s, uid=%d", df, (int) geteuid()); e->e_putbody = putbody; } /* ** Output future work requests. ** Priority and creation time should be first, since ** they are required by gatherq. */ /* output queue version number (must be first!) */ (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "V%d\n", QF_VERSION); /* output creation time */ (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "T%ld\n", (long) e->e_ctime); /* output last delivery time */ (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "K%ld\n", (long) e->e_dtime); /* output number of delivery attempts */ (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "N%d\n", e->e_ntries); /* output message priority */ (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "P%ld\n", e->e_msgpriority); /* ** If data file is in a different directory than the queue file, ** output a "d" record naming the directory of the data file. */ if (e->e_dfqgrp != e->e_qgrp) { (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "d%s\n", Queue[e->e_dfqgrp]->qg_qpaths[e->e_dfqdir].qp_name); } /* output inode number of data file */ if (e->e_dfino != -1) { (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "I%ld/%ld/%llu\n", (long) major(e->e_dfdev), (long) minor(e->e_dfdev), (ULONGLONG_T) e->e_dfino); } /* output body type */ if (e->e_bodytype != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "B%s\n", denlstring(e->e_bodytype, true, false)); /* quarantine reason */ if (e->e_quarmsg != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "q%s\n", denlstring(e->e_quarmsg, true, false)); /* message from envelope, if it exists */ if (e->e_message != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "M%s\n", denlstring(e->e_message, true, false)); /* send various flag bits through */ p = buf; if (bitset(EF_WARNING, e->e_flags)) *p++ = 'w'; if (bitset(EF_RESPONSE, e->e_flags)) *p++ = 'r'; if (bitset(EF_HAS8BIT, e->e_flags)) *p++ = '8'; if (bitset(EF_DELETE_BCC, e->e_flags)) *p++ = 'b'; if (bitset(EF_RET_PARAM, e->e_flags)) *p++ = 'd'; if (bitset(EF_NO_BODY_RETN, e->e_flags)) *p++ = 'n'; if (bitset(EF_SPLIT, e->e_flags)) *p++ = 's'; *p++ = '\0'; if (buf[0] != '\0') (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "F%s\n", buf); /* save $={persistentMacros} macro values */ queueup_macros(macid("{persistentMacros}"), tfp, e); /* output name of sender */ if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags)) p = e->e_sender; else p = e->e_from.q_paddr; (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "S%s\n", denlstring(p, true, false)); /* output ESMTP-supplied "original" information */ if (e->e_envid != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "Z%s\n", denlstring(e->e_envid, true, false)); /* output AUTH= parameter */ if (e->e_auth_param != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "A%s\n", denlstring(e->e_auth_param, true, false)); if (e->e_dlvr_flag != 0) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "!%c %ld\n", (char) e->e_dlvr_flag, e->e_deliver_by); /* output list of recipient addresses */ printctladdr(NULL, NULL); for (q = e->e_sendqueue; q != NULL; q = q->q_next) { if (!QS_IS_UNDELIVERED(q->q_state)) continue; /* message for this recipient, if it exists */ if (q->q_message != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "M%s\n", denlstring(q->q_message, true, false)); printctladdr(q, tfp); if (q->q_orcpt != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "Q%s\n", denlstring(q->q_orcpt, true, false)); if (q->q_finalrcpt != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "r%s\n", denlstring(q->q_finalrcpt, true, false)); (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'R'); if (bitset(QPRIMARY, q->q_flags)) (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'P'); if (bitset(QHASNOTIFY, q->q_flags)) (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'N'); if (bitset(QPINGONSUCCESS, q->q_flags)) (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'S'); if (bitset(QPINGONFAILURE, q->q_flags)) (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'F'); if (bitset(QPINGONDELAY, q->q_flags)) (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'D'); if (q->q_alias != NULL && bitset(QALIAS, q->q_alias->q_flags)) (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'A'); (void) sm_io_putc(tfp, SM_TIME_DEFAULT, ':'); (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s\n", denlstring(q->q_paddr, true, false)); if (announce) { char *tag = "queued"; if (e->e_quarmsg != NULL) tag = "quarantined"; e->e_to = q->q_paddr; message(tag); if (LogLevel > 8) logdelivery(q->q_mailer, NULL, q->q_status, tag, NULL, (time_t) 0, e); e->e_to = NULL; } if (tTd(40, 1)) { sm_dprintf("queueing "); printaddr(sm_debug_file(), q, false); } } /* ** Output headers for this message. ** Expand macros completely here. Queue run will deal with ** everything as absolute headers. ** All headers that must be relative to the recipient ** can be cracked later. ** We set up a "null mailer" -- i.e., a mailer that will have ** no effect on the addresses as they are output. */ memset((char *) &nullmailer, '\0', sizeof(nullmailer)); nullmailer.m_re_rwset = nullmailer.m_rh_rwset = nullmailer.m_se_rwset = nullmailer.m_sh_rwset = -1; nullmailer.m_eol = "\n"; memset(&mcibuf, '\0', sizeof(mcibuf)); mcibuf.mci_mailer = &nullmailer; mcibuf.mci_out = tfp; macdefine(&e->e_macro, A_PERM, 'g', "\201f"); for (h = e->e_header; h != NULL; h = h->h_link) { if (h->h_value == NULL) continue; /* don't output resent headers on non-resent messages */ if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags)) continue; /* expand macros; if null, don't output header at all */ if (bitset(H_DEFAULT, h->h_flags)) { (void) expand(h->h_value, buf, sizeof(buf), e); if (buf[0] == '\0') continue; if (buf[0] == ' ' && buf[1] == '\0') continue; } /* output this header */ (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "H?"); /* output conditional macro if present */ if (h->h_macro != '\0') { if (bitset(0200, h->h_macro)) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "${%s}", macname(bitidx(h->h_macro))); else (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "$%c", h->h_macro); } else if (!bitzerop(h->h_mflags) && bitset(H_CHECK|H_ACHECK, h->h_flags)) { int j; /* if conditional, output the set of conditions */ for (j = '\0'; j <= '\177'; j++) if (bitnset(j, h->h_mflags)) (void) sm_io_putc(tfp, SM_TIME_DEFAULT, j); } (void) sm_io_putc(tfp, SM_TIME_DEFAULT, '?'); /* output the header: expand macros, convert addresses */ if (bitset(H_DEFAULT, h->h_flags) && !bitset(H_BINDLATE, h->h_flags)) { (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s:%s\n", h->h_field, denlstring(buf, false, true)); } else if (bitset(H_FROM|H_RCPT, h->h_flags) && !bitset(H_BINDLATE, h->h_flags)) { bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags); SM_FILE_T *savetrace = TrafficLogFile; TrafficLogFile = NULL; if (bitset(H_FROM, h->h_flags)) oldstyle = false; commaize(h, h->h_value, oldstyle, &mcibuf, e, PXLF_HEADER); TrafficLogFile = savetrace; } else { (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s:%s\n", h->h_field, denlstring(h->h_value, false, true)); } } /* ** Clean up. ** ** Write a terminator record -- this is to prevent ** scurrilous crackers from appending any data. */ (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, ".\n"); if (sm_io_flush(tfp, SM_TIME_DEFAULT) != 0 || ((SuperSafe == SAFE_REALLY || SuperSafe == SAFE_REALLY_POSTMILTER || (SuperSafe == SAFE_INTERACTIVE && msync)) && fsync(sm_io_getinfo(tfp, SM_IO_WHAT_FD, NULL)) < 0) || sm_io_error(tfp)) { if (newid) syserr("!552 Error writing control file %s", tf); else syserr("!452 Error writing control file %s", tf); } if (!newid) { char new = queue_letter(e, ANYQFL_LETTER); /* rename (locked) tf to be (locked) [qh]f */ (void) sm_strlcpy(qf, queuename(e, ANYQFL_LETTER), sizeof(qf)); if (rename(tf, qf) < 0) syserr("cannot rename(%s, %s), uid=%d", tf, qf, (int) geteuid()); else { /* ** Check if type has changed and only ** remove the old item if the rename above ** succeeded. */ if (e->e_qfletter != '\0' && e->e_qfletter != new) { if (tTd(40, 5)) { sm_dprintf("type changed from %c to %c\n", e->e_qfletter, new); } if (unlink(queuename(e, e->e_qfletter)) < 0) { /* XXX: something more drastic? */ if (LogLevel > 0) sm_syslog(LOG_ERR, e->e_id, "queueup: unlink(%s) failed: %s", queuename(e, e->e_qfletter), sm_errstring(errno)); } } } e->e_qfletter = new; /* ** fsync() after renaming to make sure metadata is ** written to disk on filesystems in which renames are ** not guaranteed. */ if (SuperSafe != SAFE_NO) { /* for softupdates */ if (tfd >= 0 && fsync(tfd) < 0) { syserr("!queueup: cannot fsync queue temp file %s", tf); } SYNC_DIR(qf, true); } /* close and unlock old (locked) queue file */ if (e->e_lockfp != NULL) (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT); e->e_lockfp = tfp; /* save log info */ if (LogLevel > 79) sm_syslog(LOG_DEBUG, e->e_id, "queueup %s", qf); } else { /* save log info */ if (LogLevel > 79) sm_syslog(LOG_DEBUG, e->e_id, "queueup %s", tf); e->e_qfletter = queue_letter(e, ANYQFL_LETTER); } errno = 0; e->e_flags |= EF_INQUEUE; if (tTd(40, 1)) sm_dprintf("<<<<< done queueing %s <<<<<\n\n", e->e_id); return; } /* ** PRINTCTLADDR -- print control address to file. ** ** Parameters: ** a -- address. ** tfp -- file pointer. ** ** Returns: ** none. ** ** Side Effects: ** The control address (if changed) is printed to the file. ** The last control address and uid are saved. */ static void printctladdr(a, tfp) register ADDRESS *a; SM_FILE_T *tfp; { char *user; register ADDRESS *q; uid_t uid; gid_t gid; static ADDRESS *lastctladdr = NULL; static uid_t lastuid; /* initialization */ if (a == NULL || a->q_alias == NULL || tfp == NULL) { if (lastctladdr != NULL && tfp != NULL) (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C\n"); lastctladdr = NULL; lastuid = 0; return; } /* find the active uid */ q = getctladdr(a); if (q == NULL) { user = NULL; uid = 0; gid = 0; } else { user = q->q_ruser != NULL ? q->q_ruser : q->q_user; uid = q->q_uid; gid = q->q_gid; } a = a->q_alias; /* check to see if this is the same as last time */ if (lastctladdr != NULL && uid == lastuid && strcmp(lastctladdr->q_paddr, a->q_paddr) == 0) return; lastuid = uid; lastctladdr = a; if (uid == 0 || user == NULL || user[0] == '\0') (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C"); else (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C%s:%ld:%ld", denlstring(user, true, false), (long) uid, (long) gid); (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, ":%s\n", denlstring(a->q_paddr, true, false)); } /* ** RUNNERS_SIGTERM -- propagate a SIGTERM to queue runner process ** ** This propagates the signal to the child processes that are queue ** runners. This is for a queue runner "cleanup". After all of the ** child queue runner processes are signaled (it should be SIGTERM ** being the sig) then the old signal handler (Oldsh) is called ** to handle any cleanup set for this process (provided it is not ** SIG_DFL or SIG_IGN). The signal may not be handled immediately ** if the BlockOldsh flag is set. If the current process doesn't ** have a parent then handle the signal immediately, regardless of ** BlockOldsh. ** ** Parameters: ** sig -- the signal number being sent ** ** Returns: ** none. ** ** Side Effects: ** Sets the NoMoreRunners boolean to true to stop more runners ** from being started in runqueue(). ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ static bool volatile NoMoreRunners = false; static sigfunc_t Oldsh_term = SIG_DFL; static sigfunc_t Oldsh_hup = SIG_DFL; static sigfunc_t volatile Oldsh = SIG_DFL; static bool BlockOldsh = false; static int volatile Oldsig = 0; static SIGFUNC_DECL runners_sigterm __P((int)); static SIGFUNC_DECL runners_sighup __P((int)); static SIGFUNC_DECL runners_sigterm(sig) int sig; { int save_errno = errno; FIX_SYSV_SIGNAL(sig, runners_sigterm); errno = save_errno; CHECK_CRITICAL(sig); NoMoreRunners = true; Oldsh = Oldsh_term; Oldsig = sig; proc_list_signal(PROC_QUEUE, sig); if (!BlockOldsh || getppid() <= 1) { /* Check that a valid 'old signal handler' is callable */ if (Oldsh_term != SIG_DFL && Oldsh_term != SIG_IGN && Oldsh_term != runners_sigterm) (*Oldsh_term)(sig); } errno = save_errno; return SIGFUNC_RETURN; } /* ** RUNNERS_SIGHUP -- propagate a SIGHUP to queue runner process ** ** This propagates the signal to the child processes that are queue ** runners. This is for a queue runner "cleanup". After all of the ** child queue runner processes are signaled (it should be SIGHUP ** being the sig) then the old signal handler (Oldsh) is called to ** handle any cleanup set for this process (provided it is not SIG_DFL ** or SIG_IGN). The signal may not be handled immediately if the ** BlockOldsh flag is set. If the current process doesn't have ** a parent then handle the signal immediately, regardless of ** BlockOldsh. ** ** Parameters: ** sig -- the signal number being sent ** ** Returns: ** none. ** ** Side Effects: ** Sets the NoMoreRunners boolean to true to stop more runners ** from being started in runqueue(). ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ static SIGFUNC_DECL runners_sighup(sig) int sig; { int save_errno = errno; FIX_SYSV_SIGNAL(sig, runners_sighup); errno = save_errno; CHECK_CRITICAL(sig); NoMoreRunners = true; Oldsh = Oldsh_hup; Oldsig = sig; proc_list_signal(PROC_QUEUE, sig); if (!BlockOldsh || getppid() <= 1) { /* Check that a valid 'old signal handler' is callable */ if (Oldsh_hup != SIG_DFL && Oldsh_hup != SIG_IGN && Oldsh_hup != runners_sighup) (*Oldsh_hup)(sig); } errno = save_errno; return SIGFUNC_RETURN; } /* ** MARK_WORK_GROUP_RESTART -- mark a work group as needing a restart ** ** Sets a workgroup for restarting. ** ** Parameters: ** wgrp -- the work group id to restart. ** reason -- why (signal?), -1 to turn off restart ** ** Returns: ** none. ** ** Side effects: ** May set global RestartWorkGroup to true. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ void mark_work_group_restart(wgrp, reason) int wgrp; int reason; { if (wgrp < 0 || wgrp > NumWorkGroups) return; WorkGrp[wgrp].wg_restart = reason; if (reason >= 0) RestartWorkGroup = true; } /* ** RESTART_MARKED_WORK_GROUPS -- restart work groups marked as needing restart ** ** Restart any workgroup marked as needing a restart provided more ** runners are allowed. ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side effects: ** Sets global RestartWorkGroup to false. */ void restart_marked_work_groups() { int i; int wasblocked; if (NoMoreRunners) return; /* Block SIGCHLD so reapchild() doesn't mess with us */ wasblocked = sm_blocksignal(SIGCHLD); for (i = 0; i < NumWorkGroups; i++) { if (WorkGrp[i].wg_restart >= 0) { if (LogLevel > 8) sm_syslog(LOG_ERR, NOQID, "restart queue runner=%d due to signal 0x%x", i, WorkGrp[i].wg_restart); restart_work_group(i); } } RestartWorkGroup = false; if (wasblocked == 0) (void) sm_releasesignal(SIGCHLD); } /* ** RESTART_WORK_GROUP -- restart a specific work group ** ** Restart a specific workgroup provided more runners are allowed. ** If the requested work group has been restarted too many times log ** this and refuse to restart. ** ** Parameters: ** wgrp -- the work group id to restart ** ** Returns: ** none. ** ** Side Effects: ** starts another process doing the work of wgrp */ #define MAX_PERSIST_RESTART 10 /* max allowed number of restarts */ static void restart_work_group(wgrp) int wgrp; { if (NoMoreRunners || wgrp < 0 || wgrp > NumWorkGroups) return; WorkGrp[wgrp].wg_restart = -1; if (WorkGrp[wgrp].wg_restartcnt < MAX_PERSIST_RESTART) { /* avoid overflow; increment here */ WorkGrp[wgrp].wg_restartcnt++; (void) run_work_group(wgrp, RWG_FORK|RWG_PERSISTENT|RWG_RUNALL); } else { sm_syslog(LOG_ERR, NOQID, "ERROR: persistent queue runner=%d restarted too many times, queue runner lost", wgrp); } } /* ** SCHEDULE_QUEUE_RUNS -- schedule the next queue run for a work group. ** ** Parameters: ** runall -- schedule even if individual bit is not set. ** wgrp -- the work group id to schedule. ** didit -- the queue run was performed for this work group. ** ** Returns: ** nothing */ #define INCR_MOD(v, m) if (++v >= m) \ v = 0; \ else static void schedule_queue_runs(runall, wgrp, didit) bool runall; int wgrp; bool didit; { int qgrp, cgrp, endgrp; #if _FFR_QUEUE_SCHED_DBG time_t lastsched; bool sched; #endif /* _FFR_QUEUE_SCHED_DBG */ time_t now; time_t minqintvl; /* ** This is a bit ugly since we have to duplicate the ** code that "walks" through a work queue group. */ now = curtime(); minqintvl = 0; cgrp = endgrp = WorkGrp[wgrp].wg_curqgrp; do { time_t qintvl; #if _FFR_QUEUE_SCHED_DBG lastsched = 0; sched = false; #endif /* _FFR_QUEUE_SCHED_DBG */ qgrp = WorkGrp[wgrp].wg_qgs[cgrp]->qg_index; if (Queue[qgrp]->qg_queueintvl > 0) qintvl = Queue[qgrp]->qg_queueintvl; else if (QueueIntvl > 0) qintvl = QueueIntvl; else qintvl = (time_t) 0; #if _FFR_QUEUE_SCHED_DBG lastsched = Queue[qgrp]->qg_nextrun; #endif /* _FFR_QUEUE_SCHED_DBG */ if ((runall || Queue[qgrp]->qg_nextrun <= now) && qintvl > 0) { #if _FFR_QUEUE_SCHED_DBG sched = true; #endif /* _FFR_QUEUE_SCHED_DBG */ if (minqintvl == 0 || qintvl < minqintvl) minqintvl = qintvl; /* ** Only set a new time if a queue run was performed ** for this queue group. If the queue was not run, ** we could starve it by setting a new time on each ** call. */ if (didit) Queue[qgrp]->qg_nextrun += qintvl; } #if _FFR_QUEUE_SCHED_DBG if (tTd(69, 10)) sm_syslog(LOG_INFO, NOQID, "sqr: wgrp=%d, cgrp=%d, qgrp=%d, intvl=%ld, QI=%ld, runall=%d, lastrun=%ld, nextrun=%ld, sched=%d", wgrp, cgrp, qgrp, Queue[qgrp]->qg_queueintvl, QueueIntvl, runall, lastsched, Queue[qgrp]->qg_nextrun, sched); #endif /* _FFR_QUEUE_SCHED_DBG */ INCR_MOD(cgrp, WorkGrp[wgrp].wg_numqgrp); } while (endgrp != cgrp); if (minqintvl > 0) (void) sm_setevent(minqintvl, runqueueevent, 0); } #if _FFR_QUEUE_RUN_PARANOIA /* ** CHECKQUEUERUNNER -- check whether a queue group hasn't been run. ** ** Use this if events may get lost and hence queue runners may not ** be started and mail will pile up in a queue. ** ** Parameters: ** none. ** ** Returns: ** true if a queue run is necessary. ** ** Side Effects: ** may schedule a queue run. */ bool checkqueuerunner() { int qgrp; time_t now, minqintvl; now = curtime(); minqintvl = 0; for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; qgrp++) { time_t qintvl; if (Queue[qgrp]->qg_queueintvl > 0) qintvl = Queue[qgrp]->qg_queueintvl; else if (QueueIntvl > 0) qintvl = QueueIntvl; else qintvl = (time_t) 0; if (Queue[qgrp]->qg_nextrun <= now - qintvl) { if (minqintvl == 0 || qintvl < minqintvl) minqintvl = qintvl; if (LogLevel > 1) sm_syslog(LOG_WARNING, NOQID, "checkqueuerunner: queue %d should have been run at %s, queue interval %ld", qgrp, arpadate(ctime(&Queue[qgrp]->qg_nextrun)), qintvl); } } if (minqintvl > 0) { (void) sm_setevent(minqintvl, runqueueevent, 0); return true; } return false; } #endif /* _FFR_QUEUE_RUN_PARANOIA */ /* ** RUNQUEUE -- run the jobs in the queue. ** ** Gets the stuff out of the queue in some presumably logical ** order and processes them. ** ** Parameters: ** forkflag -- true if the queue scanning should be done in ** a child process. We double-fork so it is not our ** child and we don't have to clean up after it. ** false can be ignored if we have multiple queues. ** verbose -- if true, print out status information. ** persistent -- persistent queue runner? ** runall -- run all groups or only a subset (DoQueueRun)? ** ** Returns: ** true if the queue run successfully began. ** ** Side Effects: ** runs things in the mail queue using run_work_group(). ** maybe schedules next queue run. */ static ENVELOPE QueueEnvelope; /* the queue run envelope */ static time_t LastQueueTime = 0; /* last time a queue ID assigned */ static pid_t LastQueuePid = -1; /* last PID which had a queue ID */ /* values for qp_supdirs */ #define QP_NOSUB 0x0000 /* No subdirectories */ #define QP_SUBDF 0x0001 /* "df" subdirectory */ #define QP_SUBQF 0x0002 /* "qf" subdirectory */ #define QP_SUBXF 0x0004 /* "xf" subdirectory */ bool runqueue(forkflag, verbose, persistent, runall) bool forkflag; bool verbose; bool persistent; bool runall; { int i; bool ret = true; static int curnum = 0; sigfunc_t cursh; #if SM_HEAP_CHECK SM_NONVOLATILE int oldgroup = 0; if (sm_debug_active(&DebugLeakQ, 1)) { oldgroup = sm_heap_group(); sm_heap_newgroup(); sm_dprintf("runqueue() heap group #%d\n", sm_heap_group()); } #endif /* SM_HEAP_CHECK */ /* queue run has been started, don't do any more this time */ DoQueueRun = false; /* more than one queue or more than one directory per queue */ if (!forkflag && !verbose && (WorkGrp[0].wg_qgs[0]->qg_numqueues > 1 || NumWorkGroups > 1 || WorkGrp[0].wg_numqgrp > 1)) forkflag = true; /* ** For controlling queue runners via signals sent to this process. ** Oldsh* will get called too by runners_sig* (if it is not SIG_IGN ** or SIG_DFL) to preserve cleanup behavior. Now that this process ** will have children (and perhaps grandchildren) this handler will ** be left in place. This is because this process, once it has ** finished spinning off queue runners, may go back to doing something ** else (like being a daemon). And we still want on a SIG{TERM,HUP} to ** clean up the child queue runners. Only install 'runners_sig*' once ** else we'll get stuck looping forever. */ cursh = sm_signal(SIGTERM, runners_sigterm); if (cursh != runners_sigterm) Oldsh_term = cursh; cursh = sm_signal(SIGHUP, runners_sighup); if (cursh != runners_sighup) Oldsh_hup = cursh; for (i = 0; i < NumWorkGroups && !NoMoreRunners; i++) { int rwgflags = RWG_NONE; int wasblocked; /* ** If MaxQueueChildren active then test whether the start ** of the next queue group's additional queue runners (maximum) ** will result in MaxQueueChildren being exceeded. ** ** Note: do not use continue; even though another workgroup ** may have fewer queue runners, this would be "unfair", ** i.e., this work group might "starve" then. */ #if _FFR_QUEUE_SCHED_DBG if (tTd(69, 10)) sm_syslog(LOG_INFO, NOQID, "rq: curnum=%d, MaxQueueChildren=%d, CurRunners=%d, WorkGrp[curnum].wg_maxact=%d", curnum, MaxQueueChildren, CurRunners, WorkGrp[curnum].wg_maxact); #endif /* _FFR_QUEUE_SCHED_DBG */ if (MaxQueueChildren > 0 && CurRunners + WorkGrp[curnum].wg_maxact > MaxQueueChildren) break; /* ** Pick up where we left off (curnum), in case we ** used up all the children last time without finishing. ** This give a round-robin fairness to queue runs. ** ** Increment CurRunners before calling run_work_group() ** to avoid a "race condition" with proc_list_drop() which ** decrements CurRunners if the queue runners terminate. ** Notice: CurRunners is an upper limit, in some cases ** (too few jobs in the queue) this value is larger than ** the actual number of queue runners. The discrepancy can ** increase if some queue runners "hang" for a long time. */ /* don't let proc_list_drop() change CurRunners */ wasblocked = sm_blocksignal(SIGCHLD); CurRunners += WorkGrp[curnum].wg_maxact; if (wasblocked == 0) (void) sm_releasesignal(SIGCHLD); if (forkflag) rwgflags |= RWG_FORK; if (verbose) rwgflags |= RWG_VERBOSE; if (persistent) rwgflags |= RWG_PERSISTENT; if (runall) rwgflags |= RWG_RUNALL; ret = run_work_group(curnum, rwgflags); /* ** Failure means a message was printed for ETRN ** and subsequent queues are likely to fail as well. ** Decrement CurRunners in that case because ** none have been started. */ if (!ret) { /* don't let proc_list_drop() change CurRunners */ wasblocked = sm_blocksignal(SIGCHLD); CurRunners -= WorkGrp[curnum].wg_maxact; CHK_CUR_RUNNERS("runqueue", curnum, WorkGrp[curnum].wg_maxact); if (wasblocked == 0) (void) sm_releasesignal(SIGCHLD); break; } if (!persistent) schedule_queue_runs(runall, curnum, true); INCR_MOD(curnum, NumWorkGroups); } /* schedule left over queue runs */ if (i < NumWorkGroups && !NoMoreRunners && !persistent) { int h; for (h = curnum; i < NumWorkGroups; i++) { schedule_queue_runs(runall, h, false); INCR_MOD(h, NumWorkGroups); } } #if SM_HEAP_CHECK if (sm_debug_active(&DebugLeakQ, 1)) sm_heap_setgroup(oldgroup); #endif /* SM_HEAP_CHECK */ return ret; } #if _FFR_SKIP_DOMAINS /* ** SKIP_DOMAINS -- Skip 'skip' number of domains in the WorkQ. ** ** Added by Stephen Frost to support ** having each runner process every N'th domain instead of ** every N'th message. ** ** Parameters: ** skip -- number of domains in WorkQ to skip. ** ** Returns: ** total number of messages skipped. ** ** Side Effects: ** may change WorkQ */ static int skip_domains(skip) int skip; { int n, seqjump; for (n = 0, seqjump = 0; n < skip && WorkQ != NULL; seqjump++) { if (WorkQ->w_next != NULL) { if (WorkQ->w_host != NULL && WorkQ->w_next->w_host != NULL) { if (sm_strcasecmp(WorkQ->w_host, WorkQ->w_next->w_host) != 0) n++; } else { if ((WorkQ->w_host != NULL && WorkQ->w_next->w_host == NULL) || (WorkQ->w_host == NULL && WorkQ->w_next->w_host != NULL)) n++; } } WorkQ = WorkQ->w_next; } return seqjump; } #endif /* _FFR_SKIP_DOMAINS */ /* ** RUNNER_WORK -- have a queue runner do its work ** ** Have a queue runner do its work a list of entries. ** When work isn't directly being done then this process can take a signal ** and terminate immediately (in a clean fashion of course). ** When work is directly being done, it's not to be interrupted ** immediately: the work should be allowed to finish at a clean point ** before termination (in a clean fashion of course). ** ** Parameters: ** e -- envelope. ** sequenceno -- 'th process to run WorkQ. ** didfork -- did the calling process fork()? ** skip -- process only each skip'th item. ** njobs -- number of jobs in WorkQ. ** ** Returns: ** none. ** ** Side Effects: ** runs things in the mail queue. */ static void runner_work(e, sequenceno, didfork, skip, njobs) register ENVELOPE *e; int sequenceno; bool didfork; int skip; int njobs; { int n, seqjump; WORK *w; time_t now; SM_GET_LA(now); /* ** Here we temporarily block the second calling of the handlers. ** This allows us to handle the signal without terminating in the ** middle of direct work. If a signal does come, the test for ** NoMoreRunners will find it. */ BlockOldsh = true; seqjump = skip; /* process them once at a time */ while (WorkQ != NULL) { #if SM_HEAP_CHECK SM_NONVOLATILE int oldgroup = 0; if (sm_debug_active(&DebugLeakQ, 1)) { oldgroup = sm_heap_group(); sm_heap_newgroup(); sm_dprintf("run_queue_group() heap group #%d\n", sm_heap_group()); } #endif /* SM_HEAP_CHECK */ /* do no more work */ if (NoMoreRunners) { /* Check that a valid signal handler is callable */ if (Oldsh != SIG_DFL && Oldsh != SIG_IGN && Oldsh != runners_sighup && Oldsh != runners_sigterm) (*Oldsh)(Oldsig); break; } w = WorkQ; /* assign current work item */ /* ** Set the head of the WorkQ to the next work item. ** It is set 'skip' ahead (the number of parallel queue ** runners working on WorkQ together) since each runner ** works on every 'skip'th (N-th) item. #if _FFR_SKIP_DOMAINS ** In the case of the BYHOST Queue Sort Order, the 'item' ** is a domain, so we work on every 'skip'th (N-th) domain. #endif * _FFR_SKIP_DOMAINS * */ #if _FFR_SKIP_DOMAINS if (QueueSortOrder == QSO_BYHOST) { seqjump = 1; if (WorkQ->w_next != NULL) { if (WorkQ->w_host != NULL && WorkQ->w_next->w_host != NULL) { if (sm_strcasecmp(WorkQ->w_host, WorkQ->w_next->w_host) != 0) seqjump = skip_domains(skip); else WorkQ = WorkQ->w_next; } else { if ((WorkQ->w_host != NULL && WorkQ->w_next->w_host == NULL) || (WorkQ->w_host == NULL && WorkQ->w_next->w_host != NULL)) seqjump = skip_domains(skip); else WorkQ = WorkQ->w_next; } } else WorkQ = WorkQ->w_next; } else #endif /* _FFR_SKIP_DOMAINS */ { for (n = 0; n < skip && WorkQ != NULL; n++) WorkQ = WorkQ->w_next; } e->e_to = NULL; /* ** Ignore jobs that are too expensive for the moment. ** ** Get new load average every GET_NEW_LA_TIME seconds. */ SM_GET_LA(now); if (shouldqueue(WkRecipFact, Current_LA_time)) { char *msg = "Aborting queue run: load average too high"; if (Verbose) message("%s", msg); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, "runqueue: %s", msg); break; } if (shouldqueue(w->w_pri, w->w_ctime)) { if (Verbose) message(EmptyString); if (QueueSortOrder == QSO_BYPRIORITY) { if (Verbose) message("Skipping %s/%s (sequence %d of %d) and flushing rest of queue", qid_printqueue(w->w_qgrp, w->w_qdir), w->w_name + 2, sequenceno, njobs); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, "runqueue: Flushing queue from %s/%s (pri %ld, LA %d, %d of %d)", qid_printqueue(w->w_qgrp, w->w_qdir), w->w_name + 2, w->w_pri, CurrentLA, sequenceno, njobs); break; } else if (Verbose) message("Skipping %s/%s (sequence %d of %d)", qid_printqueue(w->w_qgrp, w->w_qdir), w->w_name + 2, sequenceno, njobs); } else { if (Verbose) { message(EmptyString); message("Running %s/%s (sequence %d of %d)", qid_printqueue(w->w_qgrp, w->w_qdir), w->w_name + 2, sequenceno, njobs); } if (didfork && MaxQueueChildren > 0) { sm_blocksignal(SIGCHLD); (void) sm_signal(SIGCHLD, reapchild); } if (tTd(63, 100)) sm_syslog(LOG_DEBUG, NOQID, "runqueue %s dowork(%s)", qid_printqueue(w->w_qgrp, w->w_qdir), w->w_name + 2); (void) dowork(w->w_qgrp, w->w_qdir, w->w_name + 2, ForkQueueRuns, false, e); errno = 0; } sm_free(w->w_name); /* XXX */ if (w->w_host != NULL) sm_free(w->w_host); /* XXX */ sm_free((char *) w); /* XXX */ sequenceno += seqjump; /* next sequence number */ #if SM_HEAP_CHECK if (sm_debug_active(&DebugLeakQ, 1)) sm_heap_setgroup(oldgroup); #endif /* SM_HEAP_CHECK */ } BlockOldsh = false; /* check the signals didn't happen during the revert */ if (NoMoreRunners) { /* Check that a valid signal handler is callable */ if (Oldsh != SIG_DFL && Oldsh != SIG_IGN && Oldsh != runners_sighup && Oldsh != runners_sigterm) (*Oldsh)(Oldsig); } Oldsh = SIG_DFL; /* after the NoMoreRunners check */ } /* ** RUN_WORK_GROUP -- run the jobs in a queue group from a work group. ** ** Gets the stuff out of the queue in some presumably logical ** order and processes them. ** ** Parameters: ** wgrp -- work group to process. ** flags -- RWG_* flags ** ** Returns: ** true if the queue run successfully began. ** ** Side Effects: ** runs things in the mail queue. */ /* Minimum sleep time for persistent queue runners */ #define MIN_SLEEP_TIME 5 bool run_work_group(wgrp, flags) int wgrp; int flags; { register ENVELOPE *e; int njobs, qdir; int sequenceno = 1; int qgrp, endgrp, h, i; time_t now; bool full, more; SM_RPOOL_T *rpool; extern ENVELOPE BlankEnvelope; extern SIGFUNC_DECL reapchild __P((int)); if (wgrp < 0) return false; /* ** If no work will ever be selected, don't even bother reading ** the queue. */ SM_GET_LA(now); if (!bitset(RWG_PERSISTENT, flags) && shouldqueue(WkRecipFact, Current_LA_time)) { char *msg = "Skipping queue run -- load average too high"; if (bitset(RWG_VERBOSE, flags)) message("458 %s\n", msg); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, "runqueue: %s", msg); return false; } /* ** See if we already have too many children. */ if (bitset(RWG_FORK, flags) && WorkGrp[wgrp].wg_lowqintvl > 0 && !bitset(RWG_PERSISTENT, flags) && MaxChildren > 0 && CurChildren >= MaxChildren) { char *msg = "Skipping queue run -- too many children"; if (bitset(RWG_VERBOSE, flags)) message("458 %s (%d)\n", msg, CurChildren); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, "runqueue: %s (%d)", msg, CurChildren); return false; } /* ** See if we want to go off and do other useful work. */ if (bitset(RWG_FORK, flags)) { pid_t pid; (void) sm_blocksignal(SIGCHLD); (void) sm_signal(SIGCHLD, reapchild); pid = dofork(); if (pid == -1) { const char *msg = "Skipping queue run -- fork() failed"; const char *err = sm_errstring(errno); if (bitset(RWG_VERBOSE, flags)) message("458 %s: %s\n", msg, err); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, "runqueue: %s: %s", msg, err); (void) sm_releasesignal(SIGCHLD); return false; } if (pid != 0) { /* parent -- pick up intermediate zombie */ (void) sm_blocksignal(SIGALRM); /* wgrp only used when queue runners are persistent */ proc_list_add(pid, "Queue runner", PROC_QUEUE, WorkGrp[wgrp].wg_maxact, bitset(RWG_PERSISTENT, flags) ? wgrp : -1, NULL); (void) sm_releasesignal(SIGALRM); (void) sm_releasesignal(SIGCHLD); return true; } /* child -- clean up signals */ /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; CurrentPid = getpid(); close_sendmail_pid(); /* ** Initialize exception stack and default exception ** handler for child process. */ sm_exc_newthread(fatal_error); clrcontrol(); proc_list_clear(); /* Add parent process as first child item */ proc_list_add(CurrentPid, "Queue runner child process", PROC_QUEUE_CHILD, 0, -1, NULL); (void) sm_releasesignal(SIGCHLD); (void) sm_signal(SIGCHLD, SIG_DFL); (void) sm_signal(SIGHUP, SIG_DFL); (void) sm_signal(SIGTERM, intsig); } /* ** Release any resources used by the daemon code. */ clrdaemon(); /* force it to run expensive jobs */ NoConnect = false; /* drop privileges */ if (geteuid() == (uid_t) 0) (void) drop_privileges(false); /* ** Create ourselves an envelope */ CurEnv = &QueueEnvelope; rpool = sm_rpool_new_x(NULL); e = newenvelope(&QueueEnvelope, CurEnv, rpool); e->e_flags = BlankEnvelope.e_flags; e->e_parent = NULL; /* make sure we have disconnected from parent */ if (bitset(RWG_FORK, flags)) { disconnect(1, e); QuickAbort = false; } /* ** If we are running part of the queue, always ignore stored ** host status. */ if (QueueLimitId != NULL || QueueLimitSender != NULL || QueueLimitQuarantine != NULL || QueueLimitRecipient != NULL) { IgnoreHostStatus = true; MinQueueAge = 0; #if _FFR_EXPDELAY MaxQueueAge = 0; #endif /* _FFR_EXPDELAY */ } /* ** Here is where we choose the queue group from the work group. ** The caller of the "domorework" label must setup a new envelope. */ endgrp = WorkGrp[wgrp].wg_curqgrp; /* to not spin endlessly */ domorework: /* ** Run a queue group if: ** RWG_RUNALL bit is set or the bit for this group is set. */ now = curtime(); for (;;) { /* ** Find the next queue group within the work group that ** has been marked as needing a run. */ qgrp = WorkGrp[wgrp].wg_qgs[WorkGrp[wgrp].wg_curqgrp]->qg_index; WorkGrp[wgrp].wg_curqgrp++; /* advance */ WorkGrp[wgrp].wg_curqgrp %= WorkGrp[wgrp].wg_numqgrp; /* wrap */ if (bitset(RWG_RUNALL, flags) || (Queue[qgrp]->qg_nextrun <= now && Queue[qgrp]->qg_nextrun != (time_t) -1)) break; if (endgrp == WorkGrp[wgrp].wg_curqgrp) { e->e_id = NULL; if (bitset(RWG_FORK, flags)) finis(true, true, ExitStat); return true; /* we're done */ } } qdir = Queue[qgrp]->qg_curnum; /* round-robin init of queue position */ #if _FFR_QUEUE_SCHED_DBG if (tTd(69, 12)) sm_syslog(LOG_INFO, NOQID, "rwg: wgrp=%d, qgrp=%d, qdir=%d, name=%s, curqgrp=%d, numgrps=%d", wgrp, qgrp, qdir, qid_printqueue(qgrp, qdir), WorkGrp[wgrp].wg_curqgrp, WorkGrp[wgrp].wg_numqgrp); #endif /* _FFR_QUEUE_SCHED_DBG */ #if HASNICE /* tweak niceness of queue runs */ if (Queue[qgrp]->qg_nice > 0) (void) nice(Queue[qgrp]->qg_nice); #endif /* HASNICE */ /* XXX running queue group... */ sm_setproctitle(true, CurEnv, "running queue: %s", qid_printqueue(qgrp, qdir)); if (LogLevel > 69 || tTd(63, 99)) sm_syslog(LOG_DEBUG, NOQID, "runqueue %s, pid=%d, forkflag=%d", qid_printqueue(qgrp, qdir), (int) CurrentPid, bitset(RWG_FORK, flags)); /* ** Start making passes through the queue. ** First, read and sort the entire queue. ** Then, process the work in that order. ** But if you take too long, start over. */ for (i = 0; i < Queue[qgrp]->qg_numqueues; i++) { (void) gatherq(qgrp, qdir, false, &full, &more, &h); #if SM_CONF_SHM if (ShmId != SM_SHM_NO_ID) QSHM_ENTRIES(Queue[qgrp]->qg_qpaths[qdir].qp_idx) = h; #endif /* SM_CONF_SHM */ /* If there are no more items in this queue advance */ if (!more) { /* A round-robin advance */ qdir++; qdir %= Queue[qgrp]->qg_numqueues; } /* Has the WorkList reached the limit? */ if (full) break; /* don't try to gather more */ } /* order the existing work requests */ njobs = sortq(Queue[qgrp]->qg_maxlist); Queue[qgrp]->qg_curnum = qdir; /* update */ if (!Verbose && bitnset(QD_FORK, Queue[qgrp]->qg_flags)) { int loop, maxrunners; pid_t pid; /* ** For this WorkQ we want to fork off N children (maxrunners) ** at this point. Each child has a copy of WorkQ. Each child ** will process every N-th item. The parent will wait for all ** of the children to finish before moving on to the next ** queue group within the work group. This saves us forking ** a new runner-child for each work item. ** It's valid for qg_maxqrun == 0 since this may be an ** explicit "don't run this queue" setting. */ maxrunners = Queue[qgrp]->qg_maxqrun; /* ** If no runners are configured for this group but ** the queue is "forced" then lets use 1 runner. */ if (maxrunners == 0 && bitset(RWG_FORCE, flags)) maxrunners = 1; /* No need to have more runners then there are jobs */ if (maxrunners > njobs) maxrunners = njobs; for (loop = 0; loop < maxrunners; loop++) { /* ** Since the delivery may happen in a child and the ** parent does not wait, the parent may close the ** maps thereby removing any shared memory used by ** the map. Therefore, close the maps now so the ** child will dynamically open them if necessary. */ closemaps(false); pid = fork(); if (pid < 0) { syserr("run_work_group: cannot fork"); return false; } else if (pid > 0) { /* parent -- clean out connection cache */ mci_flush(false, NULL); #if _FFR_SKIP_DOMAINS if (QueueSortOrder == QSO_BYHOST) { sequenceno += skip_domains(1); } else #endif /* _FFR_SKIP_DOMAINS */ { /* for the skip */ WorkQ = WorkQ->w_next; sequenceno++; } proc_list_add(pid, "Queue child runner process", PROC_QUEUE_CHILD, 0, -1, NULL); /* No additional work, no additional runners */ if (WorkQ == NULL) break; } else { /* child -- Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; CurrentPid = getpid(); close_sendmail_pid(); /* ** Initialize exception stack and default ** exception handler for child process. ** When fork()'d the child now has a private ** copy of WorkQ at its current position. */ sm_exc_newthread(fatal_error); /* ** SMTP processes (whether -bd or -bs) set ** SIGCHLD to reapchild to collect ** children status. However, at delivery ** time, that status must be collected ** by sm_wait() to be dealt with properly ** (check success of delivery based ** on status code, etc). Therefore, if we ** are an SMTP process, reset SIGCHLD ** back to the default so reapchild ** doesn't collect status before ** sm_wait(). */ if (OpMode == MD_SMTP || OpMode == MD_DAEMON || MaxQueueChildren > 0) { proc_list_clear(); sm_releasesignal(SIGCHLD); (void) sm_signal(SIGCHLD, SIG_DFL); } /* child -- error messages to the transcript */ QuickAbort = OnlyOneError = false; runner_work(e, sequenceno, true, maxrunners, njobs); /* This child is done */ finis(true, true, ExitStat); /* NOTREACHED */ } } sm_releasesignal(SIGCHLD); /* ** Wait until all of the runners have completed before ** seeing if there is another queue group in the ** work group to process. ** XXX Future enhancement: don't wait() for all children ** here, just go ahead and make sure that overall the number ** of children is not exceeded. */ while (CurChildren > 0) { int status; pid_t ret; while ((ret = sm_wait(&status)) <= 0) continue; proc_list_drop(ret, status, NULL); } } else if (Queue[qgrp]->qg_maxqrun > 0 || bitset(RWG_FORCE, flags)) { /* ** When current process will not fork children to do the work, ** it will do the work itself. The 'skip' will be 1 since ** there are no child runners to divide the work across. */ runner_work(e, sequenceno, false, 1, njobs); } /* free memory allocated by newenvelope() above */ sm_rpool_free(rpool); QueueEnvelope.e_rpool = NULL; /* Are there still more queues in the work group to process? */ if (endgrp != WorkGrp[wgrp].wg_curqgrp) { rpool = sm_rpool_new_x(NULL); e = newenvelope(&QueueEnvelope, CurEnv, rpool); e->e_flags = BlankEnvelope.e_flags; goto domorework; } /* No more queues in work group to process. Now check persistent. */ if (bitset(RWG_PERSISTENT, flags)) { sequenceno = 1; sm_setproctitle(true, NULL, "running queue: %s", qid_printqueue(qgrp, qdir)); /* ** close bogus maps, i.e., maps which caused a tempfail, ** so we get fresh map connections on the next lookup. ** closemaps() is also called when children are started. */ closemaps(true); /* Close any cached connections. */ mci_flush(true, NULL); /* Clean out expired related entries. */ rmexpstab(); #if NAMED_BIND /* Update MX records for FallbackMX. */ if (FallbackMX != NULL) (void) getfallbackmxrr(FallbackMX); #endif /* NAMED_BIND */ #if USERDB /* close UserDatabase */ _udbx_close(); #endif /* USERDB */ #if SM_HEAP_CHECK if (sm_debug_active(&SmHeapCheck, 2) && access("memdump", F_OK) == 0 ) { SM_FILE_T *out; remove("memdump"); out = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, "memdump.out", SM_IO_APPEND, NULL); if (out != NULL) { (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "----------------------\n"); sm_heap_report(out, sm_debug_level(&SmHeapCheck) - 1); (void) sm_io_close(out, SM_TIME_DEFAULT); } } #endif /* SM_HEAP_CHECK */ /* let me rest for a second to catch my breath */ if (njobs == 0 && WorkGrp[wgrp].wg_lowqintvl < MIN_SLEEP_TIME) sleep(MIN_SLEEP_TIME); else if (WorkGrp[wgrp].wg_lowqintvl <= 0) sleep(QueueIntvl > 0 ? QueueIntvl : MIN_SLEEP_TIME); else sleep(WorkGrp[wgrp].wg_lowqintvl); /* ** Get the LA outside the WorkQ loop if necessary. ** In a persistent queue runner the code is repeated over ** and over but gatherq() may ignore entries due to ** shouldqueue() (do we really have to do this twice?). ** Hence the queue runners would just idle around when once ** CurrentLA caused all entries in a queue to be ignored. */ if (njobs == 0) SM_GET_LA(now); rpool = sm_rpool_new_x(NULL); e = newenvelope(&QueueEnvelope, CurEnv, rpool); e->e_flags = BlankEnvelope.e_flags; goto domorework; } /* exit without the usual cleanup */ e->e_id = NULL; if (bitset(RWG_FORK, flags)) finis(true, true, ExitStat); /* NOTREACHED */ return true; } /* ** DOQUEUERUN -- do a queue run? */ bool doqueuerun() { return DoQueueRun; } /* ** RUNQUEUEEVENT -- Sets a flag to indicate that a queue run should be done. ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** The invocation of this function via an alarm may interrupt ** a set of actions. Thus errno may be set in that context. ** We need to restore errno at the end of this function to ensure ** that any work done here that sets errno doesn't return a ** misleading/false errno value. Errno may be EINTR upon entry to ** this function because of non-restartable/continuable system ** API was active. Iff this is true we will override errno as ** a timeout (as a more accurate error message). ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ void runqueueevent(ignore) int ignore; { int save_errno = errno; /* ** Set the general bit that we want a queue run, ** tested in doqueuerun() */ DoQueueRun = true; #if _FFR_QUEUE_SCHED_DBG if (tTd(69, 10)) sm_syslog(LOG_INFO, NOQID, "rqe: done"); #endif /* _FFR_QUEUE_SCHED_DBG */ errno = save_errno; if (errno == EINTR) errno = ETIMEDOUT; } /* ** GATHERQ -- gather messages from the message queue(s) the work queue. ** ** Parameters: ** qgrp -- the index of the queue group. ** qdir -- the index of the queue directory. ** doall -- if set, include everything in the queue (even ** the jobs that cannot be run because the load ** average is too high, or MaxQueueRun is reached). ** Otherwise, exclude those jobs. ** full -- (optional) to be set 'true' if WorkList is full ** more -- (optional) to be set 'true' if there are still more ** messages in this queue not added to WorkList ** pnentries -- (optional) total nuber of entries in queue ** ** Returns: ** The number of request in the queue (not necessarily ** the number of requests in WorkList however). ** ** Side Effects: ** prepares available work into WorkList */ #define NEED_P 0001 /* 'P': priority */ #define NEED_T 0002 /* 'T': time */ #define NEED_R 0004 /* 'R': recipient */ #define NEED_S 0010 /* 'S': sender */ #define NEED_H 0020 /* host */ #define HAS_QUARANTINE 0040 /* has an unexpected 'q' line */ #define NEED_QUARANTINE 0100 /* 'q': reason */ static WORK *WorkList = NULL; /* list of unsort work */ static int WorkListSize = 0; /* current max size of WorkList */ static int WorkListCount = 0; /* # of work items in WorkList */ static int gatherq(qgrp, qdir, doall, full, more, pnentries) int qgrp; int qdir; bool doall; bool *full; bool *more; int *pnentries; { register struct dirent *d; register WORK *w; register char *p; DIR *f; int i, num_ent, wn, nentries; QUEUE_CHAR *check; char qd[MAXPATHLEN]; char qf[MAXPATHLEN]; wn = WorkListCount - 1; num_ent = 0; nentries = 0; if (qdir == NOQDIR) (void) sm_strlcpy(qd, ".", sizeof(qd)); else (void) sm_strlcpyn(qd, sizeof(qd), 2, Queue[qgrp]->qg_qpaths[qdir].qp_name, (bitset(QP_SUBQF, Queue[qgrp]->qg_qpaths[qdir].qp_subdirs) ? "/qf" : "")); if (tTd(41, 1)) { sm_dprintf("gatherq:\n"); check = QueueLimitId; while (check != NULL) { sm_dprintf("\tQueueLimitId = %s%s\n", check->queue_negate ? "!" : "", check->queue_match); check = check->queue_next; } check = QueueLimitSender; while (check != NULL) { sm_dprintf("\tQueueLimitSender = %s%s\n", check->queue_negate ? "!" : "", check->queue_match); check = check->queue_next; } check = QueueLimitRecipient; while (check != NULL) { sm_dprintf("\tQueueLimitRecipient = %s%s\n", check->queue_negate ? "!" : "", check->queue_match); check = check->queue_next; } if (QueueMode == QM_QUARANTINE) { check = QueueLimitQuarantine; while (check != NULL) { sm_dprintf("\tQueueLimitQuarantine = %s%s\n", check->queue_negate ? "!" : "", check->queue_match); check = check->queue_next; } } } /* open the queue directory */ f = opendir(qd); if (f == NULL) { syserr("gatherq: cannot open \"%s\"", qid_printqueue(qgrp, qdir)); if (full != NULL) *full = WorkListCount >= MaxQueueRun && MaxQueueRun > 0; if (more != NULL) *more = false; return 0; } /* ** Read the work directory. */ while ((d = readdir(f)) != NULL) { SM_FILE_T *cf; int qfver = 0; char lbuf[MAXNAME + 1]; struct stat sbuf; if (tTd(41, 50)) sm_dprintf("gatherq: checking %s..", d->d_name); /* is this an interesting entry? */ if (!(((QueueMode == QM_NORMAL && d->d_name[0] == NORMQF_LETTER) || (QueueMode == QM_QUARANTINE && d->d_name[0] == QUARQF_LETTER) || (QueueMode == QM_LOST && d->d_name[0] == LOSEQF_LETTER)) && d->d_name[1] == 'f')) { if (tTd(41, 50)) sm_dprintf(" skipping\n"); continue; } if (tTd(41, 50)) sm_dprintf("\n"); if (strlen(d->d_name) >= MAXQFNAME) { if (Verbose) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "gatherq: %s too long, %d max characters\n", d->d_name, MAXQFNAME); if (LogLevel > 0) sm_syslog(LOG_ALERT, NOQID, "gatherq: %s too long, %d max characters", d->d_name, MAXQFNAME); continue; } ++nentries; check = QueueLimitId; while (check != NULL) { if (strcontainedin(false, check->queue_match, d->d_name) != check->queue_negate) break; else check = check->queue_next; } if (QueueLimitId != NULL && check == NULL) continue; /* grow work list if necessary */ if (++wn >= MaxQueueRun && MaxQueueRun > 0) { if (wn == MaxQueueRun && LogLevel > 0) sm_syslog(LOG_WARNING, NOQID, "WorkList for %s maxed out at %d", qid_printqueue(qgrp, qdir), MaxQueueRun); if (doall) continue; /* just count entries */ break; } if (wn >= WorkListSize) { grow_wlist(qgrp, qdir); if (wn >= WorkListSize) continue; } SM_ASSERT(wn >= 0); w = &WorkList[wn]; (void) sm_strlcpyn(qf, sizeof(qf), 3, qd, "/", d->d_name); if (stat(qf, &sbuf) < 0) { if (errno != ENOENT) sm_syslog(LOG_INFO, NOQID, "gatherq: can't stat %s/%s", qid_printqueue(qgrp, qdir), d->d_name); wn--; continue; } if (!bitset(S_IFREG, sbuf.st_mode)) { /* Yikes! Skip it or we will hang on open! */ if (!((d->d_name[0] == DATAFL_LETTER || d->d_name[0] == NORMQF_LETTER || d->d_name[0] == QUARQF_LETTER || d->d_name[0] == LOSEQF_LETTER || d->d_name[0] == XSCRPT_LETTER) && d->d_name[1] == 'f' && d->d_name[2] == '\0')) syserr("gatherq: %s/%s is not a regular file", qid_printqueue(qgrp, qdir), d->d_name); wn--; continue; } /* avoid work if possible */ if ((QueueSortOrder == QSO_BYFILENAME || QueueSortOrder == QSO_BYMODTIME || QueueSortOrder == QSO_NONE || QueueSortOrder == QSO_RANDOM) && QueueLimitQuarantine == NULL && QueueLimitSender == NULL && QueueLimitRecipient == NULL) { w->w_qgrp = qgrp; w->w_qdir = qdir; w->w_name = newstr(d->d_name); w->w_host = NULL; w->w_lock = w->w_tooyoung = false; w->w_pri = 0; w->w_ctime = 0; w->w_mtime = sbuf.st_mtime; ++num_ent; continue; } /* open control file */ cf = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDONLY_B, NULL); if (cf == NULL && OpMode != MD_PRINT) { /* this may be some random person sending hir msgs */ if (tTd(41, 2)) sm_dprintf("gatherq: cannot open %s: %s\n", d->d_name, sm_errstring(errno)); errno = 0; wn--; continue; } w->w_qgrp = qgrp; w->w_qdir = qdir; w->w_name = newstr(d->d_name); w->w_host = NULL; if (cf != NULL) { w->w_lock = !lockfile(sm_io_getinfo(cf, SM_IO_WHAT_FD, NULL), w->w_name, NULL, LOCK_SH|LOCK_NB); } w->w_tooyoung = false; /* make sure jobs in creation don't clog queue */ w->w_pri = 0x7fffffff; w->w_ctime = 0; w->w_mtime = sbuf.st_mtime; /* extract useful information */ i = NEED_P|NEED_T; if (QueueSortOrder == QSO_BYHOST #if _FFR_RHS || QueueSortOrder == QSO_BYSHUFFLE #endif /* _FFR_RHS */ ) { /* need w_host set for host sort order */ i |= NEED_H; } if (QueueLimitSender != NULL) i |= NEED_S; if (QueueLimitRecipient != NULL) i |= NEED_R; if (QueueLimitQuarantine != NULL) i |= NEED_QUARANTINE; while (cf != NULL && i != 0 && sm_io_fgets(cf, SM_TIME_DEFAULT, lbuf, - sizeof(lbuf)) != NULL) + sizeof(lbuf)) >= 0) { int c; time_t age; p = strchr(lbuf, '\n'); if (p != NULL) *p = '\0'; else { /* flush rest of overly long line */ while ((c = sm_io_getc(cf, SM_TIME_DEFAULT)) != SM_IO_EOF && c != '\n') continue; } switch (lbuf[0]) { case 'V': qfver = atoi(&lbuf[1]); break; case 'P': w->w_pri = atol(&lbuf[1]); i &= ~NEED_P; break; case 'T': w->w_ctime = atol(&lbuf[1]); i &= ~NEED_T; break; case 'q': if (QueueMode != QM_QUARANTINE && QueueMode != QM_LOST) { if (tTd(41, 49)) sm_dprintf("%s not marked as quarantined but has a 'q' line\n", w->w_name); i |= HAS_QUARANTINE; } else if (QueueMode == QM_QUARANTINE) { if (QueueLimitQuarantine == NULL) { i &= ~NEED_QUARANTINE; break; } p = &lbuf[1]; check = QueueLimitQuarantine; while (check != NULL) { if (strcontainedin(false, check->queue_match, p) != check->queue_negate) break; else check = check->queue_next; } if (check != NULL) i &= ~NEED_QUARANTINE; } break; case 'R': if (w->w_host == NULL && (p = strrchr(&lbuf[1], '@')) != NULL) { #if _FFR_RHS if (QueueSortOrder == QSO_BYSHUFFLE) w->w_host = newstr(&p[1]); else #endif /* _FFR_RHS */ w->w_host = strrev(&p[1]); makelower(w->w_host); i &= ~NEED_H; } if (QueueLimitRecipient == NULL) { i &= ~NEED_R; break; } if (qfver > 0) { p = strchr(&lbuf[1], ':'); if (p == NULL) p = &lbuf[1]; else ++p; /* skip over ':' */ } else p = &lbuf[1]; check = QueueLimitRecipient; while (check != NULL) { if (strcontainedin(true, check->queue_match, p) != check->queue_negate) break; else check = check->queue_next; } if (check != NULL) i &= ~NEED_R; break; case 'S': check = QueueLimitSender; while (check != NULL) { if (strcontainedin(true, check->queue_match, &lbuf[1]) != check->queue_negate) break; else check = check->queue_next; } if (check != NULL) i &= ~NEED_S; break; case 'K': #if _FFR_EXPDELAY if (MaxQueueAge > 0) { time_t lasttry, delay; lasttry = (time_t) atol(&lbuf[1]); delay = MIN(lasttry - w->w_ctime, MaxQueueAge); age = curtime() - lasttry; if (age < delay) w->w_tooyoung = true; break; } #endif /* _FFR_EXPDELAY */ age = curtime() - (time_t) atol(&lbuf[1]); if (age >= 0 && MinQueueAge > 0 && age < MinQueueAge) w->w_tooyoung = true; break; case 'N': if (atol(&lbuf[1]) == 0) w->w_tooyoung = false; break; } } if (cf != NULL) (void) sm_io_close(cf, SM_TIME_DEFAULT); if ((!doall && (shouldqueue(w->w_pri, w->w_ctime) || w->w_tooyoung)) || bitset(HAS_QUARANTINE, i) || bitset(NEED_QUARANTINE, i) || bitset(NEED_R|NEED_S, i)) { /* don't even bother sorting this job in */ if (tTd(41, 49)) sm_dprintf("skipping %s (%x)\n", w->w_name, i); sm_free(w->w_name); /* XXX */ if (w->w_host != NULL) sm_free(w->w_host); /* XXX */ wn--; } else ++num_ent; } (void) closedir(f); wn++; i = wn - WorkListCount; WorkListCount += SM_MIN(num_ent, WorkListSize); if (more != NULL) *more = WorkListCount < wn; if (full != NULL) *full = (wn >= MaxQueueRun && MaxQueueRun > 0) || (WorkList == NULL && wn > 0); if (pnentries != NULL) *pnentries = nentries; return i; } /* ** SORTQ -- sort the work list ** ** First the old WorkQ is cleared away. Then the WorkList is sorted ** for all items so that important (higher sorting value) items are not ** trunctated off. Then the most important items are moved from ** WorkList to WorkQ. The lower count of 'max' or MaxListCount items ** are moved. ** ** Parameters: ** max -- maximum number of items to be placed in WorkQ ** ** Returns: ** the number of items in WorkQ ** ** Side Effects: ** WorkQ gets released and filled with new work. WorkList ** gets released. Work items get sorted in order. */ static int sortq(max) int max; { register int i; /* local counter */ register WORK *w; /* tmp item pointer */ int wc = WorkListCount; /* trim size for WorkQ */ if (WorkQ != NULL) { WORK *nw; /* Clear out old WorkQ. */ for (w = WorkQ; w != NULL; w = nw) { nw = w->w_next; sm_free(w->w_name); /* XXX */ if (w->w_host != NULL) sm_free(w->w_host); /* XXX */ sm_free((char *) w); /* XXX */ } WorkQ = NULL; } if (WorkList == NULL || wc <= 0) return 0; /* ** The sort now takes place using all of the items in WorkList. ** The list gets trimmed to the most important items after the sort. ** If the trim were to happen before the sort then one or more ** important items might get truncated off -- not what we want. */ if (QueueSortOrder == QSO_BYHOST) { /* ** Sort the work directory for the first time, ** based on host name, lock status, and priority. */ qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf1); /* ** If one message to host is locked, "lock" all messages ** to that host. */ i = 0; while (i < wc) { if (!WorkList[i].w_lock) { i++; continue; } w = &WorkList[i]; while (++i < wc) { if (WorkList[i].w_host == NULL && w->w_host == NULL) WorkList[i].w_lock = true; else if (WorkList[i].w_host != NULL && w->w_host != NULL && sm_strcasecmp(WorkList[i].w_host, w->w_host) == 0) WorkList[i].w_lock = true; else break; } } /* ** Sort the work directory for the second time, ** based on lock status, host name, and priority. */ qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf2); } else if (QueueSortOrder == QSO_BYTIME) { /* ** Simple sort based on submission time only. */ qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf3); } else if (QueueSortOrder == QSO_BYFILENAME) { /* ** Sort based on queue filename. */ qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf4); } else if (QueueSortOrder == QSO_RANDOM) { /* ** Sort randomly. To avoid problems with an instable sort, ** use a random index into the queue file name to start ** comparison. */ randi = get_rand_mod(MAXQFNAME); if (randi < 2) randi = 3; qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf5); } else if (QueueSortOrder == QSO_BYMODTIME) { /* ** Simple sort based on modification time of queue file. ** This puts the oldest items first. */ qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf6); } #if _FFR_RHS else if (QueueSortOrder == QSO_BYSHUFFLE) { /* ** Simple sort based on shuffled host name. */ init_shuffle_alphabet(); qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf7); } #endif /* _FFR_RHS */ else if (QueueSortOrder == QSO_BYPRIORITY) { /* ** Simple sort based on queue priority only. */ qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf0); } /* else don't sort at all */ /* Check if the per queue group item limit will be exceeded */ if (wc > max && max > 0) wc = max; /* ** Convert the work list into canonical form. ** Should be turning it into a list of envelopes here perhaps. ** Only take the most important items up to the per queue group ** maximum. */ for (i = wc; --i >= 0; ) { w = (WORK *) xalloc(sizeof(*w)); w->w_qgrp = WorkList[i].w_qgrp; w->w_qdir = WorkList[i].w_qdir; w->w_name = WorkList[i].w_name; w->w_host = WorkList[i].w_host; w->w_lock = WorkList[i].w_lock; w->w_tooyoung = WorkList[i].w_tooyoung; w->w_pri = WorkList[i].w_pri; w->w_ctime = WorkList[i].w_ctime; w->w_mtime = WorkList[i].w_mtime; w->w_next = WorkQ; WorkQ = w; } /* free the rest of the list */ for (i = WorkListCount; --i >= wc; ) { sm_free(WorkList[i].w_name); if (WorkList[i].w_host != NULL) sm_free(WorkList[i].w_host); } if (WorkList != NULL) sm_free(WorkList); /* XXX */ WorkList = NULL; WorkListSize = 0; WorkListCount = 0; if (tTd(40, 1)) { for (w = WorkQ; w != NULL; w = w->w_next) { if (w->w_host != NULL) sm_dprintf("%22s: pri=%ld %s\n", w->w_name, w->w_pri, w->w_host); else sm_dprintf("%32s: pri=%ld\n", w->w_name, w->w_pri); } } return wc; /* return number of WorkQ items */ } /* ** GROW_WLIST -- make the work list larger ** ** Parameters: ** qgrp -- the index for the queue group. ** qdir -- the index for the queue directory. ** ** Returns: ** none. ** ** Side Effects: ** Adds another QUEUESEGSIZE entries to WorkList if possible. ** It can fail if there isn't enough memory, so WorkListSize ** should be checked again upon return. */ static void grow_wlist(qgrp, qdir) int qgrp; int qdir; { if (tTd(41, 1)) sm_dprintf("grow_wlist: WorkListSize=%d\n", WorkListSize); if (WorkList == NULL) { WorkList = (WORK *) xalloc((sizeof(*WorkList)) * (QUEUESEGSIZE + 1)); WorkListSize = QUEUESEGSIZE; } else { int newsize = WorkListSize + QUEUESEGSIZE; WORK *newlist = (WORK *) sm_realloc((char *) WorkList, (unsigned) sizeof(WORK) * (newsize + 1)); if (newlist != NULL) { WorkListSize = newsize; WorkList = newlist; if (LogLevel > 1) { sm_syslog(LOG_INFO, NOQID, "grew WorkList for %s to %d", qid_printqueue(qgrp, qdir), WorkListSize); } } else if (LogLevel > 0) { sm_syslog(LOG_ALERT, NOQID, "FAILED to grow WorkList for %s to %d", qid_printqueue(qgrp, qdir), newsize); } } if (tTd(41, 1)) sm_dprintf("grow_wlist: WorkListSize now %d\n", WorkListSize); } /* ** WORKCMPF0 -- simple priority-only compare function. ** ** Parameters: ** a -- the first argument. ** b -- the second argument. ** ** Returns: ** -1 if a < b ** 0 if a == b ** +1 if a > b ** */ static int workcmpf0(a, b) register WORK *a; register WORK *b; { long pa = a->w_pri; long pb = b->w_pri; if (pa == pb) return 0; else if (pa > pb) return 1; else return -1; } /* ** WORKCMPF1 -- first compare function for ordering work based on host name. ** ** Sorts on host name, lock status, and priority in that order. ** ** Parameters: ** a -- the first argument. ** b -- the second argument. ** ** Returns: ** <0 if a < b ** 0 if a == b ** >0 if a > b ** */ static int workcmpf1(a, b) register WORK *a; register WORK *b; { int i; /* host name */ if (a->w_host != NULL && b->w_host == NULL) return 1; else if (a->w_host == NULL && b->w_host != NULL) return -1; if (a->w_host != NULL && b->w_host != NULL && (i = sm_strcasecmp(a->w_host, b->w_host)) != 0) return i; /* lock status */ if (a->w_lock != b->w_lock) return b->w_lock - a->w_lock; /* job priority */ return workcmpf0(a, b); } /* ** WORKCMPF2 -- second compare function for ordering work based on host name. ** ** Sorts on lock status, host name, and priority in that order. ** ** Parameters: ** a -- the first argument. ** b -- the second argument. ** ** Returns: ** <0 if a < b ** 0 if a == b ** >0 if a > b ** */ static int workcmpf2(a, b) register WORK *a; register WORK *b; { int i; /* lock status */ if (a->w_lock != b->w_lock) return a->w_lock - b->w_lock; /* host name */ if (a->w_host != NULL && b->w_host == NULL) return 1; else if (a->w_host == NULL && b->w_host != NULL) return -1; if (a->w_host != NULL && b->w_host != NULL && (i = sm_strcasecmp(a->w_host, b->w_host)) != 0) return i; /* job priority */ return workcmpf0(a, b); } /* ** WORKCMPF3 -- simple submission-time-only compare function. ** ** Parameters: ** a -- the first argument. ** b -- the second argument. ** ** Returns: ** -1 if a < b ** 0 if a == b ** +1 if a > b ** */ static int workcmpf3(a, b) register WORK *a; register WORK *b; { if (a->w_ctime > b->w_ctime) return 1; else if (a->w_ctime < b->w_ctime) return -1; else return 0; } /* ** WORKCMPF4 -- compare based on file name ** ** Parameters: ** a -- the first argument. ** b -- the second argument. ** ** Returns: ** -1 if a < b ** 0 if a == b ** +1 if a > b ** */ static int workcmpf4(a, b) register WORK *a; register WORK *b; { return strcmp(a->w_name, b->w_name); } /* ** WORKCMPF5 -- compare based on assigned random number ** ** Parameters: ** a -- the first argument. ** b -- the second argument. ** ** Returns: ** randomly 1/-1 */ /* ARGSUSED0 */ static int workcmpf5(a, b) register WORK *a; register WORK *b; { if (strlen(a->w_name) < randi || strlen(b->w_name) < randi) return -1; return a->w_name[randi] - b->w_name[randi]; } /* ** WORKCMPF6 -- simple modification-time-only compare function. ** ** Parameters: ** a -- the first argument. ** b -- the second argument. ** ** Returns: ** -1 if a < b ** 0 if a == b ** +1 if a > b ** */ static int workcmpf6(a, b) register WORK *a; register WORK *b; { if (a->w_mtime > b->w_mtime) return 1; else if (a->w_mtime < b->w_mtime) return -1; else return 0; } #if _FFR_RHS /* ** WORKCMPF7 -- compare function for ordering work based on shuffled host name. ** ** Sorts on lock status, host name, and priority in that order. ** ** Parameters: ** a -- the first argument. ** b -- the second argument. ** ** Returns: ** <0 if a < b ** 0 if a == b ** >0 if a > b ** */ static int workcmpf7(a, b) register WORK *a; register WORK *b; { int i; /* lock status */ if (a->w_lock != b->w_lock) return a->w_lock - b->w_lock; /* host name */ if (a->w_host != NULL && b->w_host == NULL) return 1; else if (a->w_host == NULL && b->w_host != NULL) return -1; if (a->w_host != NULL && b->w_host != NULL && (i = sm_strshufflecmp(a->w_host, b->w_host)) != 0) return i; /* job priority */ return workcmpf0(a, b); } #endif /* _FFR_RHS */ /* ** STRREV -- reverse string ** ** Returns a pointer to a new string that is the reverse of ** the string pointed to by fwd. The space for the new ** string is obtained using xalloc(). ** ** Parameters: ** fwd -- the string to reverse. ** ** Returns: ** the reversed string. */ static char * strrev(fwd) char *fwd; { char *rev = NULL; int len, cnt; len = strlen(fwd); rev = xalloc(len + 1); for (cnt = 0; cnt < len; ++cnt) rev[cnt] = fwd[len - cnt - 1]; rev[len] = '\0'; return rev; } #if _FFR_RHS # define NASCII 128 # define NCHAR 256 static unsigned char ShuffledAlphabet[NCHAR]; void init_shuffle_alphabet() { static bool init = false; int i; if (init) return; /* fill the ShuffledAlphabet */ for (i = 0; i < NASCII; i++) ShuffledAlphabet[i] = i; /* mix it */ for (i = 1; i < NASCII; i++) { register int j = get_random() % NASCII; register int tmp; tmp = ShuffledAlphabet[j]; ShuffledAlphabet[j] = ShuffledAlphabet[i]; ShuffledAlphabet[i] = tmp; } /* make it case insensitive */ for (i = 'A'; i <= 'Z'; i++) ShuffledAlphabet[i] = ShuffledAlphabet[i + 'a' - 'A']; /* fill the upper part */ for (i = 0; i < NASCII; i++) ShuffledAlphabet[i + NASCII] = ShuffledAlphabet[i]; init = true; } static int sm_strshufflecmp(a, b) char *a; char *b; { const unsigned char *us1 = (const unsigned char *) a; const unsigned char *us2 = (const unsigned char *) b; while (ShuffledAlphabet[*us1] == ShuffledAlphabet[*us2++]) { if (*us1++ == '\0') return 0; } return (ShuffledAlphabet[*us1] - ShuffledAlphabet[*--us2]); } #endif /* _FFR_RHS */ /* ** DOWORK -- do a work request. ** ** Parameters: ** qgrp -- the index of the queue group for the job. ** qdir -- the index of the queue directory for the job. ** id -- the ID of the job to run. ** forkflag -- if set, run this in background. ** requeueflag -- if set, reinstantiate the queue quickly. ** This is used when expanding aliases in the queue. ** If forkflag is also set, it doesn't wait for the ** child. ** e - the envelope in which to run it. ** ** Returns: ** process id of process that is running the queue job. ** ** Side Effects: ** The work request is satisfied if possible. */ pid_t dowork(qgrp, qdir, id, forkflag, requeueflag, e) int qgrp; int qdir; char *id; bool forkflag; bool requeueflag; register ENVELOPE *e; { register pid_t pid; SM_RPOOL_T *rpool; if (tTd(40, 1)) sm_dprintf("dowork(%s/%s)\n", qid_printqueue(qgrp, qdir), id); /* ** Fork for work. */ if (forkflag) { /* ** Since the delivery may happen in a child and the ** parent does not wait, the parent may close the ** maps thereby removing any shared memory used by ** the map. Therefore, close the maps now so the ** child will dynamically open them if necessary. */ closemaps(false); pid = fork(); if (pid < 0) { syserr("dowork: cannot fork"); return 0; } else if (pid > 0) { /* parent -- clean out connection cache */ mci_flush(false, NULL); } else { /* ** Initialize exception stack and default exception ** handler for child process. */ /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; CurrentPid = getpid(); sm_exc_newthread(fatal_error); /* ** See note above about SMTP processes and SIGCHLD. */ if (OpMode == MD_SMTP || OpMode == MD_DAEMON || MaxQueueChildren > 0) { proc_list_clear(); sm_releasesignal(SIGCHLD); (void) sm_signal(SIGCHLD, SIG_DFL); } /* child -- error messages to the transcript */ QuickAbort = OnlyOneError = false; } } else { pid = 0; } if (pid == 0) { /* ** CHILD ** Lock the control file to avoid duplicate deliveries. ** Then run the file as though we had just read it. ** We save an idea of the temporary name so we ** can recover on interrupt. */ if (forkflag) { /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; } /* set basic modes, etc. */ sm_clear_events(); clearstats(); rpool = sm_rpool_new_x(NULL); clearenvelope(e, false, rpool); e->e_flags |= EF_QUEUERUN|EF_GLOBALERRS; set_delivery_mode(SM_DELIVER, e); e->e_errormode = EM_MAIL; e->e_id = id; e->e_qgrp = qgrp; e->e_qdir = qdir; GrabTo = UseErrorsTo = false; ExitStat = EX_OK; if (forkflag) { disconnect(1, e); set_op_mode(MD_QUEUERUN); } sm_setproctitle(true, e, "%s from queue", qid_printname(e)); if (LogLevel > 76) sm_syslog(LOG_DEBUG, e->e_id, "dowork, pid=%d", (int) CurrentPid); /* don't use the headers from sendmail.cf... */ e->e_header = NULL; /* read the queue control file -- return if locked */ if (!readqf(e, false)) { if (tTd(40, 4) && e->e_id != NULL) sm_dprintf("readqf(%s) failed\n", qid_printname(e)); e->e_id = NULL; if (forkflag) finis(false, true, EX_OK); else { /* adding this frees 8 bytes */ clearenvelope(e, false, rpool); /* adding this frees 12 bytes */ sm_rpool_free(rpool); e->e_rpool = NULL; return 0; } } e->e_flags |= EF_INQUEUE; eatheader(e, requeueflag, true); if (requeueflag) queueup(e, false, false); /* do the delivery */ sendall(e, SM_DELIVER); /* finish up and exit */ if (forkflag) finis(true, true, ExitStat); else { (void) dropenvelope(e, true, false); sm_rpool_free(rpool); e->e_rpool = NULL; e->e_message = NULL; } } e->e_id = NULL; return pid; } /* ** DOWORKLIST -- process a list of envelopes as work requests ** ** Similar to dowork(), except that after forking, it processes an ** envelope and its siblings, treating each envelope as a work request. ** ** Parameters: ** el -- envelope to be processed including its siblings. ** forkflag -- if set, run this in background. ** requeueflag -- if set, reinstantiate the queue quickly. ** This is used when expanding aliases in the queue. ** If forkflag is also set, it doesn't wait for the ** child. ** ** Returns: ** process id of process that is running the queue job. ** ** Side Effects: ** The work request is satisfied if possible. */ pid_t doworklist(el, forkflag, requeueflag) ENVELOPE *el; bool forkflag; bool requeueflag; { register pid_t pid; ENVELOPE *ei; if (tTd(40, 1)) sm_dprintf("doworklist()\n"); /* ** Fork for work. */ if (forkflag) { /* ** Since the delivery may happen in a child and the ** parent does not wait, the parent may close the ** maps thereby removing any shared memory used by ** the map. Therefore, close the maps now so the ** child will dynamically open them if necessary. */ closemaps(false); pid = fork(); if (pid < 0) { syserr("doworklist: cannot fork"); return 0; } else if (pid > 0) { /* parent -- clean out connection cache */ mci_flush(false, NULL); } else { /* ** Initialize exception stack and default exception ** handler for child process. */ /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; CurrentPid = getpid(); sm_exc_newthread(fatal_error); /* ** See note above about SMTP processes and SIGCHLD. */ if (OpMode == MD_SMTP || OpMode == MD_DAEMON || MaxQueueChildren > 0) { proc_list_clear(); sm_releasesignal(SIGCHLD); (void) sm_signal(SIGCHLD, SIG_DFL); } /* child -- error messages to the transcript */ QuickAbort = OnlyOneError = false; } } else { pid = 0; } if (pid != 0) return pid; /* ** IN CHILD ** Lock the control file to avoid duplicate deliveries. ** Then run the file as though we had just read it. ** We save an idea of the temporary name so we ** can recover on interrupt. */ if (forkflag) { /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; } /* set basic modes, etc. */ sm_clear_events(); clearstats(); GrabTo = UseErrorsTo = false; ExitStat = EX_OK; if (forkflag) { disconnect(1, el); set_op_mode(MD_QUEUERUN); } if (LogLevel > 76) sm_syslog(LOG_DEBUG, el->e_id, "doworklist, pid=%d", (int) CurrentPid); for (ei = el; ei != NULL; ei = ei->e_sibling) { ENVELOPE e; SM_RPOOL_T *rpool; if (WILL_BE_QUEUED(ei->e_sendmode)) continue; else if (QueueMode != QM_QUARANTINE && ei->e_quarmsg != NULL) continue; rpool = sm_rpool_new_x(NULL); clearenvelope(&e, true, rpool); e.e_flags |= EF_QUEUERUN|EF_GLOBALERRS; set_delivery_mode(SM_DELIVER, &e); e.e_errormode = EM_MAIL; e.e_id = ei->e_id; e.e_qgrp = ei->e_qgrp; e.e_qdir = ei->e_qdir; openxscript(&e); sm_setproctitle(true, &e, "%s from queue", qid_printname(&e)); /* don't use the headers from sendmail.cf... */ e.e_header = NULL; CurEnv = &e; /* read the queue control file -- return if locked */ if (readqf(&e, false)) { e.e_flags |= EF_INQUEUE; eatheader(&e, requeueflag, true); if (requeueflag) queueup(&e, false, false); /* do the delivery */ sendall(&e, SM_DELIVER); (void) dropenvelope(&e, true, false); } else { if (tTd(40, 4) && e.e_id != NULL) sm_dprintf("readqf(%s) failed\n", qid_printname(&e)); } sm_rpool_free(rpool); ei->e_id = NULL; } /* restore CurEnv */ CurEnv = el; /* finish up and exit */ if (forkflag) finis(true, true, ExitStat); return 0; } /* ** READQF -- read queue file and set up environment. ** ** Parameters: ** e -- the envelope of the job to run. ** openonly -- only open the qf (returned as e_lockfp) ** ** Returns: ** true if it successfully read the queue file. ** false otherwise. ** ** Side Effects: ** The queue file is returned locked. */ static bool readqf(e, openonly) register ENVELOPE *e; bool openonly; { register SM_FILE_T *qfp; ADDRESS *ctladdr; struct stat st, stf; char *bp; int qfver = 0; long hdrsize = 0; register char *p; char *frcpt = NULL; char *orcpt = NULL; bool nomore = false; bool bogus = false; MODE_T qsafe; char *err; char qf[MAXPATHLEN]; char buf[MAXLINE]; int bufsize; /* ** Read and process the file. */ SM_REQUIRE(e != NULL); bp = NULL; (void) sm_strlcpy(qf, queuename(e, ANYQFL_LETTER), sizeof(qf)); qfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDWR_B, NULL); if (qfp == NULL) { int save_errno = errno; if (tTd(40, 8)) sm_dprintf("readqf(%s): sm_io_open failure (%s)\n", qf, sm_errstring(errno)); errno = save_errno; if (errno != ENOENT ) syserr("readqf: no control file %s", qf); RELEASE_QUEUE; return false; } if (!lockfile(sm_io_getinfo(qfp, SM_IO_WHAT_FD, NULL), qf, NULL, LOCK_EX|LOCK_NB)) { /* being processed by another queuer */ if (Verbose) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: locked\n", e->e_id); if (tTd(40, 8)) sm_dprintf("%s: locked\n", e->e_id); if (LogLevel > 19) sm_syslog(LOG_DEBUG, e->e_id, "locked"); (void) sm_io_close(qfp, SM_TIME_DEFAULT); RELEASE_QUEUE; return false; } RELEASE_QUEUE; /* ** Prevent locking race condition. ** ** Process A: readqf(): qfp = fopen(qffile) ** Process B: queueup(): rename(tf, qf) ** Process B: unlocks(tf) ** Process A: lockfile(qf); ** ** Process A (us) has the old qf file (before the rename deleted ** the directory entry) and will be delivering based on old data. ** This can lead to multiple deliveries of the same recipients. ** ** Catch this by checking if the underlying qf file has changed ** *after* acquiring our lock and if so, act as though the file ** was still locked (i.e., just return like the lockfile() case ** above. */ if (stat(qf, &stf) < 0 || fstat(sm_io_getinfo(qfp, SM_IO_WHAT_FD, NULL), &st) < 0) { /* must have been being processed by someone else */ if (tTd(40, 8)) sm_dprintf("readqf(%s): [f]stat failure (%s)\n", qf, sm_errstring(errno)); (void) sm_io_close(qfp, SM_TIME_DEFAULT); return false; } if (st.st_nlink != stf.st_nlink || st.st_dev != stf.st_dev || ST_INODE(st) != ST_INODE(stf) || #if HAS_ST_GEN && 0 /* AFS returns garbage in st_gen */ st.st_gen != stf.st_gen || #endif /* HAS_ST_GEN && 0 */ st.st_uid != stf.st_uid || st.st_gid != stf.st_gid || st.st_size != stf.st_size) { /* changed after opened */ if (Verbose) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: changed\n", e->e_id); if (tTd(40, 8)) sm_dprintf("%s: changed\n", e->e_id); if (LogLevel > 19) sm_syslog(LOG_DEBUG, e->e_id, "changed"); (void) sm_io_close(qfp, SM_TIME_DEFAULT); return false; } /* ** Check the queue file for plausibility to avoid attacks. */ qsafe = S_IWOTH|S_IWGRP; if (bitset(S_IWGRP, QueueFileMode)) qsafe &= ~S_IWGRP; bogus = st.st_uid != geteuid() && st.st_uid != TrustedUid && geteuid() != RealUid; /* ** If this qf file results from a set-group-ID binary, then ** we check whether the directory is group-writable, ** the queue file mode contains the group-writable bit, and ** the groups are the same. ** Notice: this requires that the set-group-ID binary is used to ** run the queue! */ if (bogus && st.st_gid == getegid() && UseMSP) { char delim; struct stat dst; bp = SM_LAST_DIR_DELIM(qf); if (bp == NULL) delim = '\0'; else { delim = *bp; *bp = '\0'; } if (stat(delim == '\0' ? "." : qf, &dst) < 0) syserr("readqf: cannot stat directory %s", delim == '\0' ? "." : qf); else { bogus = !(bitset(S_IWGRP, QueueFileMode) && bitset(S_IWGRP, dst.st_mode) && dst.st_gid == st.st_gid); } if (delim != '\0') *bp = delim; bp = NULL; } if (!bogus) bogus = bitset(qsafe, st.st_mode); if (bogus) { if (LogLevel > 0) { sm_syslog(LOG_ALERT, e->e_id, "bogus queue file, uid=%d, gid=%d, mode=%o", st.st_uid, st.st_gid, st.st_mode); } if (tTd(40, 8)) sm_dprintf("readqf(%s): bogus file\n", qf); e->e_flags |= EF_INQUEUE; if (!openonly) loseqfile(e, "bogus file uid/gid in mqueue"); (void) sm_io_close(qfp, SM_TIME_DEFAULT); return false; } if (st.st_size == 0) { /* must be a bogus file -- if also old, just remove it */ if (!openonly && st.st_ctime + 10 * 60 < curtime()) { (void) xunlink(queuename(e, DATAFL_LETTER)); (void) xunlink(queuename(e, ANYQFL_LETTER)); } (void) sm_io_close(qfp, SM_TIME_DEFAULT); return false; } if (st.st_nlink == 0) { /* ** Race condition -- we got a file just as it was being ** unlinked. Just assume it is zero length. */ (void) sm_io_close(qfp, SM_TIME_DEFAULT); return false; } #if _FFR_TRUSTED_QF /* ** If we don't own the file mark it as unsafe. ** However, allow TrustedUser to own it as well ** in case TrustedUser manipulates the queue. */ if (st.st_uid != geteuid() && st.st_uid != TrustedUid) e->e_flags |= EF_UNSAFE; #else /* _FFR_TRUSTED_QF */ /* If we don't own the file mark it as unsafe */ if (st.st_uid != geteuid()) e->e_flags |= EF_UNSAFE; #endif /* _FFR_TRUSTED_QF */ /* good file -- save this lock */ e->e_lockfp = qfp; /* Just wanted the open file */ if (openonly) return true; /* do basic system initialization */ initsys(e); macdefine(&e->e_macro, A_PERM, 'i', e->e_id); LineNumber = 0; e->e_flags |= EF_GLOBALERRS; set_op_mode(MD_QUEUERUN); ctladdr = NULL; e->e_qfletter = queue_letter(e, ANYQFL_LETTER); e->e_dfqgrp = e->e_qgrp; e->e_dfqdir = e->e_qdir; #if _FFR_QUEUE_MACRO macdefine(&e->e_macro, A_TEMP, macid("{queue}"), qid_printqueue(e->e_qgrp, e->e_qdir)); #endif /* _FFR_QUEUE_MACRO */ e->e_dfino = -1; e->e_msgsize = -1; while (bufsize = sizeof(buf), (bp = fgetfolded(buf, &bufsize, qfp)) != NULL) { unsigned long qflags; ADDRESS *q; int r; time_t now; auto char *ep; if (tTd(40, 4)) sm_dprintf("+++++ %s\n", bp); if (nomore) { /* hack attack */ hackattack: syserr("SECURITY ALERT: extra or bogus data in queue file: %s", bp); err = "bogus queue line"; goto fail; } switch (bp[0]) { case 'A': /* AUTH= parameter */ if (!xtextok(&bp[1])) goto hackattack; e->e_auth_param = sm_rpool_strdup_x(e->e_rpool, &bp[1]); break; case 'B': /* body type */ r = check_bodytype(&bp[1]); if (!BODYTYPE_VALID(r)) goto hackattack; e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, &bp[1]); break; case 'C': /* specify controlling user */ ctladdr = setctluser(&bp[1], qfver, e); break; case 'D': /* data file name */ /* obsolete -- ignore */ break; case 'd': /* data file directory name */ { int qgrp, qdir; #if _FFR_MSP_PARANOIA /* forbid queue groups in MSP? */ if (UseMSP) goto hackattack; #endif /* _FFR_MSP_PARANOIA */ for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; ++qgrp) { for (qdir = 0; qdir < Queue[qgrp]->qg_numqueues; ++qdir) { if (strcmp(&bp[1], Queue[qgrp]->qg_qpaths[qdir].qp_name) == 0) { e->e_dfqgrp = qgrp; e->e_dfqdir = qdir; goto done; } } } err = "bogus queue file directory"; goto fail; done: break; } case 'E': /* specify error recipient */ /* no longer used */ break; case 'F': /* flag bits */ if (strncmp(bp, "From ", 5) == 0) { /* we are being spoofed! */ syserr("SECURITY ALERT: bogus qf line %s", bp); err = "bogus queue line"; goto fail; } for (p = &bp[1]; *p != '\0'; p++) { switch (*p) { case '8': /* has 8 bit data */ e->e_flags |= EF_HAS8BIT; break; case 'b': /* delete Bcc: header */ e->e_flags |= EF_DELETE_BCC; break; case 'd': /* envelope has DSN RET= */ e->e_flags |= EF_RET_PARAM; break; case 'n': /* don't return body */ e->e_flags |= EF_NO_BODY_RETN; break; case 'r': /* response */ e->e_flags |= EF_RESPONSE; break; case 's': /* split */ e->e_flags |= EF_SPLIT; break; case 'w': /* warning sent */ e->e_flags |= EF_WARNING; break; } } break; case 'q': /* quarantine reason */ e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, &bp[1]); macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), e->e_quarmsg); break; case 'H': /* header */ /* ** count size before chompheader() destroys the line. ** this isn't accurate due to macro expansion, but ** better than before. "-3" to skip H?? at least. */ hdrsize += strlen(bp) - 3; (void) chompheader(&bp[1], CHHDR_QUEUE, NULL, e); break; case 'I': /* data file's inode number */ /* regenerated below */ break; case 'K': /* time of last delivery attempt */ e->e_dtime = atol(&buf[1]); break; case 'L': /* Solaris Content-Length: */ case 'M': /* message */ /* ignore this; we want a new message next time */ break; case 'N': /* number of delivery attempts */ e->e_ntries = atoi(&buf[1]); /* if this has been tried recently, let it be */ now = curtime(); if (e->e_ntries > 0 && e->e_dtime <= now && now < e->e_dtime + MinQueueAge) { char *howlong; howlong = pintvl(now - e->e_dtime, true); if (Verbose) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: too young (%s)\n", e->e_id, howlong); if (tTd(40, 8)) sm_dprintf("%s: too young (%s)\n", e->e_id, howlong); if (LogLevel > 19) sm_syslog(LOG_DEBUG, e->e_id, "too young (%s)", howlong); e->e_id = NULL; unlockqueue(e); if (bp != buf) sm_free(bp); return false; } macdefine(&e->e_macro, A_TEMP, macid("{ntries}"), &buf[1]); #if NAMED_BIND /* adjust BIND parameters immediately */ if (e->e_ntries == 0) { _res.retry = TimeOuts.res_retry[RES_TO_FIRST]; _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST]; } else { _res.retry = TimeOuts.res_retry[RES_TO_NORMAL]; _res.retrans = TimeOuts.res_retrans[RES_TO_NORMAL]; } #endif /* NAMED_BIND */ break; case 'P': /* message priority */ e->e_msgpriority = atol(&bp[1]) + WkTimeFact; break; case 'Q': /* original recipient */ orcpt = sm_rpool_strdup_x(e->e_rpool, &bp[1]); break; case 'r': /* final recipient */ frcpt = sm_rpool_strdup_x(e->e_rpool, &bp[1]); break; case 'R': /* specify recipient */ p = bp; qflags = 0; if (qfver >= 1) { /* get flag bits */ while (*++p != '\0' && *p != ':') { switch (*p) { case 'N': qflags |= QHASNOTIFY; break; case 'S': qflags |= QPINGONSUCCESS; break; case 'F': qflags |= QPINGONFAILURE; break; case 'D': qflags |= QPINGONDELAY; break; case 'P': qflags |= QPRIMARY; break; case 'A': if (ctladdr != NULL) ctladdr->q_flags |= QALIAS; break; default: /* ignore or complain? */ break; } } } else qflags |= QPRIMARY; macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r"); if (*p != '\0') q = parseaddr(++p, NULLADDR, RF_COPYALL, '\0', NULL, e, true); else q = NULL; if (q != NULL) { /* make sure we keep the current qgrp */ if (ISVALIDQGRP(e->e_qgrp)) q->q_qgrp = e->e_qgrp; q->q_alias = ctladdr; if (qfver >= 1) q->q_flags &= ~Q_PINGFLAGS; q->q_flags |= qflags; q->q_finalrcpt = frcpt; q->q_orcpt = orcpt; (void) recipient(q, &e->e_sendqueue, 0, e); } frcpt = NULL; orcpt = NULL; macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL); break; case 'S': /* sender */ setsender(sm_rpool_strdup_x(e->e_rpool, &bp[1]), e, NULL, '\0', true); break; case 'T': /* init time */ e->e_ctime = atol(&bp[1]); break; case 'V': /* queue file version number */ qfver = atoi(&bp[1]); if (qfver <= QF_VERSION) break; syserr("Version number in queue file (%d) greater than max (%d)", qfver, QF_VERSION); err = "unsupported queue file version"; goto fail; /* NOTREACHED */ break; case 'Z': /* original envelope id from ESMTP */ e->e_envid = sm_rpool_strdup_x(e->e_rpool, &bp[1]); macdefine(&e->e_macro, A_PERM, macid("{dsn_envid}"), e->e_envid); break; case '!': /* deliver by */ /* format: flag (1 char) space long-integer */ e->e_dlvr_flag = buf[1]; e->e_deliver_by = strtol(&buf[3], NULL, 10); case '$': /* define macro */ { char *p; /* XXX elimate p? */ r = macid_parse(&bp[1], &ep); if (r == 0) break; p = sm_rpool_strdup_x(e->e_rpool, ep); macdefine(&e->e_macro, A_PERM, r, p); } break; case '.': /* terminate file */ nomore = true; break; #if _FFR_QUEUEDELAY case 'G': case 'Y': /* ** Maintain backward compatibility for ** users who defined _FFR_QUEUEDELAY in ** previous releases. Remove this ** code in 8.14 or 8.15. */ if (qfver == 5 || qfver == 7) break; /* If not qfver 5 or 7, then 'G' or 'Y' is invalid */ /* FALLTHROUGH */ #endif /* _FFR_QUEUEDELAY */ default: syserr("readqf: %s: line %d: bad line \"%s\"", qf, LineNumber, shortenstring(bp, MAXSHORTSTR)); err = "unrecognized line"; goto fail; } if (bp != buf) SM_FREE(bp); } /* ** If we haven't read any lines, this queue file is empty. ** Arrange to remove it without referencing any null pointers. */ if (LineNumber == 0) { errno = 0; e->e_flags |= EF_CLRQUEUE|EF_FATALERRS|EF_RESPONSE; return true; } /* Check to make sure we have a complete queue file read */ if (!nomore) { syserr("readqf: %s: incomplete queue file read", qf); (void) sm_io_close(qfp, SM_TIME_DEFAULT); return false; } #if _FFR_QF_PARANOIA /* Check to make sure key fields were read */ if (e->e_from.q_mailer == NULL) { syserr("readqf: %s: sender not specified in queue file", qf); (void) sm_io_close(qfp, SM_TIME_DEFAULT); return false; } /* other checks? */ #endif /* _FFR_QF_PARANOIA */ /* possibly set ${dsn_ret} macro */ if (bitset(EF_RET_PARAM, e->e_flags)) { if (bitset(EF_NO_BODY_RETN, e->e_flags)) macdefine(&e->e_macro, A_PERM, macid("{dsn_ret}"), "hdrs"); else macdefine(&e->e_macro, A_PERM, macid("{dsn_ret}"), "full"); } /* ** Arrange to read the data file. */ p = queuename(e, DATAFL_LETTER); e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, p, SM_IO_RDONLY_B, NULL); if (e->e_dfp == NULL) { syserr("readqf: cannot open %s", p); } else { e->e_flags |= EF_HAS_DF; if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &st) >= 0) { e->e_msgsize = st.st_size + hdrsize; e->e_dfdev = st.st_dev; e->e_dfino = ST_INODE(st); (void) sm_snprintf(buf, sizeof(buf), "%ld", PRT_NONNEGL(e->e_msgsize)); macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf); } } return true; fail: /* ** There was some error reading the qf file (reason is in err var.) ** Cleanup: ** close file; clear e_lockfp since it is the same as qfp, ** hence it is invalid (as file) after qfp is closed; ** the qf file is on disk, so set the flag to avoid calling ** queueup() with bogus data. */ if (bp != buf) SM_FREE(bp); if (qfp != NULL) (void) sm_io_close(qfp, SM_TIME_DEFAULT); e->e_lockfp = NULL; e->e_flags |= EF_INQUEUE; loseqfile(e, err); return false; } /* ** PRTSTR -- print a string, "unprintable" characters are shown as \oct ** ** Parameters: ** s -- string to print ** ml -- maximum length of output ** ** Returns: ** number of entries ** ** Side Effects: ** Prints a string on stdout. */ static void prtstr __P((char *, int)); static void prtstr(s, ml) char *s; int ml; { int c; if (s == NULL) return; while (ml-- > 0 && ((c = *s++) != '\0')) { if (c == '\\') { if (ml-- > 0) { (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c); (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c); } } else if (isascii(c) && isprint(c)) (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c); else { if ((ml -= 3) > 0) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\\%03o", c & 0xFF); } } } /* ** PRINTNQE -- print out number of entries in the mail queue ** ** Parameters: ** out -- output file pointer. ** prefix -- string to output in front of each line. ** ** Returns: ** none. */ void printnqe(out, prefix) SM_FILE_T *out; char *prefix; { #if SM_CONF_SHM int i, k = 0, nrequests = 0; bool unknown = false; if (ShmId == SM_SHM_NO_ID) { if (prefix == NULL) (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "Data unavailable: shared memory not updated\n"); else (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%sNOTCONFIGURED:-1\r\n", prefix); return; } for (i = 0; i < NumQueue && Queue[i] != NULL; i++) { int j; k++; for (j = 0; j < Queue[i]->qg_numqueues; j++) { int n; if (StopRequest) stop_sendmail(); n = QSHM_ENTRIES(Queue[i]->qg_qpaths[j].qp_idx); if (prefix != NULL) (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%s%s:%d\r\n", prefix, qid_printqueue(i, j), n); else if (n < 0) { (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%s: unknown number of entries\n", qid_printqueue(i, j)); unknown = true; } else if (n == 0) { (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%s is empty\n", qid_printqueue(i, j)); } else if (n > 0) { (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%s: entries=%d\n", qid_printqueue(i, j), n); nrequests += n; k++; } } } if (prefix == NULL && k > 1) (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "\t\tTotal requests: %d%s\n", nrequests, unknown ? " (about)" : ""); #else /* SM_CONF_SHM */ if (prefix == NULL) (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "Data unavailable without shared memory support\n"); else (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%sNOTAVAILABLE:-1\r\n", prefix); #endif /* SM_CONF_SHM */ } /* ** PRINTQUEUE -- print out a representation of the mail queue ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** Prints a listing of the mail queue on the standard output. */ void printqueue() { int i, k = 0, nrequests = 0; for (i = 0; i < NumQueue && Queue[i] != NULL; i++) { int j; k++; for (j = 0; j < Queue[i]->qg_numqueues; j++) { if (StopRequest) stop_sendmail(); nrequests += print_single_queue(i, j); k++; } } if (k > 1) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\t\tTotal requests: %d\n", nrequests); } /* ** PRINT_SINGLE_QUEUE -- print out a representation of a single mail queue ** ** Parameters: ** qgrp -- the index of the queue group. ** qdir -- the queue directory. ** ** Returns: ** number of requests in mail queue. ** ** Side Effects: ** Prints a listing of the mail queue on the standard output. */ int print_single_queue(qgrp, qdir) int qgrp; int qdir; { register WORK *w; SM_FILE_T *f; int nrequests; char qd[MAXPATHLEN]; char qddf[MAXPATHLEN]; char buf[MAXLINE]; if (qdir == NOQDIR) { (void) sm_strlcpy(qd, ".", sizeof(qd)); (void) sm_strlcpy(qddf, ".", sizeof(qddf)); } else { (void) sm_strlcpyn(qd, sizeof(qd), 2, Queue[qgrp]->qg_qpaths[qdir].qp_name, (bitset(QP_SUBQF, Queue[qgrp]->qg_qpaths[qdir].qp_subdirs) ? "/qf" : "")); (void) sm_strlcpyn(qddf, sizeof(qddf), 2, Queue[qgrp]->qg_qpaths[qdir].qp_name, (bitset(QP_SUBDF, Queue[qgrp]->qg_qpaths[qdir].qp_subdirs) ? "/df" : "")); } /* ** Check for permission to print the queue */ if (bitset(PRIV_RESTRICTMAILQ, PrivacyFlags) && RealUid != 0) { struct stat st; #ifdef NGROUPS_MAX int n; extern GIDSET_T InitialGidSet[NGROUPS_MAX]; #endif /* NGROUPS_MAX */ if (stat(qd, &st) < 0) { syserr("Cannot stat %s", qid_printqueue(qgrp, qdir)); return 0; } #ifdef NGROUPS_MAX n = NGROUPS_MAX; while (--n >= 0) { if (InitialGidSet[n] == st.st_gid) break; } if (n < 0 && RealGid != st.st_gid) #else /* NGROUPS_MAX */ if (RealGid != st.st_gid) #endif /* NGROUPS_MAX */ { usrerr("510 You are not permitted to see the queue"); setstat(EX_NOPERM); return 0; } } /* ** Read and order the queue. */ nrequests = gatherq(qgrp, qdir, true, NULL, NULL, NULL); (void) sortq(Queue[qgrp]->qg_maxlist); /* ** Print the work list that we have read. */ /* first see if there is anything */ if (nrequests <= 0) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s is empty\n", qid_printqueue(qgrp, qdir)); return 0; } sm_getla(); /* get load average */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\t\t%s (%d request%s", qid_printqueue(qgrp, qdir), nrequests, nrequests == 1 ? "" : "s"); if (MaxQueueRun > 0 && nrequests > MaxQueueRun) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, ", only %d printed", MaxQueueRun); if (Verbose) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, ")\n-----Q-ID----- --Size-- -Priority- ---Q-Time--- --------Sender/Recipient--------\n"); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, ")\n-----Q-ID----- --Size-- -----Q-Time----- ------------Sender/Recipient-----------\n"); for (w = WorkQ; w != NULL; w = w->w_next) { struct stat st; auto time_t submittime = 0; long dfsize; int flags = 0; int qfver; char quarmsg[MAXLINE]; char statmsg[MAXLINE]; char bodytype[MAXNAME + 1]; char qf[MAXPATHLEN]; if (StopRequest) stop_sendmail(); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%13s", w->w_name + 2); (void) sm_strlcpyn(qf, sizeof(qf), 3, qd, "/", w->w_name); f = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDONLY_B, NULL); if (f == NULL) { if (errno == EPERM) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " (permission denied)\n"); else if (errno == ENOENT) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " (job completed)\n"); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " (%s)\n", sm_errstring(errno)); errno = 0; continue; } w->w_name[0] = DATAFL_LETTER; (void) sm_strlcpyn(qf, sizeof(qf), 3, qddf, "/", w->w_name); if (stat(qf, &st) >= 0) dfsize = st.st_size; else { ENVELOPE e; /* ** Maybe the df file can't be statted because ** it is in a different directory than the qf file. ** In order to find out, we must read the qf file. */ newenvelope(&e, &BlankEnvelope, sm_rpool_new_x(NULL)); e.e_id = w->w_name + 2; e.e_qgrp = qgrp; e.e_qdir = qdir; dfsize = -1; if (readqf(&e, false)) { char *df = queuename(&e, DATAFL_LETTER); if (stat(df, &st) >= 0) dfsize = st.st_size; } if (e.e_lockfp != NULL) { (void) sm_io_close(e.e_lockfp, SM_TIME_DEFAULT); e.e_lockfp = NULL; } clearenvelope(&e, false, e.e_rpool); sm_rpool_free(e.e_rpool); } if (w->w_lock) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "*"); else if (QueueMode == QM_LOST) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "?"); else if (w->w_tooyoung) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "-"); else if (shouldqueue(w->w_pri, w->w_ctime)) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "X"); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " "); errno = 0; quarmsg[0] = '\0'; statmsg[0] = bodytype[0] = '\0'; qfver = 0; - while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { register int i; register char *p; if (StopRequest) stop_sendmail(); fixcrlf(buf, true); switch (buf[0]) { case 'V': /* queue file version */ qfver = atoi(&buf[1]); break; case 'M': /* error message */ if ((i = strlen(&buf[1])) >= sizeof(statmsg)) i = sizeof(statmsg) - 1; memmove(statmsg, &buf[1], i); statmsg[i] = '\0'; break; case 'q': /* quarantine reason */ if ((i = strlen(&buf[1])) >= sizeof(quarmsg)) i = sizeof(quarmsg) - 1; memmove(quarmsg, &buf[1], i); quarmsg[i] = '\0'; break; case 'B': /* body type */ if ((i = strlen(&buf[1])) >= sizeof(bodytype)) i = sizeof(bodytype) - 1; memmove(bodytype, &buf[1], i); bodytype[i] = '\0'; break; case 'S': /* sender name */ if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%8ld %10ld%c%.12s ", dfsize, w->w_pri, bitset(EF_WARNING, flags) ? '+' : ' ', ctime(&submittime) + 4); prtstr(&buf[1], 78); } else { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%8ld %.16s ", dfsize, ctime(&submittime)); prtstr(&buf[1], 39); } if (quarmsg[0] != '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n QUARANTINE: %.*s", Verbose ? 100 : 60, quarmsg); quarmsg[0] = '\0'; } if (statmsg[0] != '\0' || bodytype[0] != '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n %10.10s", bodytype); if (statmsg[0] != '\0') (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " (%.*s)", Verbose ? 100 : 60, statmsg); statmsg[0] = '\0'; } break; case 'C': /* controlling user */ if (Verbose) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n\t\t\t\t\t\t(---%.64s---)", &buf[1]); break; case 'R': /* recipient name */ p = &buf[1]; if (qfver >= 1) { p = strchr(p, ':'); if (p == NULL) break; p++; } if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n\t\t\t\t\t\t"); prtstr(p, 71); } else { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n\t\t\t\t\t "); prtstr(p, 38); } if (Verbose && statmsg[0] != '\0') { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n\t\t (%.100s)", statmsg); statmsg[0] = '\0'; } break; case 'T': /* creation time */ submittime = atol(&buf[1]); break; case 'F': /* flag bits */ for (p = &buf[1]; *p != '\0'; p++) { switch (*p) { case 'w': flags |= EF_WARNING; break; } } } } if (submittime == (time_t) 0) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " (no control file)"); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n"); (void) sm_io_close(f, SM_TIME_DEFAULT); } return nrequests; } /* ** QUEUE_LETTER -- get the proper queue letter for the current QueueMode. ** ** Parameters: ** e -- envelope to build it in/from. ** type -- the file type, used as the first character ** of the file name. ** ** Returns: ** the letter to use */ static char queue_letter(e, type) ENVELOPE *e; int type; { /* Change type according to QueueMode */ if (type == ANYQFL_LETTER) { if (e->e_quarmsg != NULL) type = QUARQF_LETTER; else { switch (QueueMode) { case QM_NORMAL: type = NORMQF_LETTER; break; case QM_QUARANTINE: type = QUARQF_LETTER; break; case QM_LOST: type = LOSEQF_LETTER; break; default: /* should never happen */ abort(); /* NOTREACHED */ } } } return type; } /* ** QUEUENAME -- build a file name in the queue directory for this envelope. ** ** Parameters: ** e -- envelope to build it in/from. ** type -- the file type, used as the first character ** of the file name. ** ** Returns: ** a pointer to the queue name (in a static buffer). ** ** Side Effects: ** If no id code is already assigned, queuename() will ** assign an id code with assign_queueid(). If no queue ** directory is assigned, one will be set with setnewqueue(). */ char * queuename(e, type) register ENVELOPE *e; int type; { int qd, qg; char *sub = "/"; char pref[3]; static char buf[MAXPATHLEN]; /* Assign an ID if needed */ if (e->e_id == NULL) { if (IntSig) return NULL; assign_queueid(e); } type = queue_letter(e, type); /* begin of filename */ pref[0] = (char) type; pref[1] = 'f'; pref[2] = '\0'; /* Assign a queue group/directory if needed */ if (type == XSCRPT_LETTER) { /* ** We don't want to call setnewqueue() if we are fetching ** the pathname of the transcript file, because setnewqueue ** chooses a queue, and sometimes we need to write to the ** transcript file before we have gathered enough information ** to choose a queue. */ if (e->e_xfqgrp == NOQGRP || e->e_xfqdir == NOQDIR) { if (e->e_qgrp != NOQGRP && e->e_qdir != NOQDIR) { e->e_xfqgrp = e->e_qgrp; e->e_xfqdir = e->e_qdir; } else { e->e_xfqgrp = 0; if (Queue[e->e_xfqgrp]->qg_numqueues <= 1) e->e_xfqdir = 0; else { e->e_xfqdir = get_rand_mod( Queue[e->e_xfqgrp]->qg_numqueues); } } } qd = e->e_xfqdir; qg = e->e_xfqgrp; } else { if (e->e_qgrp == NOQGRP || e->e_qdir == NOQDIR) { if (IntSig) return NULL; (void) setnewqueue(e); } if (type == DATAFL_LETTER) { qd = e->e_dfqdir; qg = e->e_dfqgrp; } else { qd = e->e_qdir; qg = e->e_qgrp; } } /* xf files always have a valid qd and qg picked above */ if ((qd == NOQDIR || qg == NOQGRP) && type != XSCRPT_LETTER) (void) sm_strlcpyn(buf, sizeof(buf), 2, pref, e->e_id); else { switch (type) { case DATAFL_LETTER: if (bitset(QP_SUBDF, Queue[qg]->qg_qpaths[qd].qp_subdirs)) sub = "/df/"; break; case QUARQF_LETTER: case TEMPQF_LETTER: case NEWQFL_LETTER: case LOSEQF_LETTER: case NORMQF_LETTER: if (bitset(QP_SUBQF, Queue[qg]->qg_qpaths[qd].qp_subdirs)) sub = "/qf/"; break; case XSCRPT_LETTER: if (bitset(QP_SUBXF, Queue[qg]->qg_qpaths[qd].qp_subdirs)) sub = "/xf/"; break; default: if (IntSig) return NULL; sm_abort("queuename: bad queue file type %d", type); } (void) sm_strlcpyn(buf, sizeof(buf), 4, Queue[qg]->qg_qpaths[qd].qp_name, sub, pref, e->e_id); } if (tTd(7, 2)) sm_dprintf("queuename: %s\n", buf); return buf; } /* ** INIT_QID_ALG -- Initialize the (static) parameters that are used to ** generate a queue ID. ** ** This function is called by the daemon to reset ** LastQueueTime and LastQueuePid which are used by assign_queueid(). ** Otherwise the algorithm may cause problems because ** LastQueueTime and LastQueuePid are set indirectly by main() ** before the daemon process is started, hence LastQueuePid is not ** the pid of the daemon and therefore a child of the daemon can ** actually have the same pid as LastQueuePid which means the section ** in assign_queueid(): ** * see if we need to get a new base time/pid * ** is NOT triggered which will cause the same queue id to be generated. ** ** Parameters: ** none ** ** Returns: ** none. */ void init_qid_alg() { LastQueueTime = 0; LastQueuePid = -1; } /* ** ASSIGN_QUEUEID -- assign a queue ID for this envelope. ** ** Assigns an id code if one does not already exist. ** This code assumes that nothing will remain in the queue for ** longer than 60 years. It is critical that files with the given ** name do not already exist in the queue. ** [No longer initializes e_qdir to NOQDIR.] ** ** Parameters: ** e -- envelope to set it in. ** ** Returns: ** none. */ static const char QueueIdChars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; # define QIC_LEN 60 # define QIC_LEN_R 62 /* ** Note: the length is "officially" 60 because minutes and seconds are ** usually only 0-59. However (Linux): ** tm_sec The number of seconds after the minute, normally in ** the range 0 to 59, but can be up to 61 to allow for ** leap seconds. ** Hence the real length of the string is 62 to take this into account. ** Alternatively % QIC_LEN can (should) be used for access everywhere. */ # define queuenextid() CurrentPid #define QIC_LEN_SQR (QIC_LEN * QIC_LEN) void assign_queueid(e) register ENVELOPE *e; { pid_t pid = queuenextid(); static unsigned int cX = 0; static unsigned int random_offset; struct tm *tm; char idbuf[MAXQFNAME - 2]; unsigned int seq; if (e->e_id != NULL) return; /* see if we need to get a new base time/pid */ if (cX >= QIC_LEN_SQR || LastQueueTime == 0 || LastQueuePid != pid) { time_t then = LastQueueTime; /* if the first time through, pick a random offset */ if (LastQueueTime == 0) random_offset = ((unsigned int)get_random()) % QIC_LEN_SQR; while ((LastQueueTime = curtime()) == then && LastQueuePid == pid) { (void) sleep(1); } LastQueuePid = queuenextid(); cX = 0; } /* ** Generate a new sequence number between 0 and QIC_LEN_SQR-1. ** This lets us generate up to QIC_LEN_SQR unique queue ids ** per second, per process. With envelope splitting, ** a single message can consume many queue ids. */ seq = (cX + random_offset) % QIC_LEN_SQR; ++cX; if (tTd(7, 50)) sm_dprintf("assign_queueid: random_offset=%u (%u)\n", random_offset, seq); tm = gmtime(&LastQueueTime); idbuf[0] = QueueIdChars[tm->tm_year % QIC_LEN]; idbuf[1] = QueueIdChars[tm->tm_mon]; idbuf[2] = QueueIdChars[tm->tm_mday]; idbuf[3] = QueueIdChars[tm->tm_hour]; idbuf[4] = QueueIdChars[tm->tm_min % QIC_LEN_R]; idbuf[5] = QueueIdChars[tm->tm_sec % QIC_LEN_R]; idbuf[6] = QueueIdChars[seq / QIC_LEN]; idbuf[7] = QueueIdChars[seq % QIC_LEN]; (void) sm_snprintf(&idbuf[8], sizeof(idbuf) - 8, "%06d", (int) LastQueuePid); e->e_id = sm_rpool_strdup_x(e->e_rpool, idbuf); macdefine(&e->e_macro, A_PERM, 'i', e->e_id); #if 0 /* XXX: inherited from MainEnvelope */ e->e_qgrp = NOQGRP; /* too early to do anything else */ e->e_qdir = NOQDIR; e->e_xfqgrp = NOQGRP; #endif /* 0 */ /* New ID means it's not on disk yet */ e->e_qfletter = '\0'; if (tTd(7, 1)) sm_dprintf("assign_queueid: assigned id %s, e=%p\n", e->e_id, e); if (LogLevel > 93) sm_syslog(LOG_DEBUG, e->e_id, "assigned id"); } /* ** SYNC_QUEUE_TIME -- Assure exclusive PID in any given second ** ** Make sure one PID can't be used by two processes in any one second. ** ** If the system rotates PIDs fast enough, may get the ** same pid in the same second for two distinct processes. ** This will interfere with the queue file naming system. ** ** Parameters: ** none ** ** Returns: ** none */ void sync_queue_time() { #if FAST_PID_RECYCLE if (OpMode != MD_TEST && OpMode != MD_CHECKCONFIG && OpMode != MD_VERIFY && LastQueueTime > 0 && LastQueuePid == CurrentPid && curtime() == LastQueueTime) (void) sleep(1); #endif /* FAST_PID_RECYCLE */ } /* ** UNLOCKQUEUE -- unlock the queue entry for a specified envelope ** ** Parameters: ** e -- the envelope to unlock. ** ** Returns: ** none ** ** Side Effects: ** unlocks the queue for `e'. */ void unlockqueue(e) ENVELOPE *e; { if (tTd(51, 4)) sm_dprintf("unlockqueue(%s)\n", e->e_id == NULL ? "NOQUEUE" : e->e_id); /* if there is a lock file in the envelope, close it */ if (e->e_lockfp != NULL) (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT); e->e_lockfp = NULL; /* don't create a queue id if we don't already have one */ if (e->e_id == NULL) return; /* remove the transcript */ if (LogLevel > 87) sm_syslog(LOG_DEBUG, e->e_id, "unlock"); if (!tTd(51, 104)) (void) xunlink(queuename(e, XSCRPT_LETTER)); } /* ** SETCTLUSER -- create a controlling address ** ** Create a fake "address" given only a local login name; this is ** used as a "controlling user" for future recipient addresses. ** ** Parameters: ** user -- the user name of the controlling user. ** qfver -- the version stamp of this queue file. ** e -- envelope ** ** Returns: ** An address descriptor for the controlling user, ** using storage allocated from e->e_rpool. ** */ static ADDRESS * setctluser(user, qfver, e) char *user; int qfver; ENVELOPE *e; { register ADDRESS *a; struct passwd *pw; char *p; /* ** See if this clears our concept of controlling user. */ if (user == NULL || *user == '\0') return NULL; /* ** Set up addr fields for controlling user. */ a = (ADDRESS *) sm_rpool_malloc_x(e->e_rpool, sizeof(*a)); memset((char *) a, '\0', sizeof(*a)); if (*user == ':') { p = &user[1]; a->q_user = sm_rpool_strdup_x(e->e_rpool, p); } else { p = strtok(user, ":"); a->q_user = sm_rpool_strdup_x(e->e_rpool, user); if (qfver >= 2) { if ((p = strtok(NULL, ":")) != NULL) a->q_uid = atoi(p); if ((p = strtok(NULL, ":")) != NULL) a->q_gid = atoi(p); if ((p = strtok(NULL, ":")) != NULL) { char *o; a->q_flags |= QGOODUID; /* if there is another ':': restore it */ if ((o = strtok(NULL, ":")) != NULL && o > p) o[-1] = ':'; } } else if ((pw = sm_getpwnam(user)) != NULL) { if (*pw->pw_dir == '\0') a->q_home = NULL; else if (strcmp(pw->pw_dir, "/") == 0) a->q_home = ""; else a->q_home = sm_rpool_strdup_x(e->e_rpool, pw->pw_dir); a->q_uid = pw->pw_uid; a->q_gid = pw->pw_gid; a->q_flags |= QGOODUID; } } a->q_flags |= QPRIMARY; /* flag as a "ctladdr" */ a->q_mailer = LocalMailer; if (p == NULL) a->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_user); else a->q_paddr = sm_rpool_strdup_x(e->e_rpool, p); return a; } /* ** LOSEQFILE -- rename queue file with LOSEQF_LETTER & try to let someone know ** ** Parameters: ** e -- the envelope (e->e_id will be used). ** why -- reported to whomever can hear. ** ** Returns: ** none. */ void loseqfile(e, why) register ENVELOPE *e; char *why; { bool loseit = true; char *p; char buf[MAXPATHLEN]; if (e == NULL || e->e_id == NULL) return; p = queuename(e, ANYQFL_LETTER); if (sm_strlcpy(buf, p, sizeof(buf)) >= sizeof(buf)) return; if (!bitset(EF_INQUEUE, e->e_flags)) queueup(e, false, true); else if (QueueMode == QM_LOST) loseit = false; /* if already lost, no need to re-lose */ if (loseit) { p = queuename(e, LOSEQF_LETTER); if (rename(buf, p) < 0) syserr("cannot rename(%s, %s), uid=%d", buf, p, (int) geteuid()); else if (LogLevel > 0) sm_syslog(LOG_ALERT, e->e_id, "Losing %s: %s", buf, why); } if (e->e_dfp != NULL) { (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT); e->e_dfp = NULL; } e->e_flags &= ~EF_HAS_DF; } /* ** NAME2QID -- translate a queue group name to a queue group id ** ** Parameters: ** queuename -- name of queue group. ** ** Returns: ** queue group id if found. ** NOQGRP otherwise. */ int name2qid(queuename) char *queuename; { register STAB *s; s = stab(queuename, ST_QUEUE, ST_FIND); if (s == NULL) return NOQGRP; return s->s_quegrp->qg_index; } /* ** QID_PRINTNAME -- create externally printable version of queue id ** ** Parameters: ** e -- the envelope. ** ** Returns: ** a printable version */ char * qid_printname(e) ENVELOPE *e; { char *id; static char idbuf[MAXQFNAME + 34]; if (e == NULL) return ""; if (e->e_id == NULL) id = ""; else id = e->e_id; if (e->e_qdir == NOQDIR) return id; (void) sm_snprintf(idbuf, sizeof(idbuf), "%.32s/%s", Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_name, id); return idbuf; } /* ** QID_PRINTQUEUE -- create full version of queue directory for data files ** ** Parameters: ** qgrp -- index in queue group. ** qdir -- the short version of the queue directory ** ** Returns: ** the full pathname to the queue (might point to a static var) */ char * qid_printqueue(qgrp, qdir) int qgrp; int qdir; { char *subdir; static char dir[MAXPATHLEN]; if (qdir == NOQDIR) return Queue[qgrp]->qg_qdir; if (strcmp(Queue[qgrp]->qg_qpaths[qdir].qp_name, ".") == 0) subdir = NULL; else subdir = Queue[qgrp]->qg_qpaths[qdir].qp_name; (void) sm_strlcpyn(dir, sizeof(dir), 4, Queue[qgrp]->qg_qdir, subdir == NULL ? "" : "/", subdir == NULL ? "" : subdir, (bitset(QP_SUBDF, Queue[qgrp]->qg_qpaths[qdir].qp_subdirs) ? "/df" : "")); return dir; } /* ** PICKQDIR -- Pick a queue directory from a queue group ** ** Parameters: ** qg -- queue group ** fsize -- file size in bytes ** e -- envelope, or NULL ** ** Result: ** NOQDIR if no queue directory in qg has enough free space to ** hold a file of size 'fsize', otherwise the index of ** a randomly selected queue directory which resides on a ** file system with enough disk space. ** XXX This could be extended to select a queuedir with ** a few (the fewest?) number of entries. That data ** is available if shared memory is used. ** ** Side Effects: ** If the request fails and e != NULL then sm_syslog is called. */ int pickqdir(qg, fsize, e) QUEUEGRP *qg; long fsize; ENVELOPE *e; { int qdir; int i; long avail = 0; /* Pick a random directory, as a starting point. */ if (qg->qg_numqueues <= 1) qdir = 0; else qdir = get_rand_mod(qg->qg_numqueues); #if _FFR_TESTS if (tTd(4, 101)) return NOQDIR; #endif /* _FFR_TESTS */ if (MinBlocksFree <= 0 && fsize <= 0) return qdir; /* ** Now iterate over the queue directories, ** looking for a directory with enough space for this message. */ i = qdir; do { QPATHS *qp = &qg->qg_qpaths[i]; long needed = 0; long fsavail = 0; if (fsize > 0) needed += fsize / FILE_SYS_BLKSIZE(qp->qp_fsysidx) + ((fsize % FILE_SYS_BLKSIZE(qp->qp_fsysidx) > 0) ? 1 : 0); if (MinBlocksFree > 0) needed += MinBlocksFree; fsavail = FILE_SYS_AVAIL(qp->qp_fsysidx); #if SM_CONF_SHM if (fsavail <= 0) { long blksize; /* ** might be not correctly updated, ** let's try to get the info directly. */ fsavail = freediskspace(FILE_SYS_NAME(qp->qp_fsysidx), &blksize); if (fsavail < 0) fsavail = 0; } #endif /* SM_CONF_SHM */ if (needed <= fsavail) return i; if (avail < fsavail) avail = fsavail; if (qg->qg_numqueues > 0) i = (i + 1) % qg->qg_numqueues; } while (i != qdir); if (e != NULL && LogLevel > 0) sm_syslog(LOG_ALERT, e->e_id, "low on space (%s needs %ld bytes + %ld blocks in %s), max avail: %ld", CurHostName == NULL ? "SMTP-DAEMON" : CurHostName, fsize, MinBlocksFree, qg->qg_qdir, avail); return NOQDIR; } /* ** SETNEWQUEUE -- Sets a new queue group and directory ** ** Assign a queue group and directory to an envelope and store the ** directory in e->e_qdir. ** ** Parameters: ** e -- envelope to assign a queue for. ** ** Returns: ** true if successful ** false otherwise ** ** Side Effects: ** On success, e->e_qgrp and e->e_qdir are non-negative. ** On failure (not enough disk space), ** e->qgrp = NOQGRP, e->e_qdir = NOQDIR ** and usrerr() is invoked (which could raise an exception). */ bool setnewqueue(e) ENVELOPE *e; { if (tTd(41, 20)) sm_dprintf("setnewqueue: called\n"); /* not set somewhere else */ if (e->e_qgrp == NOQGRP) { ADDRESS *q; /* ** Use the queue group of the "first" recipient, as set by ** the "queuegroup" rule set. If that is not defined, then ** use the queue group of the mailer of the first recipient. ** If that is not defined either, then use the default ** queue group. ** Notice: "first" depends on the sorting of sendqueue ** in recipient(). ** To avoid problems with "bad" recipients look ** for a valid address first. */ q = e->e_sendqueue; while (q != NULL && (QS_IS_BADADDR(q->q_state) || QS_IS_DEAD(q->q_state))) { q = q->q_next; } if (q == NULL) e->e_qgrp = 0; else if (q->q_qgrp >= 0) e->e_qgrp = q->q_qgrp; else if (q->q_mailer != NULL && ISVALIDQGRP(q->q_mailer->m_qgrp)) e->e_qgrp = q->q_mailer->m_qgrp; else e->e_qgrp = 0; e->e_dfqgrp = e->e_qgrp; } if (ISVALIDQDIR(e->e_qdir) && ISVALIDQDIR(e->e_dfqdir)) { if (tTd(41, 20)) sm_dprintf("setnewqueue: e_qdir already assigned (%s)\n", qid_printqueue(e->e_qgrp, e->e_qdir)); return true; } filesys_update(); e->e_qdir = pickqdir(Queue[e->e_qgrp], e->e_msgsize, e); if (e->e_qdir == NOQDIR) { e->e_qgrp = NOQGRP; if (!bitset(EF_FATALERRS, e->e_flags)) usrerr("452 4.4.5 Insufficient disk space; try again later"); e->e_flags |= EF_FATALERRS; return false; } if (tTd(41, 3)) sm_dprintf("setnewqueue: Assigned queue directory %s\n", qid_printqueue(e->e_qgrp, e->e_qdir)); if (e->e_xfqgrp == NOQGRP || e->e_xfqdir == NOQDIR) { e->e_xfqgrp = e->e_qgrp; e->e_xfqdir = e->e_qdir; } e->e_dfqdir = e->e_qdir; return true; } /* ** CHKQDIR -- check a queue directory ** ** Parameters: ** name -- name of queue directory ** sff -- flags for safefile() ** ** Returns: ** is it a queue directory? */ static bool chkqdir __P((char *, long)); static bool chkqdir(name, sff) char *name; long sff; { struct stat statb; int i; /* skip over . and .. directories */ if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'))) return false; #if HASLSTAT if (lstat(name, &statb) < 0) #else /* HASLSTAT */ if (stat(name, &statb) < 0) #endif /* HASLSTAT */ { if (tTd(41, 2)) sm_dprintf("chkqdir: stat(\"%s\"): %s\n", name, sm_errstring(errno)); return false; } #if HASLSTAT if (S_ISLNK(statb.st_mode)) { /* ** For a symlink we need to make sure the ** target is a directory */ if (stat(name, &statb) < 0) { if (tTd(41, 2)) sm_dprintf("chkqdir: stat(\"%s\"): %s\n", name, sm_errstring(errno)); return false; } } #endif /* HASLSTAT */ if (!S_ISDIR(statb.st_mode)) { if (tTd(41, 2)) sm_dprintf("chkqdir: \"%s\": Not a directory\n", name); return false; } /* Print a warning if unsafe (but still use it) */ /* XXX do this only if we want the warning? */ i = safedirpath(name, RunAsUid, RunAsGid, NULL, sff, 0, 0); if (i != 0) { if (tTd(41, 2)) sm_dprintf("chkqdir: \"%s\": Not safe: %s\n", name, sm_errstring(i)); #if _FFR_CHK_QUEUE if (LogLevel > 8) sm_syslog(LOG_WARNING, NOQID, "queue directory \"%s\": Not safe: %s", name, sm_errstring(i)); #endif /* _FFR_CHK_QUEUE */ } return true; } /* ** MULTIQUEUE_CACHE -- cache a list of paths to queues. ** ** Each potential queue is checked as the cache is built. ** Thereafter, each is blindly trusted. ** Note that we can be called again after a timeout to rebuild ** (although code for that is not ready yet). ** ** Parameters: ** basedir -- base of all queue directories. ** blen -- strlen(basedir). ** qg -- queue group. ** qn -- number of queue directories already cached. ** phash -- pointer to hash value over queue dirs. #if SM_CONF_SHM ** only used if shared memory is active. #endif * SM_CONF_SHM * ** ** Returns: ** new number of queue directories. */ #define INITIAL_SLOTS 20 #define ADD_SLOTS 10 static int multiqueue_cache(basedir, blen, qg, qn, phash) char *basedir; int blen; QUEUEGRP *qg; int qn; unsigned int *phash; { char *cp; int i, len; int slotsleft = 0; long sff = SFF_ANYFILE; char qpath[MAXPATHLEN]; char subdir[MAXPATHLEN]; char prefix[MAXPATHLEN]; /* dir relative to basedir */ if (tTd(41, 20)) sm_dprintf("multiqueue_cache: called\n"); /* Initialize to current directory */ prefix[0] = '.'; prefix[1] = '\0'; if (qg->qg_numqueues != 0 && qg->qg_qpaths != NULL) { for (i = 0; i < qg->qg_numqueues; i++) { if (qg->qg_qpaths[i].qp_name != NULL) (void) sm_free(qg->qg_qpaths[i].qp_name); /* XXX */ } (void) sm_free((char *) qg->qg_qpaths); /* XXX */ qg->qg_qpaths = NULL; qg->qg_numqueues = 0; } /* If running as root, allow safedirpath() checks to use privs */ if (RunAsUid == 0) sff |= SFF_ROOTOK; #if _FFR_CHK_QUEUE sff |= SFF_SAFEDIRPATH|SFF_NOWWFILES; if (!UseMSP) sff |= SFF_NOGWFILES; #endif /* _FFR_CHK_QUEUE */ if (!SM_IS_DIR_START(qg->qg_qdir)) { /* ** XXX we could add basedir, but then we have to realloc() ** the string... Maybe another time. */ syserr("QueuePath %s not absolute", qg->qg_qdir); ExitStat = EX_CONFIG; return qn; } /* qpath: directory of current workgroup */ len = sm_strlcpy(qpath, qg->qg_qdir, sizeof(qpath)); if (len >= sizeof(qpath)) { syserr("QueuePath %.256s too long (%d max)", qg->qg_qdir, (int) sizeof(qpath)); ExitStat = EX_CONFIG; return qn; } /* begin of qpath must be same as basedir */ if (strncmp(basedir, qpath, blen) != 0 && (strncmp(basedir, qpath, blen - 1) != 0 || len != blen - 1)) { syserr("QueuePath %s not subpath of QueueDirectory %s", qpath, basedir); ExitStat = EX_CONFIG; return qn; } /* Do we have a nested subdirectory? */ if (blen < len && SM_FIRST_DIR_DELIM(qg->qg_qdir + blen) != NULL) { /* Copy subdirectory into prefix for later use */ if (sm_strlcpy(prefix, qg->qg_qdir + blen, sizeof(prefix)) >= sizeof(prefix)) { syserr("QueuePath %.256s too long (%d max)", qg->qg_qdir, (int) sizeof(qpath)); ExitStat = EX_CONFIG; return qn; } cp = SM_LAST_DIR_DELIM(prefix); SM_ASSERT(cp != NULL); *cp = '\0'; /* cut off trailing / */ } /* This is guaranteed by the basedir check above */ SM_ASSERT(len >= blen - 1); cp = &qpath[len - 1]; if (*cp == '*') { register DIR *dp; register struct dirent *d; int off; char *delim; char relpath[MAXPATHLEN]; *cp = '\0'; /* Overwrite wildcard */ if ((cp = SM_LAST_DIR_DELIM(qpath)) == NULL) { syserr("QueueDirectory: can not wildcard relative path"); if (tTd(41, 2)) sm_dprintf("multiqueue_cache: \"%s*\": Can not wildcard relative path.\n", qpath); ExitStat = EX_CONFIG; return qn; } if (cp == qpath) { /* ** Special case of top level wildcard, like /foo* ** Change to //foo* */ (void) sm_strlcpy(qpath + 1, qpath, sizeof(qpath) - 1); ++cp; } delim = cp; *(cp++) = '\0'; /* Replace / with \0 */ len = strlen(cp); /* Last component of queue directory */ /* ** Path relative to basedir, with trailing / ** It will be modified below to specify the subdirectories ** so they can be opened without chdir(). */ off = sm_strlcpyn(relpath, sizeof(relpath), 2, prefix, "/"); SM_ASSERT(off < sizeof(relpath)); if (tTd(41, 2)) sm_dprintf("multiqueue_cache: prefix=\"%s%s\"\n", relpath, cp); /* It is always basedir: we don't need to store it per group */ /* XXX: optimize this! -> one more global? */ qg->qg_qdir = newstr(basedir); qg->qg_qdir[blen - 1] = '\0'; /* cut off trailing / */ /* ** XXX Should probably wrap this whole loop in a timeout ** in case some wag decides to NFS mount the queues. */ /* Test path to get warning messages. */ if (qn == 0) { /* XXX qg_runasuid and qg_runasgid for specials? */ i = safedirpath(basedir, RunAsUid, RunAsGid, NULL, sff, 0, 0); if (i != 0 && tTd(41, 2)) sm_dprintf("multiqueue_cache: \"%s\": Not safe: %s\n", basedir, sm_errstring(i)); } if ((dp = opendir(prefix)) == NULL) { syserr("can not opendir(%s/%s)", qg->qg_qdir, prefix); if (tTd(41, 2)) sm_dprintf("multiqueue_cache: opendir(\"%s/%s\"): %s\n", qg->qg_qdir, prefix, sm_errstring(errno)); ExitStat = EX_CONFIG; return qn; } while ((d = readdir(dp)) != NULL) { /* Skip . and .. directories */ if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) continue; i = strlen(d->d_name); if (i < len || strncmp(d->d_name, cp, len) != 0) { if (tTd(41, 5)) sm_dprintf("multiqueue_cache: \"%s\", skipped\n", d->d_name); continue; } /* Create relative pathname: prefix + local directory */ i = sizeof(relpath) - off; if (sm_strlcpy(relpath + off, d->d_name, i) >= i) continue; /* way too long */ if (!chkqdir(relpath, sff)) continue; if (qg->qg_qpaths == NULL) { slotsleft = INITIAL_SLOTS; qg->qg_qpaths = (QPATHS *)xalloc((sizeof(*qg->qg_qpaths)) * slotsleft); qg->qg_numqueues = 0; } else if (slotsleft < 1) { qg->qg_qpaths = (QPATHS *)sm_realloc((char *)qg->qg_qpaths, (sizeof(*qg->qg_qpaths)) * (qg->qg_numqueues + ADD_SLOTS)); if (qg->qg_qpaths == NULL) { (void) closedir(dp); return qn; } slotsleft += ADD_SLOTS; } /* check subdirs */ qg->qg_qpaths[qg->qg_numqueues].qp_subdirs = QP_NOSUB; #define CHKRSUBDIR(name, flag) \ (void) sm_strlcpyn(subdir, sizeof(subdir), 3, relpath, "/", name); \ if (chkqdir(subdir, sff)) \ qg->qg_qpaths[qg->qg_numqueues].qp_subdirs |= flag; \ else CHKRSUBDIR("qf", QP_SUBQF); CHKRSUBDIR("df", QP_SUBDF); CHKRSUBDIR("xf", QP_SUBXF); /* assert(strlen(d->d_name) < MAXPATHLEN - 14) */ /* maybe even - 17 (subdirs) */ if (prefix[0] != '.') qg->qg_qpaths[qg->qg_numqueues].qp_name = newstr(relpath); else qg->qg_qpaths[qg->qg_numqueues].qp_name = newstr(d->d_name); if (tTd(41, 2)) sm_dprintf("multiqueue_cache: %d: \"%s\" cached (%x).\n", qg->qg_numqueues, relpath, qg->qg_qpaths[qg->qg_numqueues].qp_subdirs); #if SM_CONF_SHM qg->qg_qpaths[qg->qg_numqueues].qp_idx = qn; *phash = hash_q(relpath, *phash); #endif /* SM_CONF_SHM */ qg->qg_numqueues++; ++qn; slotsleft--; } (void) closedir(dp); /* undo damage */ *delim = '/'; } if (qg->qg_numqueues == 0) { qg->qg_qpaths = (QPATHS *) xalloc(sizeof(*qg->qg_qpaths)); /* test path to get warning messages */ i = safedirpath(qpath, RunAsUid, RunAsGid, NULL, sff, 0, 0); if (i == ENOENT) { syserr("can not opendir(%s)", qpath); if (tTd(41, 2)) sm_dprintf("multiqueue_cache: opendir(\"%s\"): %s\n", qpath, sm_errstring(i)); ExitStat = EX_CONFIG; return qn; } qg->qg_qpaths[0].qp_subdirs = QP_NOSUB; qg->qg_numqueues = 1; /* check subdirs */ #define CHKSUBDIR(name, flag) \ (void) sm_strlcpyn(subdir, sizeof(subdir), 3, qg->qg_qdir, "/", name); \ if (chkqdir(subdir, sff)) \ qg->qg_qpaths[0].qp_subdirs |= flag; \ else CHKSUBDIR("qf", QP_SUBQF); CHKSUBDIR("df", QP_SUBDF); CHKSUBDIR("xf", QP_SUBXF); if (qg->qg_qdir[blen - 1] != '\0' && qg->qg_qdir[blen] != '\0') { /* ** Copy the last component into qpaths and ** cut off qdir */ qg->qg_qpaths[0].qp_name = newstr(qg->qg_qdir + blen); qg->qg_qdir[blen - 1] = '\0'; } else qg->qg_qpaths[0].qp_name = newstr("."); #if SM_CONF_SHM qg->qg_qpaths[0].qp_idx = qn; *phash = hash_q(qg->qg_qpaths[0].qp_name, *phash); #endif /* SM_CONF_SHM */ ++qn; } return qn; } /* ** FILESYS_FIND -- find entry in FileSys table, or add new one ** ** Given the pathname of a directory, determine the file system ** in which that directory resides, and return a pointer to the ** entry in the FileSys table that describes the file system. ** A new entry is added if necessary (and requested). ** If the directory does not exist, -1 is returned. ** ** Parameters: ** name -- name of directory (must be persistent!) ** path -- pathname of directory (name plus maybe "/df") ** add -- add to structure if not found. ** ** Returns: ** >=0: found: index in file system table ** <0: some error, i.e., ** FSF_TOO_MANY: too many filesystems (-> syserr()) ** FSF_STAT_FAIL: can't stat() filesystem (-> syserr()) ** FSF_NOT_FOUND: not in list */ static short filesys_find __P((const char *, const char *, bool)); #define FSF_NOT_FOUND (-1) #define FSF_STAT_FAIL (-2) #define FSF_TOO_MANY (-3) static short filesys_find(name, path, add) const char *name; const char *path; bool add; { struct stat st; short i; if (stat(path, &st) < 0) { syserr("cannot stat queue directory %s", path); return FSF_STAT_FAIL; } for (i = 0; i < NumFileSys; ++i) { if (FILE_SYS_DEV(i) == st.st_dev) { /* ** Make sure the file system (FS) name is set: ** even though the source code indicates that ** FILE_SYS_DEV() is only set below, it could be ** set via shared memory, hence we need to perform ** this check/assignment here. */ if (NULL == FILE_SYS_NAME(i)) FILE_SYS_NAME(i) = name; return i; } } if (i >= MAXFILESYS) { syserr("too many queue file systems (%d max)", MAXFILESYS); return FSF_TOO_MANY; } if (!add) return FSF_NOT_FOUND; ++NumFileSys; FILE_SYS_NAME(i) = name; FILE_SYS_DEV(i) = st.st_dev; FILE_SYS_AVAIL(i) = 0; FILE_SYS_BLKSIZE(i) = 1024; /* avoid divide by zero */ return i; } /* ** FILESYS_SETUP -- set up mapping from queue directories to file systems ** ** This data structure is used to efficiently check the amount of ** free space available in a set of queue directories. ** ** Parameters: ** add -- initialize structure if necessary. ** ** Returns: ** 0: success ** <0: some error, i.e., ** FSF_NOT_FOUND: not in list ** FSF_STAT_FAIL: can't stat() filesystem (-> syserr()) ** FSF_TOO_MANY: too many filesystems (-> syserr()) */ static int filesys_setup __P((bool)); static int filesys_setup(add) bool add; { int i, j; short fs; int ret; ret = 0; for (i = 0; i < NumQueue && Queue[i] != NULL; i++) { for (j = 0; j < Queue[i]->qg_numqueues; ++j) { QPATHS *qp = &Queue[i]->qg_qpaths[j]; char qddf[MAXPATHLEN]; (void) sm_strlcpyn(qddf, sizeof(qddf), 2, qp->qp_name, (bitset(QP_SUBDF, qp->qp_subdirs) ? "/df" : "")); fs = filesys_find(qp->qp_name, qddf, add); if (fs >= 0) qp->qp_fsysidx = fs; else qp->qp_fsysidx = 0; if (fs < ret) ret = fs; } } return ret; } /* ** FILESYS_UPDATE -- update amount of free space on all file systems ** ** The FileSys table is used to cache the amount of free space ** available on all queue directory file systems. ** This function updates the cached information if it has expired. ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** Updates FileSys table. */ void filesys_update() { int i; long avail, blksize; time_t now; static time_t nextupdate = 0; #if SM_CONF_SHM /* ** Only the daemon updates the shared memory, i.e., ** if shared memory is available but the pid is not the ** one of the daemon, then don't do anything. */ if (ShmId != SM_SHM_NO_ID && DaemonPid != CurrentPid) return; #endif /* SM_CONF_SHM */ now = curtime(); if (now < nextupdate) return; nextupdate = now + FILESYS_UPDATE_INTERVAL; for (i = 0; i < NumFileSys; ++i) { FILESYS *fs = &FILE_SYS(i); avail = freediskspace(FILE_SYS_NAME(i), &blksize); if (avail < 0 || blksize <= 0) { if (LogLevel > 5) sm_syslog(LOG_ERR, NOQID, "filesys_update failed: %s, fs=%s, avail=%ld, blocksize=%ld", sm_errstring(errno), FILE_SYS_NAME(i), avail, blksize); fs->fs_avail = 0; fs->fs_blksize = 1024; /* avoid divide by zero */ nextupdate = now + 2; /* let's do this soon again */ } else { fs->fs_avail = avail; fs->fs_blksize = blksize; } } } #if _FFR_ANY_FREE_FS /* ** FILESYS_FREE -- check whether there is at least one fs with enough space. ** ** Parameters: ** fsize -- file size in bytes ** ** Returns: ** true iff there is one fs with more than fsize bytes free. */ bool filesys_free(fsize) long fsize; { int i; if (fsize <= 0) return true; for (i = 0; i < NumFileSys; ++i) { long needed = 0; if (FILE_SYS_AVAIL(i) < 0 || FILE_SYS_BLKSIZE(i) <= 0) continue; needed += fsize / FILE_SYS_BLKSIZE(i) + ((fsize % FILE_SYS_BLKSIZE(i) > 0) ? 1 : 0) + MinBlocksFree; if (needed <= FILE_SYS_AVAIL(i)) return true; } return false; } #endif /* _FFR_ANY_FREE_FS */ /* ** DISK_STATUS -- show amount of free space in queue directories ** ** Parameters: ** out -- output file pointer. ** prefix -- string to output in front of each line. ** ** Returns: ** none. */ void disk_status(out, prefix) SM_FILE_T *out; char *prefix; { int i; long avail, blksize; long free; for (i = 0; i < NumFileSys; ++i) { avail = freediskspace(FILE_SYS_NAME(i), &blksize); if (avail >= 0 && blksize > 0) { free = (long)((double) avail * ((double) blksize / 1024)); } else free = -1; (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%s%d/%s/%ld\r\n", prefix, i, FILE_SYS_NAME(i), free); } } #if SM_CONF_SHM /* ** INIT_SEM -- initialize semaphore system ** ** Parameters: ** owner -- is this the owner of semaphores? ** ** Returns: ** none. */ #if _FFR_USE_SEM_LOCKING #if SM_CONF_SEM static int SemId = -1; /* Semaphore Id */ int SemKey = SM_SEM_KEY; #endif /* SM_CONF_SEM */ #endif /* _FFR_USE_SEM_LOCKING */ static void init_sem __P((bool)); static void init_sem(owner) bool owner; { #if _FFR_USE_SEM_LOCKING #if SM_CONF_SEM SemId = sm_sem_start(SemKey, 1, 0, owner); if (SemId < 0) { sm_syslog(LOG_ERR, NOQID, "func=init_sem, sem_key=%ld, sm_sem_start=%d, error=%s", (long) SemKey, SemId, sm_errstring(-SemId)); return; } if (owner && RunAsUid != 0) { int r; r = sm_semsetowner(SemId, RunAsUid, RunAsGid, 0660); if (r != 0) sm_syslog(LOG_ERR, NOQID, "key=%ld, sm_semsetowner=%d, RunAsUid=%d, RunAsGid=%d", (long) SemKey, r, RunAsUid, RunAsGid); } #endif /* SM_CONF_SEM */ #endif /* _FFR_USE_SEM_LOCKING */ return; } /* ** STOP_SEM -- stop semaphore system ** ** Parameters: ** owner -- is this the owner of semaphores? ** ** Returns: ** none. */ static void stop_sem __P((bool)); static void stop_sem(owner) bool owner; { #if _FFR_USE_SEM_LOCKING #if SM_CONF_SEM if (owner && SemId >= 0) sm_sem_stop(SemId); #endif /* SM_CONF_SEM */ #endif /* _FFR_USE_SEM_LOCKING */ return; } /* ** UPD_QS -- update information about queue when adding/deleting an entry ** ** Parameters: ** e -- envelope. ** count -- add/remove entry (+1/0/-1: add/no change/remove) ** space -- update the space available as well. ** (>0/0/<0: add/no change/remove) ** where -- caller (for logging) ** ** Returns: ** none. ** ** Side Effects: ** Modifies available space in filesystem. ** Changes number of entries in queue directory. */ void upd_qs(e, count, space, where) ENVELOPE *e; int count; int space; char *where; { short fidx; int idx; # if _FFR_USE_SEM_LOCKING int r; # endif /* _FFR_USE_SEM_LOCKING */ long s; if (ShmId == SM_SHM_NO_ID || e == NULL) return; if (e->e_qgrp == NOQGRP || e->e_qdir == NOQDIR) return; idx = Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_idx; if (tTd(73,2)) sm_dprintf("func=upd_qs, count=%d, space=%d, where=%s, idx=%d, entries=%d\n", count, space, where, idx, QSHM_ENTRIES(idx)); /* XXX in theory this needs to be protected with a mutex */ if (QSHM_ENTRIES(idx) >= 0 && count != 0) { # if _FFR_USE_SEM_LOCKING r = sm_sem_acq(SemId, 0, 1); # endif /* _FFR_USE_SEM_LOCKING */ QSHM_ENTRIES(idx) += count; # if _FFR_USE_SEM_LOCKING if (r >= 0) r = sm_sem_rel(SemId, 0, 1); # endif /* _FFR_USE_SEM_LOCKING */ } fidx = Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_fsysidx; if (fidx < 0) return; /* update available space also? (might be loseqfile) */ if (space == 0) return; /* convert size to blocks; this causes rounding errors */ s = e->e_msgsize / FILE_SYS_BLKSIZE(fidx); if (s == 0) return; /* XXX in theory this needs to be protected with a mutex */ if (space > 0) FILE_SYS_AVAIL(fidx) += s; else FILE_SYS_AVAIL(fidx) -= s; } static bool write_key_file __P((char *, long)); static long read_key_file __P((char *, long)); /* ** WRITE_KEY_FILE -- record some key into a file. ** ** Parameters: ** keypath -- file name. ** key -- key to write. ** ** Returns: ** true iff file could be written. ** ** Side Effects: ** writes file. */ static bool write_key_file(keypath, key) char *keypath; long key; { bool ok; long sff; SM_FILE_T *keyf; ok = false; if (keypath == NULL || *keypath == '\0') return ok; sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY|SFF_CREAT; if (TrustedUid != 0 && RealUid == TrustedUid) sff |= SFF_OPENASROOT; keyf = safefopen(keypath, O_WRONLY|O_TRUNC, FileMode, sff); if (keyf == NULL) { sm_syslog(LOG_ERR, NOQID, "unable to write %s: %s", keypath, sm_errstring(errno)); } else { if (geteuid() == 0 && RunAsUid != 0) { # if HASFCHOWN int fd; fd = keyf->f_file; if (fd >= 0 && fchown(fd, RunAsUid, -1) < 0) { int err = errno; sm_syslog(LOG_ALERT, NOQID, "ownership change on %s to %d failed: %s", keypath, RunAsUid, sm_errstring(err)); } # endif /* HASFCHOWN */ } ok = sm_io_fprintf(keyf, SM_TIME_DEFAULT, "%ld\n", key) != SM_IO_EOF; ok = (sm_io_close(keyf, SM_TIME_DEFAULT) != SM_IO_EOF) && ok; } return ok; } /* ** READ_KEY_FILE -- read a key from a file. ** ** Parameters: ** keypath -- file name. ** key -- default key. ** ** Returns: ** key. */ static long read_key_file(keypath, key) char *keypath; long key; { int r; long sff, n; SM_FILE_T *keyf; if (keypath == NULL || *keypath == '\0') return key; sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY; if (RealUid == 0 || (TrustedUid != 0 && RealUid == TrustedUid)) sff |= SFF_OPENASROOT; keyf = safefopen(keypath, O_RDONLY, FileMode, sff); if (keyf == NULL) { sm_syslog(LOG_ERR, NOQID, "unable to read %s: %s", keypath, sm_errstring(errno)); } else { r = sm_io_fscanf(keyf, SM_TIME_DEFAULT, "%ld", &n); if (r == 1) key = n; (void) sm_io_close(keyf, SM_TIME_DEFAULT); } return key; } /* ** INIT_SHM -- initialize shared memory structure ** ** Initialize or attach to shared memory segment. ** Currently it is not a fatal error if this doesn't work. ** However, it causes us to have a "fallback" storage location ** for everything that is supposed to be in the shared memory, ** which makes the code slightly ugly. ** ** Parameters: ** qn -- number of queue directories. ** owner -- owner of shared memory. ** hash -- identifies data that is stored in shared memory. ** ** Returns: ** none. */ static void init_shm __P((int, bool, unsigned int)); static void init_shm(qn, owner, hash) int qn; bool owner; unsigned int hash; { int i; int count; int save_errno; bool keyselect; PtrFileSys = &FileSys[0]; PNumFileSys = &Numfilesys; /* if this "key" is specified: select one yourself */ #define SEL_SHM_KEY ((key_t) -1) #define FIRST_SHM_KEY 25 /* This allows us to disable shared memory at runtime. */ if (ShmKey == 0) return; count = 0; shms = SM_T_SIZE + qn * sizeof(QUEUE_SHM_T); keyselect = ShmKey == SEL_SHM_KEY; if (keyselect) { if (owner) ShmKey = FIRST_SHM_KEY; else { errno = 0; ShmKey = read_key_file(ShmKeyFile, ShmKey); keyselect = false; if (ShmKey == SEL_SHM_KEY) { save_errno = (errno != 0) ? errno : EINVAL; goto error; } } } for (;;) { /* allow read/write access for group? */ Pshm = sm_shmstart(ShmKey, shms, SHM_R|SHM_W|(SHM_R>>3)|(SHM_W>>3), &ShmId, owner); save_errno = errno; if (Pshm != NULL || !sm_file_exists(save_errno)) break; if (++count >= 3) { if (keyselect) { ++ShmKey; /* back where we started? */ if (ShmKey == SEL_SHM_KEY) break; continue; } break; } /* only sleep if we are at the first key */ if (!keyselect || ShmKey == SEL_SHM_KEY) sleep(count); } if (Pshm != NULL) { int *p; if (keyselect) (void) write_key_file(ShmKeyFile, (long) ShmKey); if (owner && RunAsUid != 0) { i = sm_shmsetowner(ShmId, RunAsUid, RunAsGid, 0660); if (i != 0) sm_syslog(LOG_ERR, NOQID, "key=%ld, sm_shmsetowner=%d, RunAsUid=%d, RunAsGid=%d", (long) ShmKey, i, RunAsUid, RunAsGid); } p = (int *) Pshm; if (owner) { *p = (int) shms; *((pid_t *) SHM_OFF_PID(Pshm)) = CurrentPid; p = (int *) SHM_OFF_TAG(Pshm); *p = hash; } else { if (*p != (int) shms) { save_errno = EINVAL; cleanup_shm(false); goto error; } p = (int *) SHM_OFF_TAG(Pshm); if (*p != (int) hash) { save_errno = EINVAL; cleanup_shm(false); goto error; } /* ** XXX how to check the pid? ** Read it from the pid-file? That does ** not need to exist. ** We could disable shm if we can't confirm ** that it is the right one. */ } PtrFileSys = (FILESYS *) OFF_FILE_SYS(Pshm); PNumFileSys = (int *) OFF_NUM_FILE_SYS(Pshm); QShm = (QUEUE_SHM_T *) OFF_QUEUE_SHM(Pshm); PRSATmpCnt = (int *) OFF_RSA_TMP_CNT(Pshm); *PRSATmpCnt = 0; if (owner) { /* initialize values in shared memory */ NumFileSys = 0; for (i = 0; i < qn; i++) QShm[i].qs_entries = -1; } init_sem(owner); return; } error: if (LogLevel > (owner ? 8 : 11)) { sm_syslog(owner ? LOG_ERR : LOG_NOTICE, NOQID, "can't %s shared memory, key=%ld: %s", owner ? "initialize" : "attach to", (long) ShmKey, sm_errstring(save_errno)); } } #endif /* SM_CONF_SHM */ /* ** SETUP_QUEUES -- set up all queue groups ** ** Parameters: ** owner -- owner of shared memory? ** ** Returns: ** none. ** #if SM_CONF_SHM ** Side Effects: ** attaches shared memory. #endif * SM_CONF_SHM * */ void setup_queues(owner) bool owner; { int i, qn, len; unsigned int hashval; time_t now; char basedir[MAXPATHLEN]; struct stat st; /* ** Determine basedir for all queue directories. ** All queue directories must be (first level) subdirectories ** of the basedir. The basedir is the QueueDir ** without wildcards, but with trailing / */ hashval = 0; errno = 0; len = sm_strlcpy(basedir, QueueDir, sizeof(basedir)); /* Provide space for trailing '/' */ if (len >= sizeof(basedir) - 1) { syserr("QueueDirectory: path too long: %d, max %d", len, (int) sizeof(basedir) - 1); ExitStat = EX_CONFIG; return; } SM_ASSERT(len > 0); if (basedir[len - 1] == '*') { char *cp; cp = SM_LAST_DIR_DELIM(basedir); if (cp == NULL) { syserr("QueueDirectory: can not wildcard relative path \"%s\"", QueueDir); if (tTd(41, 2)) sm_dprintf("setup_queues: \"%s\": Can not wildcard relative path.\n", QueueDir); ExitStat = EX_CONFIG; return; } /* cut off wildcard pattern */ *++cp = '\0'; len = cp - basedir; } else if (!SM_IS_DIR_DELIM(basedir[len - 1])) { /* append trailing slash since it is a directory */ basedir[len] = '/'; basedir[++len] = '\0'; } /* len counts up to the last directory delimiter */ SM_ASSERT(basedir[len - 1] == '/'); if (chdir(basedir) < 0) { int save_errno = errno; syserr("can not chdir(%s)", basedir); if (save_errno == EACCES) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "Program mode requires special privileges, e.g., root or TrustedUser.\n"); if (tTd(41, 2)) sm_dprintf("setup_queues: \"%s\": %s\n", basedir, sm_errstring(errno)); ExitStat = EX_CONFIG; return; } #if SM_CONF_SHM hashval = hash_q(basedir, hashval); #endif /* SM_CONF_SHM */ /* initialize for queue runs */ DoQueueRun = false; now = curtime(); for (i = 0; i < NumQueue && Queue[i] != NULL; i++) Queue[i]->qg_nextrun = now; if (UseMSP && OpMode != MD_TEST) { long sff = SFF_CREAT; if (stat(".", &st) < 0) { syserr("can not stat(%s)", basedir); if (tTd(41, 2)) sm_dprintf("setup_queues: \"%s\": %s\n", basedir, sm_errstring(errno)); ExitStat = EX_CONFIG; return; } if (RunAsUid == 0) sff |= SFF_ROOTOK; /* ** Check queue directory permissions. ** Can we write to a group writable queue directory? */ if (bitset(S_IWGRP, QueueFileMode) && bitset(S_IWGRP, st.st_mode) && safefile(" ", RunAsUid, RunAsGid, RunAsUserName, sff, QueueFileMode, NULL) != 0) { syserr("can not write to queue directory %s (RunAsGid=%d, required=%d)", basedir, (int) RunAsGid, (int) st.st_gid); } if (bitset(S_IWOTH|S_IXOTH, st.st_mode)) { #if _FFR_MSP_PARANOIA syserr("dangerous permissions=%o on queue directory %s", (int) st.st_mode, basedir); #else /* _FFR_MSP_PARANOIA */ if (LogLevel > 0) sm_syslog(LOG_ERR, NOQID, "dangerous permissions=%o on queue directory %s", (int) st.st_mode, basedir); #endif /* _FFR_MSP_PARANOIA */ } #if _FFR_MSP_PARANOIA if (NumQueue > 1) syserr("can not use multiple queues for MSP"); #endif /* _FFR_MSP_PARANOIA */ } /* initial number of queue directories */ qn = 0; for (i = 0; i < NumQueue && Queue[i] != NULL; i++) qn = multiqueue_cache(basedir, len, Queue[i], qn, &hashval); #if SM_CONF_SHM init_shm(qn, owner, hashval); i = filesys_setup(owner || ShmId == SM_SHM_NO_ID); if (i == FSF_NOT_FOUND) { /* ** We didn't get the right filesystem data ** This may happen if we don't have the right shared memory. ** So let's do this without shared memory. */ SM_ASSERT(!owner); cleanup_shm(false); /* release shared memory */ i = filesys_setup(false); if (i < 0) syserr("filesys_setup failed twice, result=%d", i); else if (LogLevel > 8) sm_syslog(LOG_WARNING, NOQID, "shared memory does not contain expected data, ignored"); } #else /* SM_CONF_SHM */ i = filesys_setup(true); #endif /* SM_CONF_SHM */ if (i < 0) ExitStat = EX_CONFIG; } #if SM_CONF_SHM /* ** CLEANUP_SHM -- do some cleanup work for shared memory etc ** ** Parameters: ** owner -- owner of shared memory? ** ** Returns: ** none. ** ** Side Effects: ** detaches shared memory. */ void cleanup_shm(owner) bool owner; { if (ShmId != SM_SHM_NO_ID) { if (sm_shmstop(Pshm, ShmId, owner) < 0 && LogLevel > 8) sm_syslog(LOG_INFO, NOQID, "sm_shmstop failed=%s", sm_errstring(errno)); Pshm = NULL; ShmId = SM_SHM_NO_ID; } stop_sem(owner); } #endif /* SM_CONF_SHM */ /* ** CLEANUP_QUEUES -- do some cleanup work for queues ** ** Parameters: ** none. ** ** Returns: ** none. ** */ void cleanup_queues() { sync_queue_time(); } /* ** SET_DEF_QUEUEVAL -- set default values for a queue group. ** ** Parameters: ** qg -- queue group ** all -- set all values (true for default group)? ** ** Returns: ** none. ** ** Side Effects: ** sets default values for the queue group. */ void set_def_queueval(qg, all) QUEUEGRP *qg; bool all; { if (bitnset(QD_DEFINED, qg->qg_flags)) return; if (all) qg->qg_qdir = QueueDir; #if _FFR_QUEUE_GROUP_SORTORDER qg->qg_sortorder = QueueSortOrder; #endif /* _FFR_QUEUE_GROUP_SORTORDER */ qg->qg_maxqrun = all ? MaxRunnersPerQueue : -1; qg->qg_nice = NiceQueueRun; } /* ** MAKEQUEUE -- define a new queue. ** ** Parameters: ** line -- description of queue. This is in labeled fields. ** The fields are: ** F -- the flags associated with the queue ** I -- the interval between running the queue ** J -- the maximum # of jobs in work list ** [M -- the maximum # of jobs in a queue run] ** N -- the niceness at which to run ** P -- the path to the queue ** S -- the queue sorting order ** R -- number of parallel queue runners ** r -- max recipients per envelope ** The first word is the canonical name of the queue. ** qdef -- this is a 'Q' definition from .cf ** ** Returns: ** none. ** ** Side Effects: ** enters the queue into the queue table. */ void makequeue(line, qdef) char *line; bool qdef; { register char *p; register QUEUEGRP *qg; register STAB *s; int i; char fcode; /* allocate a queue and set up defaults */ qg = (QUEUEGRP *) xalloc(sizeof(*qg)); memset((char *) qg, '\0', sizeof(*qg)); if (line[0] == '\0') { syserr("name required for queue"); return; } /* collect the queue name */ for (p = line; *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p)); p++) continue; if (*p != '\0') *p++ = '\0'; qg->qg_name = newstr(line); /* set default values, can be overridden below */ set_def_queueval(qg, false); /* now scan through and assign info from the fields */ while (*p != '\0') { auto char *delimptr; while (*p != '\0' && (*p == ',' || (isascii(*p) && isspace(*p)))) p++; /* p now points to field code */ fcode = *p; while (*p != '\0' && *p != '=' && *p != ',') p++; if (*p++ != '=') { syserr("queue %s: `=' expected", qg->qg_name); return; } while (isascii(*p) && isspace(*p)) p++; /* p now points to the field body */ p = munchstring(p, &delimptr, ','); /* install the field into the queue struct */ switch (fcode) { case 'P': /* pathname */ if (*p == '\0') syserr("queue %s: empty path name", qg->qg_name); else qg->qg_qdir = newstr(p); break; case 'F': /* flags */ for (; *p != '\0'; p++) if (!(isascii(*p) && isspace(*p))) setbitn(*p, qg->qg_flags); break; /* ** Do we need two intervals here: ** One for persistent queue runners, ** one for "normal" queue runs? */ case 'I': /* interval between running the queue */ qg->qg_queueintvl = convtime(p, 'm'); break; case 'N': /* run niceness */ qg->qg_nice = atoi(p); break; case 'R': /* maximum # of runners for the group */ i = atoi(p); /* can't have more runners than allowed total */ if (MaxQueueChildren > 0 && i > MaxQueueChildren) { qg->qg_maxqrun = MaxQueueChildren; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Q=%s: R=%d exceeds MaxQueueChildren=%d, set to MaxQueueChildren\n", qg->qg_name, i, MaxQueueChildren); } else qg->qg_maxqrun = i; break; case 'J': /* maximum # of jobs in work list */ qg->qg_maxlist = atoi(p); break; case 'r': /* max recipients per envelope */ qg->qg_maxrcpt = atoi(p); break; #if _FFR_QUEUE_GROUP_SORTORDER case 'S': /* queue sorting order */ switch (*p) { case 'h': /* Host first */ case 'H': qg->qg_sortorder = QSO_BYHOST; break; case 'p': /* Priority order */ case 'P': qg->qg_sortorder = QSO_BYPRIORITY; break; case 't': /* Submission time */ case 'T': qg->qg_sortorder = QSO_BYTIME; break; case 'f': /* File name */ case 'F': qg->qg_sortorder = QSO_BYFILENAME; break; case 'm': /* Modification time */ case 'M': qg->qg_sortorder = QSO_BYMODTIME; break; case 'r': /* Random */ case 'R': qg->qg_sortorder = QSO_RANDOM; break; # if _FFR_RHS case 's': /* Shuffled host name */ case 'S': qg->qg_sortorder = QSO_BYSHUFFLE; break; # endif /* _FFR_RHS */ case 'n': /* none */ case 'N': qg->qg_sortorder = QSO_NONE; break; default: syserr("Invalid queue sort order \"%s\"", p); } break; #endif /* _FFR_QUEUE_GROUP_SORTORDER */ default: syserr("Q%s: unknown queue equate %c=", qg->qg_name, fcode); break; } p = delimptr; } #if !HASNICE if (qg->qg_nice != NiceQueueRun) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Q%s: Warning: N= set on system that doesn't support nice()\n", qg->qg_name); } #endif /* !HASNICE */ /* do some rationality checking */ if (NumQueue >= MAXQUEUEGROUPS) { syserr("too many queue groups defined (%d max)", MAXQUEUEGROUPS); return; } if (qg->qg_qdir == NULL) { if (QueueDir == NULL || *QueueDir == '\0') { syserr("QueueDir must be defined before queue groups"); return; } qg->qg_qdir = newstr(QueueDir); } if (qg->qg_maxqrun > 1 && !bitnset(QD_FORK, qg->qg_flags)) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Q=%s: R=%d: multiple queue runners specified\n\tbut flag '%c' is not set\n", qg->qg_name, qg->qg_maxqrun, QD_FORK); } /* enter the queue into the symbol table */ if (tTd(37, 8)) sm_syslog(LOG_INFO, NOQID, "Adding %s to stab, path: %s", qg->qg_name, qg->qg_qdir); s = stab(qg->qg_name, ST_QUEUE, ST_ENTER); if (s->s_quegrp != NULL) { i = s->s_quegrp->qg_index; /* XXX what about the pointers inside this struct? */ sm_free(s->s_quegrp); /* XXX */ } else i = NumQueue++; Queue[i] = s->s_quegrp = qg; qg->qg_index = i; /* set default value for max queue runners */ if (qg->qg_maxqrun < 0) { if (MaxRunnersPerQueue > 0) qg->qg_maxqrun = MaxRunnersPerQueue; else qg->qg_maxqrun = 1; } if (qdef) setbitn(QD_DEFINED, qg->qg_flags); } #if 0 /* ** HASHFQN -- calculate a hash value for a fully qualified host name ** ** Arguments: ** fqn -- an all lower-case host.domain string ** buckets -- the number of buckets (queue directories) ** ** Returns: ** a bucket number (signed integer) ** -1 on error ** ** Contributed by Exactis.com, Inc. */ int hashfqn(fqn, buckets) register char *fqn; int buckets; { register char *p; register int h = 0, hash, cnt; if (fqn == NULL) return -1; /* ** A variation on the gdb hash ** This is the best as of Feb 19, 1996 --bcx */ p = fqn; h = 0x238F13AF * strlen(p); for (cnt = 0; *p != 0; ++p, cnt++) { h = (h + (*p << (cnt * 5 % 24))) & 0x7FFFFFFF; } h = (1103515243 * h + 12345) & 0x7FFFFFFF; if (buckets < 2) hash = 0; else hash = (h % buckets); return hash; } #endif /* 0 */ /* ** A structure for sorting Queue according to maxqrun without ** screwing up Queue itself. */ struct sortqgrp { int sg_idx; /* original index */ int sg_maxqrun; /* max queue runners */ }; typedef struct sortqgrp SORTQGRP_T; static int cmpidx __P((const void *, const void *)); static int cmpidx(a, b) const void *a; const void *b; { /* The sort is highest to lowest, so the comparison is reversed */ if (((SORTQGRP_T *)a)->sg_maxqrun < ((SORTQGRP_T *)b)->sg_maxqrun) return 1; else if (((SORTQGRP_T *)a)->sg_maxqrun > ((SORTQGRP_T *)b)->sg_maxqrun) return -1; else return 0; } /* ** MAKEWORKGROUP -- balance queue groups into work groups per MaxQueueChildren ** ** Take the now defined queue groups and assign them to work groups. ** This is done to balance out the number of concurrently active ** queue runners such that MaxQueueChildren is not exceeded. This may ** result in more than one queue group per work group. In such a case ** the number of running queue groups in that work group will have no ** more than the work group maximum number of runners (a "fair" portion ** of MaxQueueRunners). All queue groups within a work group will get a ** chance at running. ** ** Parameters: ** none. ** ** Returns: ** nothing. ** ** Side Effects: ** Sets up WorkGrp structure. */ void makeworkgroups() { int i, j, total_runners, dir, h; SORTQGRP_T si[MAXQUEUEGROUPS + 1]; total_runners = 0; if (NumQueue == 1 && strcmp(Queue[0]->qg_name, "mqueue") == 0) { /* ** There is only the "mqueue" queue group (a default) ** containing all of the queues. We want to provide to ** this queue group the maximum allowable queue runners. ** To match older behavior (8.10/8.11) we'll try for ** 1 runner per queue capping it at MaxQueueChildren. ** So if there are N queues, then there will be N runners ** for the "mqueue" queue group (where N is kept less than ** MaxQueueChildren). */ NumWorkGroups = 1; WorkGrp[0].wg_numqgrp = 1; WorkGrp[0].wg_qgs = (QUEUEGRP **) xalloc(sizeof(QUEUEGRP *)); WorkGrp[0].wg_qgs[0] = Queue[0]; if (MaxQueueChildren > 0 && Queue[0]->qg_numqueues > MaxQueueChildren) WorkGrp[0].wg_runners = MaxQueueChildren; else WorkGrp[0].wg_runners = Queue[0]->qg_numqueues; Queue[0]->qg_wgrp = 0; /* can't have more runners than allowed total */ if (MaxQueueChildren > 0 && Queue[0]->qg_maxqrun > MaxQueueChildren) Queue[0]->qg_maxqrun = MaxQueueChildren; WorkGrp[0].wg_maxact = Queue[0]->qg_maxqrun; WorkGrp[0].wg_lowqintvl = Queue[0]->qg_queueintvl; return; } for (i = 0; i < NumQueue; i++) { si[i].sg_maxqrun = Queue[i]->qg_maxqrun; si[i].sg_idx = i; } qsort(si, NumQueue, sizeof(si[0]), cmpidx); NumWorkGroups = 0; for (i = 0; i < NumQueue; i++) { total_runners += si[i].sg_maxqrun; if (MaxQueueChildren <= 0 || total_runners <= MaxQueueChildren) NumWorkGroups++; else break; } if (NumWorkGroups < 1) NumWorkGroups = 1; /* gotta have one at least */ else if (NumWorkGroups > MAXWORKGROUPS) NumWorkGroups = MAXWORKGROUPS; /* the limit */ /* ** We now know the number of work groups to pack the queue groups ** into. The queue groups in 'Queue' are sorted from highest ** to lowest for the number of runners per queue group. ** We put the queue groups with the largest number of runners ** into work groups first. Then the smaller ones are fitted in ** where it looks best. */ j = 0; dir = 1; for (i = 0; i < NumQueue; i++) { /* a to-and-fro packing scheme, continue from last position */ if (j >= NumWorkGroups) { dir = -1; j = NumWorkGroups - 1; } else if (j < 0) { j = 0; dir = 1; } if (WorkGrp[j].wg_qgs == NULL) WorkGrp[j].wg_qgs = (QUEUEGRP **)sm_malloc(sizeof(QUEUEGRP *) * (WorkGrp[j].wg_numqgrp + 1)); else WorkGrp[j].wg_qgs = (QUEUEGRP **)sm_realloc(WorkGrp[j].wg_qgs, sizeof(QUEUEGRP *) * (WorkGrp[j].wg_numqgrp + 1)); if (WorkGrp[j].wg_qgs == NULL) { syserr("!cannot allocate memory for work queues, need %d bytes", (int) (sizeof(QUEUEGRP *) * (WorkGrp[j].wg_numqgrp + 1))); } h = si[i].sg_idx; WorkGrp[j].wg_qgs[WorkGrp[j].wg_numqgrp] = Queue[h]; WorkGrp[j].wg_numqgrp++; WorkGrp[j].wg_runners += Queue[h]->qg_maxqrun; Queue[h]->qg_wgrp = j; if (WorkGrp[j].wg_maxact == 0) { /* can't have more runners than allowed total */ if (MaxQueueChildren > 0 && Queue[h]->qg_maxqrun > MaxQueueChildren) Queue[h]->qg_maxqrun = MaxQueueChildren; WorkGrp[j].wg_maxact = Queue[h]->qg_maxqrun; } /* ** XXX: must wg_lowqintvl be the GCD? ** qg1: 2m, qg2: 3m, minimum: 2m, when do queue runs for ** qg2 occur? */ /* keep track of the lowest interval for a persistent runner */ if (Queue[h]->qg_queueintvl > 0 && WorkGrp[j].wg_lowqintvl < Queue[h]->qg_queueintvl) WorkGrp[j].wg_lowqintvl = Queue[h]->qg_queueintvl; j += dir; } if (tTd(41, 9)) { for (i = 0; i < NumWorkGroups; i++) { sm_dprintf("Workgroup[%d]=", i); for (j = 0; j < WorkGrp[i].wg_numqgrp; j++) { sm_dprintf("%s, ", WorkGrp[i].wg_qgs[j]->qg_name); } sm_dprintf("\n"); } } } /* ** DUP_DF -- duplicate envelope data file ** ** Copy the data file from the 'old' envelope to the 'new' envelope ** in the most efficient way possible. ** ** Create a hard link from the 'old' data file to the 'new' data file. ** If the old and new queue directories are on different file systems, ** then the new data file link is created in the old queue directory, ** and the new queue file will contain a 'd' record pointing to the ** directory containing the new data file. ** ** Parameters: ** old -- old envelope. ** new -- new envelope. ** ** Results: ** Returns true on success, false on failure. ** ** Side Effects: ** On success, the new data file is created. ** On fatal failure, EF_FATALERRS is set in old->e_flags. */ static bool dup_df __P((ENVELOPE *, ENVELOPE *)); static bool dup_df(old, new) ENVELOPE *old; ENVELOPE *new; { int ofs, nfs, r; char opath[MAXPATHLEN]; char npath[MAXPATHLEN]; if (!bitset(EF_HAS_DF, old->e_flags)) { /* ** this can happen if: SuperSafe != True ** and a bounce mail is sent that is split. */ queueup(old, false, true); } SM_REQUIRE(ISVALIDQGRP(old->e_qgrp) && ISVALIDQDIR(old->e_qdir)); SM_REQUIRE(ISVALIDQGRP(new->e_qgrp) && ISVALIDQDIR(new->e_qdir)); (void) sm_strlcpy(opath, queuename(old, DATAFL_LETTER), sizeof(opath)); (void) sm_strlcpy(npath, queuename(new, DATAFL_LETTER), sizeof(npath)); if (old->e_dfp != NULL) { r = sm_io_setinfo(old->e_dfp, SM_BF_COMMIT, NULL); if (r < 0 && errno != EINVAL) { syserr("@can't commit %s", opath); old->e_flags |= EF_FATALERRS; return false; } } /* ** Attempt to create a hard link, if we think both old and new ** are on the same file system, otherwise copy the file. ** ** Don't waste time attempting a hard link unless old and new ** are on the same file system. */ SM_REQUIRE(ISVALIDQGRP(old->e_dfqgrp) && ISVALIDQDIR(old->e_dfqdir)); SM_REQUIRE(ISVALIDQGRP(new->e_dfqgrp) && ISVALIDQDIR(new->e_dfqdir)); ofs = Queue[old->e_dfqgrp]->qg_qpaths[old->e_dfqdir].qp_fsysidx; nfs = Queue[new->e_dfqgrp]->qg_qpaths[new->e_dfqdir].qp_fsysidx; if (FILE_SYS_DEV(ofs) == FILE_SYS_DEV(nfs)) { if (link(opath, npath) == 0) { new->e_flags |= EF_HAS_DF; SYNC_DIR(npath, true); return true; } goto error; } /* ** Can't link across queue directories, so try to create a hard ** link in the same queue directory as the old df file. ** The qf file will refer to the new df file using a 'd' record. */ new->e_dfqgrp = old->e_dfqgrp; new->e_dfqdir = old->e_dfqdir; (void) sm_strlcpy(npath, queuename(new, DATAFL_LETTER), sizeof(npath)); if (link(opath, npath) == 0) { new->e_flags |= EF_HAS_DF; SYNC_DIR(npath, true); return true; } error: if (LogLevel > 0) sm_syslog(LOG_ERR, old->e_id, "dup_df: can't link %s to %s, error=%s, envelope splitting failed", opath, npath, sm_errstring(errno)); return false; } /* ** SPLIT_ENV -- Allocate a new envelope based on a given envelope. ** ** Parameters: ** e -- envelope. ** sendqueue -- sendqueue for new envelope. ** qgrp -- index of queue group. ** qdir -- queue directory. ** ** Results: ** new envelope. ** */ static ENVELOPE *split_env __P((ENVELOPE *, ADDRESS *, int, int)); static ENVELOPE * split_env(e, sendqueue, qgrp, qdir) ENVELOPE *e; ADDRESS *sendqueue; int qgrp; int qdir; { ENVELOPE *ee; ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool, sizeof(*ee)); STRUCTCOPY(*e, *ee); ee->e_message = NULL; /* XXX use original message? */ ee->e_id = NULL; assign_queueid(ee); ee->e_sendqueue = sendqueue; ee->e_flags &= ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS |EF_SENDRECEIPT|EF_RET_PARAM|EF_HAS_DF); ee->e_flags |= EF_NORECEIPT; /* XXX really? */ ee->e_from.q_state = QS_SENDER; ee->e_dfp = NULL; ee->e_lockfp = NULL; if (e->e_xfp != NULL) ee->e_xfp = sm_io_dup(e->e_xfp); /* failed to dup e->e_xfp, start a new transcript */ if (ee->e_xfp == NULL) openxscript(ee); ee->e_qgrp = ee->e_dfqgrp = qgrp; ee->e_qdir = ee->e_dfqdir = qdir; ee->e_errormode = EM_MAIL; ee->e_statmsg = NULL; if (e->e_quarmsg != NULL) ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool, e->e_quarmsg); /* ** XXX Not sure if this copying is necessary. ** sendall() does this copying, but I (dm) don't know if that is ** because of the storage management discipline we were using ** before rpools were introduced, or if it is because these lists ** can be modified later. */ ee->e_header = copyheader(e->e_header, ee->e_rpool); ee->e_errorqueue = copyqueue(e->e_errorqueue, ee->e_rpool); return ee; } /* return values from split functions, check also below! */ #define SM_SPLIT_FAIL (0) #define SM_SPLIT_NONE (1) #define SM_SPLIT_NEW(n) (1 + (n)) /* ** SPLIT_ACROSS_QUEUE_GROUPS ** ** This function splits an envelope across multiple queue groups ** based on the queue group of each recipient. ** ** Parameters: ** e -- envelope. ** ** Results: ** SM_SPLIT_FAIL on failure ** SM_SPLIT_NONE if no splitting occurred, ** or 1 + the number of additional envelopes created. ** ** Side Effects: ** On success, e->e_sibling points to a list of zero or more ** additional envelopes, and the associated data files exist ** on disk. But the queue files are not created. ** ** On failure, e->e_sibling is not changed. ** The order of recipients in e->e_sendqueue is permuted. ** Abandoned data files for additional envelopes that failed ** to be created may exist on disk. */ static int q_qgrp_compare __P((const void *, const void *)); static int e_filesys_compare __P((const void *, const void *)); static int q_qgrp_compare(p1, p2) const void *p1; const void *p2; { ADDRESS **pq1 = (ADDRESS **) p1; ADDRESS **pq2 = (ADDRESS **) p2; return (*pq1)->q_qgrp - (*pq2)->q_qgrp; } static int e_filesys_compare(p1, p2) const void *p1; const void *p2; { ENVELOPE **pe1 = (ENVELOPE **) p1; ENVELOPE **pe2 = (ENVELOPE **) p2; int fs1, fs2; fs1 = Queue[(*pe1)->e_qgrp]->qg_qpaths[(*pe1)->e_qdir].qp_fsysidx; fs2 = Queue[(*pe2)->e_qgrp]->qg_qpaths[(*pe2)->e_qdir].qp_fsysidx; if (FILE_SYS_DEV(fs1) < FILE_SYS_DEV(fs2)) return -1; if (FILE_SYS_DEV(fs1) > FILE_SYS_DEV(fs2)) return 1; return 0; } static int split_across_queue_groups __P((ENVELOPE *)); static int split_across_queue_groups(e) ENVELOPE *e; { int naddrs, nsplits, i; bool changed; char **pvp; ADDRESS *q, **addrs; ENVELOPE *ee, *es; ENVELOPE *splits[MAXQUEUEGROUPS]; char pvpbuf[PSBUFSIZE]; SM_REQUIRE(ISVALIDQGRP(e->e_qgrp)); /* Count addresses and assign queue groups. */ naddrs = 0; changed = false; for (q = e->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_DEAD(q->q_state)) continue; ++naddrs; /* bad addresses and those already sent stay put */ if (QS_IS_BADADDR(q->q_state) || QS_IS_SENT(q->q_state)) q->q_qgrp = e->e_qgrp; else if (!ISVALIDQGRP(q->q_qgrp)) { /* call ruleset which should return a queue group */ i = rscap(RS_QUEUEGROUP, q->q_user, NULL, e, &pvp, pvpbuf, sizeof(pvpbuf)); if (i == EX_OK && pvp != NULL && pvp[0] != NULL && (pvp[0][0] & 0377) == CANONNET && pvp[1] != NULL && pvp[1][0] != '\0') { i = name2qid(pvp[1]); if (ISVALIDQGRP(i)) { q->q_qgrp = i; changed = true; if (tTd(20, 4)) sm_syslog(LOG_INFO, NOQID, "queue group name %s -> %d", pvp[1], i); continue; } else if (LogLevel > 10) sm_syslog(LOG_INFO, NOQID, "can't find queue group name %s, selection ignored", pvp[1]); } if (q->q_mailer != NULL && ISVALIDQGRP(q->q_mailer->m_qgrp)) { changed = true; q->q_qgrp = q->q_mailer->m_qgrp; } else if (ISVALIDQGRP(e->e_qgrp)) q->q_qgrp = e->e_qgrp; else q->q_qgrp = 0; } } /* only one address? nothing to split. */ if (naddrs <= 1 && !changed) return SM_SPLIT_NONE; /* sort the addresses by queue group */ addrs = sm_rpool_malloc_x(e->e_rpool, naddrs * sizeof(ADDRESS *)); for (i = 0, q = e->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_DEAD(q->q_state)) continue; addrs[i++] = q; } qsort(addrs, naddrs, sizeof(ADDRESS *), q_qgrp_compare); /* split into multiple envelopes, by queue group */ nsplits = 0; es = NULL; e->e_sendqueue = NULL; for (i = 0; i < naddrs; ++i) { if (i == naddrs - 1 || addrs[i]->q_qgrp != addrs[i + 1]->q_qgrp) addrs[i]->q_next = NULL; else addrs[i]->q_next = addrs[i + 1]; /* same queue group as original envelope? */ if (addrs[i]->q_qgrp == e->e_qgrp) { if (e->e_sendqueue == NULL) e->e_sendqueue = addrs[i]; continue; } /* different queue group than original envelope */ if (es == NULL || addrs[i]->q_qgrp != es->e_qgrp) { ee = split_env(e, addrs[i], addrs[i]->q_qgrp, NOQDIR); es = ee; splits[nsplits++] = ee; } } /* no splits? return right now. */ if (nsplits <= 0) return SM_SPLIT_NONE; /* assign a queue directory to each additional envelope */ for (i = 0; i < nsplits; ++i) { es = splits[i]; #if 0 es->e_qdir = pickqdir(Queue[es->e_qgrp], es->e_msgsize, es); #endif /* 0 */ if (!setnewqueue(es)) goto failure; } /* sort the additional envelopes by queue file system */ qsort(splits, nsplits, sizeof(ENVELOPE *), e_filesys_compare); /* create data files for each additional envelope */ if (!dup_df(e, splits[0])) { i = 0; goto failure; } for (i = 1; i < nsplits; ++i) { /* copy or link to the previous data file */ if (!dup_df(splits[i - 1], splits[i])) goto failure; } /* success: prepend the new envelopes to the e->e_sibling list */ for (i = 0; i < nsplits; ++i) { es = splits[i]; es->e_sibling = e->e_sibling; e->e_sibling = es; } return SM_SPLIT_NEW(nsplits); /* failure: clean up */ failure: if (i > 0) { int j; for (j = 0; j < i; j++) (void) unlink(queuename(splits[j], DATAFL_LETTER)); } e->e_sendqueue = addrs[0]; for (i = 0; i < naddrs - 1; ++i) addrs[i]->q_next = addrs[i + 1]; addrs[naddrs - 1]->q_next = NULL; return SM_SPLIT_FAIL; } /* ** SPLIT_WITHIN_QUEUE ** ** Split an envelope with multiple recipients into several ** envelopes within the same queue directory, if the number of ** recipients exceeds the limit for the queue group. ** ** Parameters: ** e -- envelope. ** ** Results: ** SM_SPLIT_FAIL on failure ** SM_SPLIT_NONE if no splitting occurred, ** or 1 + the number of additional envelopes created. */ #define SPLIT_LOG_LEVEL 8 static int split_within_queue __P((ENVELOPE *)); static int split_within_queue(e) ENVELOPE *e; { int maxrcpt, nrcpt, ndead, nsplit, i; int j, l; char *lsplits; ADDRESS *q, **addrs; ENVELOPE *ee, *firstsibling; if (!ISVALIDQGRP(e->e_qgrp) || bitset(EF_SPLIT, e->e_flags)) return SM_SPLIT_NONE; /* don't bother if there is no recipient limit */ maxrcpt = Queue[e->e_qgrp]->qg_maxrcpt; if (maxrcpt <= 0) return SM_SPLIT_NONE; /* count recipients */ nrcpt = 0; for (q = e->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_DEAD(q->q_state)) continue; ++nrcpt; } if (nrcpt <= maxrcpt) return SM_SPLIT_NONE; /* ** Preserve the recipient list ** so that we can restore it in case of error. ** (But we discard dead addresses.) */ addrs = sm_rpool_malloc_x(e->e_rpool, nrcpt * sizeof(ADDRESS *)); for (i = 0, q = e->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_DEAD(q->q_state)) continue; addrs[i++] = q; } /* ** Partition the recipient list so that bad and sent addresses ** come first. These will go with the original envelope, and ** do not count towards the maxrcpt limit. ** addrs[] does not contain QS_IS_DEAD() addresses. */ ndead = 0; for (i = 0; i < nrcpt; ++i) { if (QS_IS_BADADDR(addrs[i]->q_state) || QS_IS_SENT(addrs[i]->q_state) || QS_IS_DEAD(addrs[i]->q_state)) /* for paranoia's sake */ { if (i > ndead) { ADDRESS *tmp = addrs[i]; addrs[i] = addrs[ndead]; addrs[ndead] = tmp; } ++ndead; } } /* Check if no splitting required. */ if (nrcpt - ndead <= maxrcpt) return SM_SPLIT_NONE; /* fix links */ for (i = 0; i < nrcpt - 1; ++i) addrs[i]->q_next = addrs[i + 1]; addrs[nrcpt - 1]->q_next = NULL; e->e_sendqueue = addrs[0]; /* prepare buffer for logging */ if (LogLevel > SPLIT_LOG_LEVEL) { l = MAXLINE; lsplits = sm_malloc(l); if (lsplits != NULL) *lsplits = '\0'; j = 0; } else { /* get rid of stupid compiler warnings */ lsplits = NULL; j = l = 0; } /* split the envelope */ firstsibling = e->e_sibling; i = maxrcpt + ndead; nsplit = 0; for (;;) { addrs[i - 1]->q_next = NULL; ee = split_env(e, addrs[i], e->e_qgrp, e->e_qdir); if (!dup_df(e, ee)) { ee = firstsibling; while (ee != NULL) { (void) unlink(queuename(ee, DATAFL_LETTER)); ee = ee->e_sibling; } /* Error. Restore e's sibling & recipient lists. */ e->e_sibling = firstsibling; for (i = 0; i < nrcpt - 1; ++i) addrs[i]->q_next = addrs[i + 1]; if (lsplits != NULL) sm_free(lsplits); return SM_SPLIT_FAIL; } /* prepend the new envelope to e->e_sibling */ ee->e_sibling = e->e_sibling; e->e_sibling = ee; ++nsplit; if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL) { if (j >= l - strlen(ee->e_id) - 3) { char *p; l += MAXLINE; p = sm_realloc(lsplits, l); if (p == NULL) { /* let's try to get this done */ sm_free(lsplits); lsplits = NULL; } else lsplits = p; } if (lsplits != NULL) { if (j == 0) j += sm_strlcat(lsplits + j, ee->e_id, l - j); else j += sm_strlcat2(lsplits + j, "; ", ee->e_id, l - j); SM_ASSERT(j < l); } } if (nrcpt - i <= maxrcpt) break; i += maxrcpt; } if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL) { if (nsplit > 0) { sm_syslog(LOG_NOTICE, e->e_id, "split: maxrcpts=%d, rcpts=%d, count=%d, id%s=%s", maxrcpt, nrcpt - ndead, nsplit, nsplit > 1 ? "s" : "", lsplits); } sm_free(lsplits); } return SM_SPLIT_NEW(nsplit); } /* ** SPLIT_BY_RECIPIENT ** ** Split an envelope with multiple recipients into multiple ** envelopes as required by the sendmail configuration. ** ** Parameters: ** e -- envelope. ** ** Results: ** Returns true on success, false on failure. ** ** Side Effects: ** see split_across_queue_groups(), split_within_queue(e) */ bool split_by_recipient(e) ENVELOPE *e; { int split, n, i, j, l; char *lsplits; ENVELOPE *ee, *next, *firstsibling; if (OpMode == SM_VERIFY || !ISVALIDQGRP(e->e_qgrp) || bitset(EF_SPLIT, e->e_flags)) return true; n = split_across_queue_groups(e); if (n == SM_SPLIT_FAIL) return false; firstsibling = ee = e->e_sibling; if (n > 1 && LogLevel > SPLIT_LOG_LEVEL) { l = MAXLINE; lsplits = sm_malloc(l); if (lsplits != NULL) *lsplits = '\0'; j = 0; } else { /* get rid of stupid compiler warnings */ lsplits = NULL; j = l = 0; } for (i = 1; i < n; ++i) { next = ee->e_sibling; if (split_within_queue(ee) == SM_SPLIT_FAIL) { e->e_sibling = firstsibling; return false; } ee->e_flags |= EF_SPLIT; if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL) { if (j >= l - strlen(ee->e_id) - 3) { char *p; l += MAXLINE; p = sm_realloc(lsplits, l); if (p == NULL) { /* let's try to get this done */ sm_free(lsplits); lsplits = NULL; } else lsplits = p; } if (lsplits != NULL) { if (j == 0) j += sm_strlcat(lsplits + j, ee->e_id, l - j); else j += sm_strlcat2(lsplits + j, "; ", ee->e_id, l - j); SM_ASSERT(j < l); } } ee = next; } if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL && n > 1) { sm_syslog(LOG_NOTICE, e->e_id, "split: count=%d, id%s=%s", n - 1, n > 2 ? "s" : "", lsplits); sm_free(lsplits); } split = split_within_queue(e) != SM_SPLIT_FAIL; if (split) e->e_flags |= EF_SPLIT; return split; } /* ** QUARANTINE_QUEUE_ITEM -- {un,}quarantine a single envelope ** ** Add/remove quarantine reason and requeue appropriately. ** ** Parameters: ** qgrp -- queue group for the item ** qdir -- queue directory in the given queue group ** e -- envelope information for the item ** reason -- quarantine reason, NULL means unquarantine. ** ** Results: ** true if item changed, false otherwise ** ** Side Effects: ** Changes quarantine tag in queue file and renames it. */ static bool quarantine_queue_item(qgrp, qdir, e, reason) int qgrp; int qdir; ENVELOPE *e; char *reason; { bool dirty = false; bool failing = false; bool foundq = false; bool finished = false; int fd; int flags; int oldtype; int newtype; int save_errno; MODE_T oldumask = 0; SM_FILE_T *oldqfp, *tempqfp; char *bp; int bufsize; char oldqf[MAXPATHLEN]; char tempqf[MAXPATHLEN]; char newqf[MAXPATHLEN]; char buf[MAXLINE]; oldtype = queue_letter(e, ANYQFL_LETTER); (void) sm_strlcpy(oldqf, queuename(e, ANYQFL_LETTER), sizeof(oldqf)); (void) sm_strlcpy(tempqf, queuename(e, NEWQFL_LETTER), sizeof(tempqf)); /* ** Instead of duplicating all the open ** and lock code here, tell readqf() to ** do that work and return the open ** file pointer in e_lockfp. Note that ** we must release the locks properly when ** we are done. */ if (!readqf(e, true)) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Skipping %s\n", qid_printname(e)); return false; } oldqfp = e->e_lockfp; /* open the new queue file */ flags = O_CREAT|O_WRONLY|O_EXCL; if (bitset(S_IWGRP, QueueFileMode)) oldumask = umask(002); fd = open(tempqf, flags, QueueFileMode); if (bitset(S_IWGRP, QueueFileMode)) (void) umask(oldumask); RELEASE_QUEUE; if (fd < 0) { save_errno = errno; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Skipping %s: Could not open %s: %s\n", qid_printname(e), tempqf, sm_errstring(save_errno)); (void) sm_io_close(oldqfp, SM_TIME_DEFAULT); return false; } if (!lockfile(fd, tempqf, NULL, LOCK_EX|LOCK_NB)) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Skipping %s: Could not lock %s\n", qid_printname(e), tempqf); (void) close(fd); (void) sm_io_close(oldqfp, SM_TIME_DEFAULT); return false; } tempqfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &fd, SM_IO_WRONLY_B, NULL); if (tempqfp == NULL) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Skipping %s: Could not lock %s\n", qid_printname(e), tempqf); (void) close(fd); (void) sm_io_close(oldqfp, SM_TIME_DEFAULT); return false; } /* Copy the data over, changing the quarantine reason */ while (bufsize = sizeof(buf), (bp = fgetfolded(buf, &bufsize, oldqfp)) != NULL) { if (tTd(40, 4)) sm_dprintf("+++++ %s\n", bp); switch (bp[0]) { case 'q': /* quarantine reason */ foundq = true; if (reason == NULL) { if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: Removed quarantine of \"%s\"\n", e->e_id, &bp[1]); } sm_syslog(LOG_INFO, e->e_id, "unquarantine"); dirty = true; } else if (strcmp(reason, &bp[1]) == 0) { if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: Already quarantined with \"%s\"\n", e->e_id, reason); } (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, "q%s\n", reason); } else { if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: Quarantine changed from \"%s\" to \"%s\"\n", e->e_id, &bp[1], reason); } (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, "q%s\n", reason); sm_syslog(LOG_INFO, e->e_id, "quarantine=%s", reason); dirty = true; } break; case 'S': /* ** If we are quarantining an unquarantined item, ** need to put in a new 'q' line before it's ** too late. */ if (!foundq && reason != NULL) { if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: Quarantined with \"%s\"\n", e->e_id, reason); } (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, "q%s\n", reason); sm_syslog(LOG_INFO, e->e_id, "quarantine=%s", reason); foundq = true; dirty = true; } /* Copy the line to the new file */ (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, "%s\n", bp); break; case '.': finished = true; /* FALLTHROUGH */ default: /* Copy the line to the new file */ (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, "%s\n", bp); break; } if (bp != buf) sm_free(bp); } /* Make sure we read the whole old file */ errno = sm_io_error(tempqfp); if (errno != 0 && errno != SM_IO_EOF) { save_errno = errno; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Skipping %s: Error reading %s: %s\n", qid_printname(e), oldqf, sm_errstring(save_errno)); failing = true; } if (!failing && !finished) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Skipping %s: Incomplete file: %s\n", qid_printname(e), oldqf); failing = true; } /* Check if we actually changed anything or we can just bail now */ if (!dirty) { /* pretend we failed, even though we technically didn't */ failing = true; } /* Make sure we wrote things out safely */ if (!failing && (sm_io_flush(tempqfp, SM_TIME_DEFAULT) != 0 || ((SuperSafe == SAFE_REALLY || SuperSafe == SAFE_REALLY_POSTMILTER || SuperSafe == SAFE_INTERACTIVE) && fsync(sm_io_getinfo(tempqfp, SM_IO_WHAT_FD, NULL)) < 0) || ((errno = sm_io_error(tempqfp)) != 0))) { save_errno = errno; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Skipping %s: Error writing %s: %s\n", qid_printname(e), tempqf, sm_errstring(save_errno)); failing = true; } /* Figure out the new filename */ newtype = (reason == NULL ? NORMQF_LETTER : QUARQF_LETTER); if (oldtype == newtype) { /* going to rename tempqf to oldqf */ (void) sm_strlcpy(newqf, oldqf, sizeof(newqf)); } else { /* going to rename tempqf to new name based on newtype */ (void) sm_strlcpy(newqf, queuename(e, newtype), sizeof(newqf)); } save_errno = 0; /* rename tempqf to newqf */ if (!failing && rename(tempqf, newqf) < 0) save_errno = (errno == 0) ? EINVAL : errno; /* Check rename() success */ if (!failing && save_errno != 0) { sm_syslog(LOG_DEBUG, e->e_id, "quarantine_queue_item: rename(%s, %s): %s", tempqf, newqf, sm_errstring(save_errno)); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Error renaming %s to %s: %s\n", tempqf, newqf, sm_errstring(save_errno)); if (oldtype == newtype) { /* ** Bail here since we don't know the state of ** the filesystem and may need to keep tempqf ** for the user to rescue us. */ RELEASE_QUEUE; errno = save_errno; syserr("!452 Error renaming control file %s", tempqf); /* NOTREACHED */ } else { /* remove new file (if rename() half completed) */ if (xunlink(newqf) < 0) { save_errno = errno; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Error removing %s: %s\n", newqf, sm_errstring(save_errno)); } /* tempqf removed below */ failing = true; } } /* If changing file types, need to remove old type */ if (!failing && oldtype != newtype) { if (xunlink(oldqf) < 0) { save_errno = errno; (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Error removing %s: %s\n", oldqf, sm_errstring(save_errno)); } } /* see if anything above failed */ if (failing) { /* Something failed: remove new file, old file still there */ (void) xunlink(tempqf); } /* ** fsync() after file operations to make sure metadata is ** written to disk on filesystems in which renames are ** not guaranteed. It's ok if they fail, mail won't be lost. */ if (SuperSafe != SAFE_NO) { /* for soft-updates */ (void) fsync(sm_io_getinfo(tempqfp, SM_IO_WHAT_FD, NULL)); if (!failing) { /* for soft-updates */ (void) fsync(sm_io_getinfo(oldqfp, SM_IO_WHAT_FD, NULL)); } /* for other odd filesystems */ SYNC_DIR(tempqf, false); } /* Close up shop */ RELEASE_QUEUE; if (tempqfp != NULL) (void) sm_io_close(tempqfp, SM_TIME_DEFAULT); if (oldqfp != NULL) (void) sm_io_close(oldqfp, SM_TIME_DEFAULT); /* All went well */ return !failing; } /* ** QUARANTINE_QUEUE -- {un,}quarantine matching items in the queue ** ** Read all matching queue items, add/remove quarantine ** reason, and requeue appropriately. ** ** Parameters: ** reason -- quarantine reason, "." means unquarantine. ** qgrplimit -- limit to single queue group unless NOQGRP ** ** Results: ** none. ** ** Side Effects: ** Lots of changes to the queue. */ void quarantine_queue(reason, qgrplimit) char *reason; int qgrplimit; { int changed = 0; int qgrp; /* Convert internal representation of unquarantine */ if (reason != NULL && reason[0] == '.' && reason[1] == '\0') reason = NULL; if (reason != NULL) { /* clean it */ reason = newstr(denlstring(reason, true, true)); } for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; qgrp++) { int qdir; if (qgrplimit != NOQGRP && qgrplimit != qgrp) continue; for (qdir = 0; qdir < Queue[qgrp]->qg_numqueues; qdir++) { int i; int nrequests; if (StopRequest) stop_sendmail(); nrequests = gatherq(qgrp, qdir, true, NULL, NULL, NULL); /* first see if there is anything */ if (nrequests <= 0) { if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s: no matches\n", qid_printqueue(qgrp, qdir)); } continue; } if (Verbose) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Processing %s:\n", qid_printqueue(qgrp, qdir)); } for (i = 0; i < WorkListCount; i++) { ENVELOPE e; if (StopRequest) stop_sendmail(); /* setup envelope */ clearenvelope(&e, true, sm_rpool_new_x(NULL)); e.e_id = WorkList[i].w_name + 2; e.e_qgrp = qgrp; e.e_qdir = qdir; if (tTd(70, 101)) { sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Would do %s\n", e.e_id); changed++; } else if (quarantine_queue_item(qgrp, qdir, &e, reason)) changed++; /* clean up */ sm_rpool_free(e.e_rpool); e.e_rpool = NULL; } if (WorkList != NULL) sm_free(WorkList); /* XXX */ WorkList = NULL; WorkListSize = 0; WorkListCount = 0; } } if (Verbose) { if (changed == 0) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "No changes\n"); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%d change%s\n", changed, changed == 1 ? "" : "s"); } } Index: head/contrib/sendmail/src/readcf.c =================================================================== --- head/contrib/sendmail/src/readcf.c (revision 249728) +++ head/contrib/sendmail/src/readcf.c (revision 249729) @@ -1,4762 +1,4781 @@ /* - * Copyright (c) 1998-2006, 2008-2010 Sendmail, Inc. and its suppliers. + * Copyright (c) 1998-2006, 2008-2010, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include #include -SM_RCSID("@(#)$Id: readcf.c,v 8.684 2011/03/15 17:29:29 guenther Exp $") +SM_RCSID("@(#)$Id: readcf.c,v 8.690 2013/03/15 17:54:12 ca Exp $") #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ #define SECONDS #define MINUTES * 60 #define HOUR * 3600 #define HOURS HOUR static void fileclass __P((int, char *, char *, bool, bool, bool)); static char **makeargv __P((char *)); static void settimeout __P((char *, char *, bool)); static void toomany __P((int, int)); static char *extrquotstr __P((char *, char **, char *, bool *)); static void parse_class_words __P((int, char *)); /* ** READCF -- read configuration file. ** ** This routine reads the configuration file and builds the internal ** form. ** ** The file is formatted as a sequence of lines, each taken ** atomically. The first character of each line describes how ** the line is to be interpreted. The lines are: ** Dxval Define macro x to have value val. ** Cxword Put word into class x. ** Fxfile [fmt] Read file for lines to put into ** class x. Use scanf string 'fmt' ** or "%s" if not present. Fmt should ** only produce one string-valued result. ** Hname: value Define header with field-name 'name' ** and value as specified; this will be ** macro expanded immediately before ** use. ** Sn Use rewriting set n. ** Rlhs rhs Rewrite addresses that match lhs to ** be rhs. ** Mn arg=val... Define mailer. n is the internal name. ** Args specify mailer parameters. ** Oxvalue Set option x to value. ** O option value Set option (long name) to value. ** Pname=value Set precedence name to value. ** Qn arg=val... Define queue groups. n is the internal name. ** Args specify queue parameters. ** Vversioncode[/vendorcode] ** Version level/vendor name of ** configuration syntax. ** Kmapname mapclass arguments.... ** Define keyed lookup of a given class. ** Arguments are class dependent. ** Eenvar=value Set the environment value to the given value. ** ** Parameters: ** cfname -- configuration file name. ** safe -- true if this is the system config file; ** false otherwise. ** e -- the main envelope. ** ** Returns: ** none. ** ** Side Effects: ** Builds several internal tables. */ void readcf(cfname, safe, e) char *cfname; bool safe; register ENVELOPE *e; { SM_FILE_T *cf; int ruleset = -1; char *q; struct rewrite *rwp = NULL; char *bp; auto char *ep; int nfuzzy; char *file; bool optional; bool ok; bool ismap; int mid; register char *p; long sff = SFF_OPENASROOT; struct stat statb; char buf[MAXLINE]; int bufsize; char exbuf[MAXLINE]; char pvpbuf[MAXLINE + MAXATOM]; static char *null_list[1] = { NULL }; extern unsigned char TokTypeNoC[]; FileName = cfname; LineNumber = 0; #if STARTTLS Srv_SSL_Options = SSL_OP_ALL; Clt_SSL_Options = SSL_OP_ALL #ifdef SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv2 #endif #ifdef SSL_OP_NO_TICKET | SSL_OP_NO_TICKET #endif ; #endif /* STARTTLS */ if (DontLockReadFiles) sff |= SFF_NOLOCK; cf = safefopen(cfname, O_RDONLY, 0444, sff); if (cf == NULL) { syserr("cannot open"); finis(false, true, EX_OSFILE); } if (fstat(sm_io_getinfo(cf, SM_IO_WHAT_FD, NULL), &statb) < 0) { syserr("cannot fstat"); finis(false, true, EX_OSFILE); } if (!S_ISREG(statb.st_mode)) { syserr("not a plain file"); finis(false, true, EX_OSFILE); } if (OpMode != MD_TEST && bitset(S_IWGRP|S_IWOTH, statb.st_mode)) { if (OpMode == MD_DAEMON || OpMode == MD_INITALIAS || OpMode == MD_CHECKCONFIG) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: WARNING: dangerous write permissions\n", FileName); if (LogLevel > 0) sm_syslog(LOG_CRIT, NOQID, "%s: WARNING: dangerous write permissions", FileName); } #if XLA xla_zero(); #endif /* XLA */ while (bufsize = sizeof(buf), (bp = fgetfolded(buf, &bufsize, cf)) != NULL) { char *nbp; if (bp[0] == '#') { if (bp != buf) sm_free(bp); /* XXX */ continue; } /* do macro expansion mappings */ nbp = translate_dollars(bp, bp, &bufsize); if (nbp != bp && bp != buf) sm_free(bp); bp = nbp; /* interpret this line */ errno = 0; switch (bp[0]) { case '\0': case '#': /* comment */ break; case 'R': /* rewriting rule */ if (ruleset < 0) { syserr("missing valid ruleset for \"%s\"", bp); break; } for (p = &bp[1]; *p != '\0' && *p != '\t'; p++) continue; if (*p == '\0') { syserr("invalid rewrite line \"%s\" (tab expected)", bp); break; } /* allocate space for the rule header */ if (rwp == NULL) { RewriteRules[ruleset] = rwp = (struct rewrite *) xalloc(sizeof(*rwp)); } else { rwp->r_next = (struct rewrite *) xalloc(sizeof(*rwp)); rwp = rwp->r_next; } rwp->r_next = NULL; /* expand and save the LHS */ *p = '\0'; expand(&bp[1], exbuf, sizeof(exbuf), e); rwp->r_lhs = prescan(exbuf, '\t', pvpbuf, sizeof(pvpbuf), NULL, ConfigLevel >= 9 ? TokTypeNoC : IntTokenTab, true); nfuzzy = 0; if (rwp->r_lhs != NULL) { register char **ap; rwp->r_lhs = copyplist(rwp->r_lhs, true, NULL); /* count the number of fuzzy matches in LHS */ for (ap = rwp->r_lhs; *ap != NULL; ap++) { char *botch; botch = NULL; switch (ap[0][0] & 0377) { case MATCHZANY: case MATCHANY: case MATCHONE: case MATCHCLASS: case MATCHNCLASS: nfuzzy++; break; case MATCHREPL: botch = "$1-$9"; break; case CANONUSER: botch = "$:"; break; case CALLSUBR: botch = "$>"; break; case CONDIF: botch = "$?"; break; case CONDFI: botch = "$."; break; case HOSTBEGIN: botch = "$["; break; case HOSTEND: botch = "$]"; break; case LOOKUPBEGIN: botch = "$("; break; case LOOKUPEND: botch = "$)"; break; } if (botch != NULL) syserr("Inappropriate use of %s on LHS", botch); } rwp->r_line = LineNumber; } else { syserr("R line: null LHS"); rwp->r_lhs = null_list; } if (nfuzzy > MAXMATCH) { syserr("R line: too many wildcards"); rwp->r_lhs = null_list; } /* expand and save the RHS */ while (*++p == '\t') continue; q = p; while (*p != '\0' && *p != '\t') p++; *p = '\0'; expand(q, exbuf, sizeof(exbuf), e); rwp->r_rhs = prescan(exbuf, '\t', pvpbuf, sizeof(pvpbuf), NULL, ConfigLevel >= 9 ? TokTypeNoC : IntTokenTab, true); if (rwp->r_rhs != NULL) { register char **ap; int args, endtoken; #if _FFR_EXTRA_MAP_CHECK int nexttoken; #endif /* _FFR_EXTRA_MAP_CHECK */ bool inmap; rwp->r_rhs = copyplist(rwp->r_rhs, true, NULL); /* check no out-of-bounds replacements */ nfuzzy += '0'; inmap = false; args = 0; endtoken = 0; for (ap = rwp->r_rhs; *ap != NULL; ap++) { char *botch; botch = NULL; switch (ap[0][0] & 0377) { case MATCHREPL: if (ap[0][1] <= '0' || ap[0][1] > nfuzzy) { syserr("replacement $%c out of bounds", ap[0][1]); } break; case MATCHZANY: botch = "$*"; break; case MATCHANY: botch = "$+"; break; case MATCHONE: botch = "$-"; break; case MATCHCLASS: botch = "$="; break; case MATCHNCLASS: botch = "$~"; break; case CANONHOST: if (!inmap) break; if (++args >= MAX_MAP_ARGS) syserr("too many arguments for map lookup"); break; case HOSTBEGIN: endtoken = HOSTEND; /* FALLTHROUGH */ case LOOKUPBEGIN: /* see above... */ if ((ap[0][0] & 0377) == LOOKUPBEGIN) endtoken = LOOKUPEND; if (inmap) syserr("cannot nest map lookups"); inmap = true; args = 0; #if _FFR_EXTRA_MAP_CHECK if (ap[1] == NULL) { syserr("syntax error in map lookup"); break; } nexttoken = ap[1][0] & 0377; if (nexttoken == CANONHOST || nexttoken == CANONUSER || nexttoken == endtoken)) { syserr("missing map name for lookup"); break; } if (ap[2] == NULL) { syserr("syntax error in map lookup"); break; } if (ap[0][0] == HOSTBEGIN) break; nexttoken = ap[2][0] & 0377; if (nexttoken == CANONHOST || nexttoken == CANONUSER || nexttoken == endtoken) { syserr("missing key name for lookup"); break; } #endif /* _FFR_EXTRA_MAP_CHECK */ break; case HOSTEND: case LOOKUPEND: if ((ap[0][0] & 0377) != endtoken) break; inmap = false; endtoken = 0; break; #if 0 /* ** This doesn't work yet as there are maps defined *after* the cf ** is read such as host, user, and alias. So for now, it's removed. ** When it comes back, the RELEASE_NOTES entry will be: ** Emit warnings for unknown maps when reading the .cf file. Based on ** patch from Robert Harker of Harker Systems. */ case LOOKUPBEGIN: /* ** Got a database lookup, ** check if map is defined. */ ep = ap[1]; if ((ep[0] & 0377) != MACRODEXPAND && stab(ep, ST_MAP, ST_FIND) == NULL) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: %s: line %d: map %s not found\n", FileName, LineNumber, ep); } break; #endif /* 0 */ } if (botch != NULL) syserr("Inappropriate use of %s on RHS", botch); } if (inmap) syserr("missing map closing token"); } else { syserr("R line: null RHS"); rwp->r_rhs = null_list; } break; case 'S': /* select rewriting set */ expand(&bp[1], exbuf, sizeof(exbuf), e); ruleset = strtorwset(exbuf, NULL, ST_ENTER); if (ruleset < 0) break; rwp = RewriteRules[ruleset]; if (rwp != NULL) { if (OpMode == MD_TEST || OpMode == MD_CHECKCONFIG) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: Ruleset %s has multiple definitions\n", &bp[1]); if (tTd(37, 1)) sm_dprintf("WARNING: Ruleset %s has multiple definitions\n", &bp[1]); while (rwp->r_next != NULL) rwp = rwp->r_next; } break; case 'D': /* macro definition */ mid = macid_parse(&bp[1], &ep); if (mid == 0) break; p = munchstring(ep, NULL, '\0'); macdefine(&e->e_macro, A_TEMP, mid, p); break; case 'H': /* required header line */ (void) chompheader(&bp[1], CHHDR_DEF, NULL, e); break; case 'C': /* word class */ case 'T': /* trusted user (set class `t') */ if (bp[0] == 'C') { mid = macid_parse(&bp[1], &ep); if (mid == 0) break; expand(ep, exbuf, sizeof(exbuf), e); p = exbuf; } else { mid = 't'; p = &bp[1]; } while (*p != '\0') { register char *wd; char delim; while (*p != '\0' && isascii(*p) && isspace(*p)) p++; wd = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; delim = *p; *p = '\0'; if (wd[0] != '\0') setclass(mid, wd); *p = delim; } break; case 'F': /* word class from file */ mid = macid_parse(&bp[1], &ep); if (mid == 0) break; for (p = ep; isascii(*p) && isspace(*p); ) p++; if (p[0] == '-' && p[1] == 'o') { optional = true; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; while (isascii(*p) && isspace(*p)) p++; } else optional = false; /* check if [key]@map:spec */ ismap = false; if (!SM_IS_DIR_DELIM(*p) && *p != '|' && (q = strchr(p, '@')) != NULL) { q++; /* look for @LDAP or @map: in string */ if (strcmp(q, "LDAP") == 0 || (*q != ':' && strchr(q, ':') != NULL)) ismap = true; } if (ismap) { /* use entire spec */ file = p; } else { file = extrquotstr(p, &q, " ", &ok); if (!ok) { syserr("illegal filename '%s'", p); break; } } if (*file == '|' || ismap) p = "%s"; else { p = q; if (*p == '\0') p = "%s"; else { *p = '\0'; while (isascii(*++p) && isspace(*p)) continue; } } fileclass(mid, file, p, ismap, safe, optional); break; #if XLA case 'L': /* extended load average description */ xla_init(&bp[1]); break; #endif /* XLA */ #if defined(SUN_EXTENSIONS) && defined(SUN_LOOKUP_MACRO) case 'L': /* lookup macro */ case 'G': /* lookup class */ /* reserved for Sun -- NIS+ database lookup */ if (VendorCode != VENDOR_SUN) goto badline; sun_lg_config_line(bp, e); break; #endif /* defined(SUN_EXTENSIONS) && defined(SUN_LOOKUP_MACRO) */ case 'M': /* define mailer */ makemailer(&bp[1]); break; case 'O': /* set option */ setoption(bp[1], &bp[2], safe, false, e); break; case 'P': /* set precedence */ if (NumPriorities >= MAXPRIORITIES) { toomany('P', MAXPRIORITIES); break; } for (p = &bp[1]; *p != '\0' && *p != '='; p++) continue; if (*p == '\0') goto badline; *p = '\0'; Priorities[NumPriorities].pri_name = newstr(&bp[1]); Priorities[NumPriorities].pri_val = atoi(++p); NumPriorities++; break; case 'Q': /* define queue */ makequeue(&bp[1], true); break; case 'V': /* configuration syntax version */ for (p = &bp[1]; isascii(*p) && isspace(*p); p++) continue; if (!isascii(*p) || !isdigit(*p)) { syserr("invalid argument to V line: \"%.20s\"", &bp[1]); break; } ConfigLevel = strtol(p, &ep, 10); /* ** Do heuristic tweaking for back compatibility. */ if (ConfigLevel >= 5) { /* level 5 configs have short name in $w */ p = macvalue('w', e); if (p != NULL && (p = strchr(p, '.')) != NULL) { *p = '\0'; macdefine(&e->e_macro, A_TEMP, 'w', macvalue('w', e)); } } if (ConfigLevel >= 6) { ColonOkInAddr = false; } /* ** Look for vendor code. */ if (*ep++ == '/') { /* extract vendor code */ for (p = ep; isascii(*p) && isalpha(*p); ) p++; *p = '\0'; if (!setvendor(ep)) syserr("invalid V line vendor code: \"%s\"", ep); } break; case 'K': expand(&bp[1], exbuf, sizeof(exbuf), e); (void) makemapentry(exbuf); break; case 'E': p = strchr(bp, '='); if (p != NULL) *p++ = '\0'; sm_setuserenv(&bp[1], p); break; case 'X': /* mail filter */ #if MILTER milter_setup(&bp[1]); #else /* MILTER */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Filter usage ('X') requires Milter support (-DMILTER)\n"); #endif /* MILTER */ break; default: badline: syserr("unknown configuration line \"%s\"", bp); } if (bp != buf) sm_free(bp); /* XXX */ } if (sm_io_error(cf)) { syserr("I/O read error"); finis(false, true, EX_OSFILE); } (void) sm_io_close(cf, SM_TIME_DEFAULT); FileName = NULL; /* initialize host maps from local service tables */ inithostmaps(); /* initialize daemon (if not defined yet) */ initdaemon(); /* determine if we need to do special name-server frotz */ { int nmaps; char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; nmaps = switch_map_find("hosts", maptype, mapreturn); UseNameServer = false; if (nmaps > 0 && nmaps <= MAXMAPSTACK) { register int mapno; for (mapno = 0; mapno < nmaps && !UseNameServer; mapno++) { if (strcmp(maptype[mapno], "dns") == 0) UseNameServer = true; } } } } /* ** TRANSLATE_DOLLARS -- convert $x into internal form ** ** Actually does all appropriate pre-processing of a config line ** to turn it into internal form. ** ** Parameters: ** ibp -- the buffer to translate. ** obp -- where to put the translation; may be the same as obp ** bsp -- a pointer to the size of obp; will be updated if ** the buffer needs to be replaced. ** ** Returns: ** The buffer pointer; may differ from obp if the expansion ** is larger then *bsp, in which case this will point to ** malloc()ed memory which must be free()d by the caller. */ char * translate_dollars(ibp, obp, bsp) char *ibp; char *obp; int *bsp; { register char *p; auto char *ep; char *bp; if (tTd(37, 53)) { sm_dprintf("translate_dollars("); xputs(sm_debug_file(), ibp); sm_dprintf(")\n"); } bp = quote_internal_chars(ibp, obp, bsp); for (p = bp; *p != '\0'; p++) { if (*p == '#' && p > bp && ConfigLevel >= 3) { register char *e; switch (*--p & 0377) { case MACROEXPAND: /* it's from $# -- let it go through */ p++; break; case '\\': /* it's backslash escaped */ (void) sm_strlcpy(p, p + 1, strlen(p)); break; default: /* delete leading white space */ while (isascii(*p) && isspace(*p) && *p != '\n' && p > bp) { p--; } if ((e = strchr(++p, '\n')) != NULL) (void) sm_strlcpy(p, e, strlen(p)); else *p-- = '\0'; break; } continue; } if (*p != '$' || p[1] == '\0') continue; if (p[1] == '$') { /* actual dollar sign.... */ (void) sm_strlcpy(p, p + 1, strlen(p)); continue; } /* convert to macro expansion character */ *p++ = MACROEXPAND; /* special handling for $=, $~, $&, and $? */ if (*p == '=' || *p == '~' || *p == '&' || *p == '?') p++; /* convert macro name to code */ *p = macid_parse(p, &ep); if (ep != p + 1) (void) sm_strlcpy(p + 1, ep, strlen(p + 1)); } /* strip trailing white space from the line */ while (--p > bp && isascii(*p) && isspace(*p)) *p = '\0'; if (tTd(37, 53)) { sm_dprintf(" translate_dollars => "); xputs(sm_debug_file(), bp); sm_dprintf("\n"); } return bp; } /* ** TOOMANY -- signal too many of some option ** ** Parameters: ** id -- the id of the error line ** maxcnt -- the maximum possible values ** ** Returns: ** none. ** ** Side Effects: ** gives a syserr. */ static void toomany(id, maxcnt) int id; int maxcnt; { syserr("too many %c lines, %d max", id, maxcnt); } /* ** FILECLASS -- read members of a class from a file ** ** Parameters: ** class -- class to define. ** filename -- name of file to read. ** fmt -- scanf string to use for match. ** ismap -- if set, this is a map lookup. ** safe -- if set, this is a safe read. ** optional -- if set, it is not an error for the file to ** not exist. ** ** Returns: ** none ** ** Side Effects: ** puts all lines in filename that match a scanf into ** the named class. */ /* ** Break up the match into words and add to class. */ static void parse_class_words(class, line) int class; char *line; { while (line != NULL && *line != '\0') { register char *q; /* strip leading spaces */ while (isascii(*line) && isspace(*line)) line++; if (*line == '\0') break; /* find the end of the word */ q = line; while (*line != '\0' && !(isascii(*line) && isspace(*line))) line++; if (*line != '\0') *line++ = '\0'; /* enter the word in the symbol table */ setclass(class, q); } } static void fileclass(class, filename, fmt, ismap, safe, optional) int class; char *filename; char *fmt; bool ismap; bool safe; bool optional; { SM_FILE_T *f; long sff; pid_t pid; register char *p; char buf[MAXLINE]; if (tTd(37, 2)) sm_dprintf("fileclass(%s, fmt=%s)\n", filename, fmt); if (*filename == '\0') { syserr("fileclass: missing file name"); return; } else if (ismap) { int status = 0; char *key; char *mn; char *cl, *spec; STAB *mapclass; MAP map; mn = newstr(macname(class)); key = filename; /* skip past key */ if ((p = strchr(filename, '@')) == NULL) { /* should not happen */ syserr("fileclass: bogus map specification"); sm_free(mn); return; } /* skip past '@' */ *p++ = '\0'; cl = p; #if LDAPMAP if (strcmp(cl, "LDAP") == 0) { int n; char *lc; char jbuf[MAXHOSTNAMELEN]; char lcbuf[MAXLINE]; /* Get $j */ expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope); if (jbuf[0] == '\0') { (void) sm_strlcpy(jbuf, "localhost", sizeof(jbuf)); } /* impose the default schema */ lc = macvalue(macid("{sendmailMTACluster}"), CurEnv); if (lc == NULL) lc = ""; else { expand(lc, lcbuf, sizeof(lcbuf), CurEnv); lc = lcbuf; } cl = "ldap"; n = sm_snprintf(buf, sizeof(buf), "-k (&(objectClass=sendmailMTAClass)(sendmailMTAClassName=%s)(|(sendmailMTACluster=%s)(sendmailMTAHost=%s))) -v sendmailMTAClassValue,sendmailMTAClassSearch:FILTER:sendmailMTAClass,sendmailMTAClassURL:URL:sendmailMTAClass", mn, lc, jbuf); if (n >= sizeof(buf)) { syserr("fileclass: F{%s}: Default LDAP string too long", mn); sm_free(mn); return; } spec = buf; } else #endif /* LDAPMAP */ { if ((spec = strchr(cl, ':')) == NULL) { syserr("fileclass: F{%s}: missing map class", mn); sm_free(mn); return; } *spec++ ='\0'; } /* set up map structure */ mapclass = stab(cl, ST_MAPCLASS, ST_FIND); if (mapclass == NULL) { syserr("fileclass: F{%s}: class %s not available", mn, cl); sm_free(mn); return; } memset(&map, '\0', sizeof(map)); map.map_class = &mapclass->s_mapclass; map.map_mname = mn; map.map_mflags |= MF_FILECLASS; if (tTd(37, 5)) sm_dprintf("fileclass: F{%s}: map class %s, key %s, spec %s\n", mn, cl, key, spec); /* parse map spec */ if (!map.map_class->map_parse(&map, spec)) { /* map_parse() showed the error already */ sm_free(mn); return; } map.map_mflags |= MF_VALID; /* open map */ if (map.map_class->map_open(&map, O_RDONLY)) { map.map_mflags |= MF_OPEN; map.map_pid = getpid(); } else { if (!optional && !bitset(MF_OPTIONAL, map.map_mflags)) syserr("fileclass: F{%s}: map open failed", mn); sm_free(mn); return; } /* lookup */ p = (*map.map_class->map_lookup)(&map, key, NULL, &status); if (status != EX_OK && status != EX_NOTFOUND) { if (!optional) syserr("fileclass: F{%s}: map lookup failed", mn); p = NULL; } /* use the results */ if (p != NULL) parse_class_words(class, p); /* close map */ map.map_mflags |= MF_CLOSING; map.map_class->map_close(&map); map.map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING); sm_free(mn); return; } else if (filename[0] == '|') { auto int fd; int i; char *argv[MAXPV + 1]; i = 0; for (p = strtok(&filename[1], " \t"); p != NULL && i < MAXPV; p = strtok(NULL, " \t")) argv[i++] = p; argv[i] = NULL; pid = prog_open(argv, &fd, CurEnv); if (pid < 0) f = NULL; else f = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &fd, SM_IO_RDONLY, NULL); } else { pid = -1; sff = SFF_REGONLY; if (!bitnset(DBS_CLASSFILEINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_SAFEDIRPATH; if (!bitnset(DBS_LINKEDCLASSFILEINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; if (safe) sff |= SFF_OPENASROOT; else if (RealUid == 0) sff |= SFF_ROOTOK; if (DontLockReadFiles) sff |= SFF_NOLOCK; f = safefopen(filename, O_RDONLY, 0, sff); } if (f == NULL) { if (!optional) syserr("fileclass: cannot open '%s'", filename); return; } - while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { #if SCANF char wordbuf[MAXLINE + 1]; #endif /* SCANF */ if (buf[0] == '#') continue; #if SCANF if (sm_io_sscanf(buf, fmt, wordbuf) != 1) continue; p = wordbuf; #else /* SCANF */ p = buf; #endif /* SCANF */ parse_class_words(class, p); /* ** If anything else is added here, ** check if the '@' map case above ** needs the code as well. */ } (void) sm_io_close(f, SM_TIME_DEFAULT); if (pid > 0) (void) waitfor(pid); } /* ** MAKEMAILER -- define a new mailer. ** ** Parameters: ** line -- description of mailer. This is in labeled ** fields. The fields are: ** A -- the argv for this mailer ** C -- the character set for MIME conversions ** D -- the directory to run in ** E -- the eol string ** F -- the flags associated with the mailer ** L -- the maximum line length ** M -- the maximum message size ** N -- the niceness at which to run ** P -- the path to the mailer ** Q -- the queue group for the mailer ** R -- the recipient rewriting set ** S -- the sender rewriting set ** T -- the mailer type (for DSNs) ** U -- the uid to run as ** W -- the time to wait at the end ** m -- maximum messages per connection ** r -- maximum number of recipients per message ** / -- new root directory ** The first word is the canonical name of the mailer. ** ** Returns: ** none. ** ** Side Effects: ** enters the mailer into the mailer table. */ void makemailer(line) char *line; { register char *p; register struct mailer *m; register STAB *s; int i; char fcode; auto char *endp; static int nextmailer = 0; /* "free" index into Mailer struct */ /* allocate a mailer and set up defaults */ m = (struct mailer *) xalloc(sizeof(*m)); memset((char *) m, '\0', sizeof(*m)); errno = 0; /* avoid bogus error text */ /* collect the mailer name */ for (p = line; *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p)); p++) continue; if (*p != '\0') *p++ = '\0'; if (line[0] == '\0') { syserr("name required for mailer"); return; } m->m_name = newstr(line); m->m_qgrp = NOQGRP; m->m_uid = NO_UID; m->m_gid = NO_GID; /* now scan through and assign info from the fields */ while (*p != '\0') { auto char *delimptr; while (*p != '\0' && (*p == ',' || (isascii(*p) && isspace(*p)))) p++; /* p now points to field code */ fcode = *p; while (*p != '\0' && *p != '=' && *p != ',') p++; if (*p++ != '=') { syserr("mailer %s: `=' expected", m->m_name); return; } while (isascii(*p) && isspace(*p)) p++; /* p now points to the field body */ p = munchstring(p, &delimptr, ','); /* install the field into the mailer struct */ switch (fcode) { case 'P': /* pathname */ if (*p != '\0') /* error is issued below */ m->m_mailer = newstr(p); break; case 'F': /* flags */ for (; *p != '\0'; p++) { if (!(isascii(*p) && isspace(*p))) { #if _FFR_DEPRECATE_MAILER_FLAG_I if (*p == M_INTERNAL) sm_syslog(LOG_WARNING, NOQID, "WARNING: mailer=%s, flag=%c deprecated", m->m_name, *p); #endif /* _FFR_DEPRECATE_MAILER_FLAG_I */ setbitn(bitidx(*p), m->m_flags); } } break; case 'S': /* sender rewriting ruleset */ case 'R': /* recipient rewriting ruleset */ i = strtorwset(p, &endp, ST_ENTER); if (i < 0) return; if (fcode == 'S') m->m_sh_rwset = m->m_se_rwset = i; else m->m_rh_rwset = m->m_re_rwset = i; p = endp; if (*p++ == '/') { i = strtorwset(p, NULL, ST_ENTER); if (i < 0) return; if (fcode == 'S') m->m_sh_rwset = i; else m->m_rh_rwset = i; } break; case 'E': /* end of line string */ if (*p == '\0') syserr("mailer %s: null end-of-line string", m->m_name); else m->m_eol = newstr(p); break; case 'A': /* argument vector */ if (*p != '\0') /* error is issued below */ m->m_argv = makeargv(p); break; case 'M': /* maximum message size */ m->m_maxsize = atol(p); break; case 'm': /* maximum messages per connection */ m->m_maxdeliveries = atoi(p); break; case 'r': /* max recipient per envelope */ m->m_maxrcpt = atoi(p); break; case 'L': /* maximum line length */ m->m_linelimit = atoi(p); if (m->m_linelimit < 0) m->m_linelimit = 0; break; case 'N': /* run niceness */ m->m_nice = atoi(p); break; case 'D': /* working directory */ if (*p == '\0') syserr("mailer %s: null working directory", m->m_name); else m->m_execdir = newstr(p); break; case 'C': /* default charset */ if (*p == '\0') syserr("mailer %s: null charset", m->m_name); else m->m_defcharset = newstr(p); break; case 'Q': /* queue for this mailer */ if (*p == '\0') { syserr("mailer %s: null queue", m->m_name); break; } s = stab(p, ST_QUEUE, ST_FIND); if (s == NULL) syserr("mailer %s: unknown queue %s", m->m_name, p); else m->m_qgrp = s->s_quegrp->qg_index; break; case 'T': /* MTA-Name/Address/Diagnostic types */ /* extract MTA name type; default to "dns" */ m->m_mtatype = newstr(p); p = strchr(m->m_mtatype, '/'); if (p != NULL) { *p++ = '\0'; if (*p == '\0') p = NULL; } if (*m->m_mtatype == '\0') m->m_mtatype = "dns"; /* extract address type; default to "rfc822" */ m->m_addrtype = p; if (p != NULL) p = strchr(p, '/'); if (p != NULL) { *p++ = '\0'; if (*p == '\0') p = NULL; } if (m->m_addrtype == NULL || *m->m_addrtype == '\0') m->m_addrtype = "rfc822"; /* extract diagnostic type; default to "smtp" */ m->m_diagtype = p; if (m->m_diagtype == NULL || *m->m_diagtype == '\0') m->m_diagtype = "smtp"; break; case 'U': /* user id */ if (isascii(*p) && !isdigit(*p)) { char *q = p; struct passwd *pw; while (*p != '\0' && isascii(*p) && (isalnum(*p) || strchr("-_", *p) != NULL)) p++; while (isascii(*p) && isspace(*p)) *p++ = '\0'; if (*p != '\0') *p++ = '\0'; if (*q == '\0') { syserr("mailer %s: null user name", m->m_name); break; } pw = sm_getpwnam(q); if (pw == NULL) { syserr("readcf: mailer U= flag: unknown user %s", q); break; } else { m->m_uid = pw->pw_uid; m->m_gid = pw->pw_gid; } } else { auto char *q; m->m_uid = strtol(p, &q, 0); p = q; while (isascii(*p) && isspace(*p)) p++; if (*p != '\0') p++; } while (isascii(*p) && isspace(*p)) p++; if (*p == '\0') break; if (isascii(*p) && !isdigit(*p)) { char *q = p; struct group *gr; while (isascii(*p) && isalnum(*p)) p++; *p++ = '\0'; if (*q == '\0') { syserr("mailer %s: null group name", m->m_name); break; } gr = getgrnam(q); if (gr == NULL) { syserr("readcf: mailer U= flag: unknown group %s", q); break; } else m->m_gid = gr->gr_gid; } else { m->m_gid = strtol(p, NULL, 0); } break; case 'W': /* wait timeout */ m->m_wait = convtime(p, 's'); break; case '/': /* new root directory */ if (*p == '\0') syserr("mailer %s: null root directory", m->m_name); else m->m_rootdir = newstr(p); break; default: syserr("M%s: unknown mailer equate %c=", m->m_name, fcode); break; } p = delimptr; } #if !HASRRESVPORT if (bitnset(M_SECURE_PORT, m->m_flags)) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "M%s: Warning: F=%c set on system that doesn't support rresvport()\n", m->m_name, M_SECURE_PORT); } #endif /* !HASRRESVPORT */ #if !HASNICE if (m->m_nice != 0) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "M%s: Warning: N= set on system that doesn't support nice()\n", m->m_name); } #endif /* !HASNICE */ /* do some rationality checking */ if (m->m_argv == NULL) { syserr("M%s: A= argument required", m->m_name); return; } if (m->m_mailer == NULL) { syserr("M%s: P= argument required", m->m_name); return; } if (nextmailer >= MAXMAILERS) { syserr("too many mailers defined (%d max)", MAXMAILERS); return; } if (m->m_maxrcpt <= 0) m->m_maxrcpt = DEFAULT_MAX_RCPT; /* do some heuristic cleanup for back compatibility */ if (bitnset(M_LIMITS, m->m_flags)) { if (m->m_linelimit == 0) m->m_linelimit = SMTPLINELIM; if (ConfigLevel < 2) setbitn(M_7BITS, m->m_flags); } if (strcmp(m->m_mailer, "[TCP]") == 0) { syserr("M%s: P=[TCP] must be replaced by P=[IPC]", m->m_name); return; } if (strcmp(m->m_mailer, "[IPC]") == 0) { /* Use the second argument for host or path to socket */ if (m->m_argv[0] == NULL || m->m_argv[1] == NULL || m->m_argv[1][0] == '\0') { syserr("M%s: too few parameters for %s mailer", m->m_name, m->m_mailer); return; } if (strcmp(m->m_argv[0], "TCP") != 0 #if NETUNIX && strcmp(m->m_argv[0], "FILE") != 0 #endif /* NETUNIX */ ) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "M%s: Warning: first argument in %s mailer must be %s\n", m->m_name, m->m_mailer, #if NETUNIX "TCP or FILE" #else /* NETUNIX */ "TCP" #endif /* NETUNIX */ ); } if (m->m_mtatype == NULL) m->m_mtatype = "dns"; if (m->m_addrtype == NULL) m->m_addrtype = "rfc822"; if (m->m_diagtype == NULL) { if (m->m_argv[0] != NULL && strcmp(m->m_argv[0], "FILE") == 0) m->m_diagtype = "x-unix"; else m->m_diagtype = "smtp"; } } else if (strcmp(m->m_mailer, "[FILE]") == 0) { /* Use the second argument for filename */ if (m->m_argv[0] == NULL || m->m_argv[1] == NULL || m->m_argv[2] != NULL) { syserr("M%s: too %s parameters for [FILE] mailer", m->m_name, (m->m_argv[0] == NULL || m->m_argv[1] == NULL) ? "few" : "many"); return; } else if (strcmp(m->m_argv[0], "FILE") != 0) { syserr("M%s: first argument in [FILE] mailer must be FILE", m->m_name); return; } } if (m->m_eol == NULL) { char **pp; /* default for SMTP is \r\n; use \n for local delivery */ for (pp = m->m_argv; *pp != NULL; pp++) { for (p = *pp; *p != '\0'; ) { if ((*p++ & 0377) == MACROEXPAND && *p == 'u') break; } if (*p != '\0') break; } if (*pp == NULL) m->m_eol = "\r\n"; else m->m_eol = "\n"; } /* enter the mailer into the symbol table */ s = stab(m->m_name, ST_MAILER, ST_ENTER); if (s->s_mailer != NULL) { i = s->s_mailer->m_mno; sm_free(s->s_mailer); /* XXX */ } else { i = nextmailer++; } Mailer[i] = s->s_mailer = m; m->m_mno = i; } /* ** MUNCHSTRING -- translate a string into internal form. ** ** Parameters: ** p -- the string to munch. ** delimptr -- if non-NULL, set to the pointer of the ** field delimiter character. ** delim -- the delimiter for the field. ** ** Returns: ** the munched string. ** ** Side Effects: ** the munched string is a local static buffer. ** it must be copied before the function is called again. */ char * munchstring(p, delimptr, delim) register char *p; char **delimptr; int delim; { register char *q; bool backslash = false; bool quotemode = false; static char buf[MAXLINE]; for (q = buf; *p != '\0' && q < &buf[sizeof(buf) - 1]; p++) { if (backslash) { /* everything is roughly literal */ backslash = false; switch (*p) { case 'r': /* carriage return */ *q++ = '\r'; continue; case 'n': /* newline */ *q++ = '\n'; continue; case 'f': /* form feed */ *q++ = '\f'; continue; case 'b': /* backspace */ *q++ = '\b'; continue; } *q++ = *p; } else { if (*p == '\\') backslash = true; else if (*p == '"') quotemode = !quotemode; else if (quotemode || *p != delim) *q++ = *p; else break; } } if (delimptr != NULL) *delimptr = p; *q++ = '\0'; return buf; } /* ** EXTRQUOTSTR -- extract a (quoted) string. ** ** This routine deals with quoted (") strings and escaped ** spaces (\\ ). ** ** Parameters: ** p -- source string. ** delimptr -- if non-NULL, set to the pointer of the ** field delimiter character. ** delimbuf -- delimiters for the field. ** st -- if non-NULL, store the return value (whether the ** string was correctly quoted) here. ** ** Returns: ** the extracted string. ** ** Side Effects: ** the returned string is a local static buffer. ** it must be copied before the function is called again. */ static char * extrquotstr(p, delimptr, delimbuf, st) register char *p; char **delimptr; char *delimbuf; bool *st; { register char *q; bool backslash = false; bool quotemode = false; static char buf[MAXLINE]; for (q = buf; *p != '\0' && q < &buf[sizeof(buf) - 1]; p++) { if (backslash) { backslash = false; if (*p != ' ') *q++ = '\\'; } if (*p == '\\') backslash = true; else if (*p == '"') quotemode = !quotemode; else if (quotemode || strchr(delimbuf, (int) *p) == NULL) *q++ = *p; else break; } if (delimptr != NULL) *delimptr = p; *q++ = '\0'; if (st != NULL) *st = !(quotemode || backslash); return buf; } /* ** MAKEARGV -- break up a string into words ** ** Parameters: ** p -- the string to break up. ** ** Returns: ** a char **argv (dynamically allocated) ** ** Side Effects: ** munges p. */ static char ** makeargv(p) register char *p; { char *q; int i; char **avp; char *argv[MAXPV + 1]; /* take apart the words */ i = 0; while (*p != '\0' && i < MAXPV) { q = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; while (isascii(*p) && isspace(*p)) *p++ = '\0'; argv[i++] = newstr(q); } argv[i++] = NULL; /* now make a copy of the argv */ avp = (char **) xalloc(sizeof(*avp) * i); memmove((char *) avp, (char *) argv, sizeof(*avp) * i); return avp; } /* ** PRINTRULES -- print rewrite rules (for debugging) ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** prints rewrite rules. */ void printrules() { register struct rewrite *rwp; register int ruleset; for (ruleset = 0; ruleset < 10; ruleset++) { if (RewriteRules[ruleset] == NULL) continue; sm_dprintf("\n----Rule Set %d:", ruleset); for (rwp = RewriteRules[ruleset]; rwp != NULL; rwp = rwp->r_next) { sm_dprintf("\nLHS:"); printav(sm_debug_file(), rwp->r_lhs); sm_dprintf("RHS:"); printav(sm_debug_file(), rwp->r_rhs); } } } /* ** PRINTMAILER -- print mailer structure (for debugging) ** ** Parameters: ** fp -- output file ** m -- the mailer to print ** ** Returns: ** none. */ void printmailer(fp, m) SM_FILE_T *fp; register MAILER *m; { int j; (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "mailer %d (%s): P=%s S=", m->m_mno, m->m_name, m->m_mailer); if (RuleSetNames[m->m_se_rwset] == NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d/", m->m_se_rwset); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s/", RuleSetNames[m->m_se_rwset]); if (RuleSetNames[m->m_sh_rwset] == NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d R=", m->m_sh_rwset); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s R=", RuleSetNames[m->m_sh_rwset]); if (RuleSetNames[m->m_re_rwset] == NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d/", m->m_re_rwset); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s/", RuleSetNames[m->m_re_rwset]); if (RuleSetNames[m->m_rh_rwset] == NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d ", m->m_rh_rwset); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s ", RuleSetNames[m->m_rh_rwset]); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "M=%ld U=%d:%d F=", m->m_maxsize, (int) m->m_uid, (int) m->m_gid); for (j = '\0'; j <= '\177'; j++) if (bitnset(j, m->m_flags)) (void) sm_io_putc(fp, SM_TIME_DEFAULT, j); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " L=%d E=", m->m_linelimit); xputs(fp, m->m_eol); if (m->m_defcharset != NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " C=%s", m->m_defcharset); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " T=%s/%s/%s", m->m_mtatype == NULL ? "" : m->m_mtatype, m->m_addrtype == NULL ? "" : m->m_addrtype, m->m_diagtype == NULL ? "" : m->m_diagtype); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " r=%d", m->m_maxrcpt); if (m->m_argv != NULL) { char **a = m->m_argv; (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " A="); while (*a != NULL) { if (a != m->m_argv) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " "); xputs(fp, *a++); } } (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\n"); } /* ** SETOPTION -- set global processing option ** ** Parameters: ** opt -- option name. ** val -- option value (as a text string). ** safe -- set if this came from a configuration file. ** Some options (if set from the command line) will ** reset the user id to avoid security problems. ** sticky -- if set, don't let other setoptions override ** this value. ** e -- the main envelope. ** ** Returns: ** none. ** ** Side Effects: ** Sets options as implied by the arguments. */ static BITMAP256 StickyOpt; /* set if option is stuck */ #if NAMED_BIND static struct resolverflags { char *rf_name; /* name of the flag */ long rf_bits; /* bits to set/clear */ } ResolverFlags[] = { { "debug", RES_DEBUG }, { "aaonly", RES_AAONLY }, { "usevc", RES_USEVC }, { "primary", RES_PRIMARY }, { "igntc", RES_IGNTC }, { "recurse", RES_RECURSE }, { "defnames", RES_DEFNAMES }, { "stayopen", RES_STAYOPEN }, { "dnsrch", RES_DNSRCH }, # ifdef RES_USE_INET6 { "use_inet6", RES_USE_INET6 }, # endif /* RES_USE_INET6 */ { "true", 0 }, /* avoid error on old syntax */ { NULL, 0 } }; #endif /* NAMED_BIND */ #define OI_NONE 0 /* no special treatment */ #define OI_SAFE 0x0001 /* safe for random people to use */ #define OI_SUBOPT 0x0002 /* option has suboptions */ static struct optioninfo { char *o_name; /* long name of option */ unsigned char o_code; /* short name of option */ unsigned short o_flags; /* option flags */ } OptionTab[] = { #if defined(SUN_EXTENSIONS) && defined(REMOTE_MODE) { "RemoteMode", '>', OI_NONE }, #endif /* defined(SUN_EXTENSIONS) && defined(REMOTE_MODE) */ { "SevenBitInput", '7', OI_SAFE }, { "EightBitMode", '8', OI_SAFE }, { "AliasFile", 'A', OI_NONE }, { "AliasWait", 'a', OI_NONE }, { "BlankSub", 'B', OI_NONE }, { "MinFreeBlocks", 'b', OI_SAFE }, { "CheckpointInterval", 'C', OI_SAFE }, { "HoldExpensive", 'c', OI_NONE }, { "DeliveryMode", 'd', OI_SAFE }, { "ErrorHeader", 'E', OI_NONE }, { "ErrorMode", 'e', OI_SAFE }, { "TempFileMode", 'F', OI_NONE }, { "SaveFromLine", 'f', OI_NONE }, { "MatchGECOS", 'G', OI_NONE }, /* no long name, just here to avoid problems in setoption */ { "", 'g', OI_NONE }, { "HelpFile", 'H', OI_NONE }, { "MaxHopCount", 'h', OI_NONE }, { "ResolverOptions", 'I', OI_NONE }, { "IgnoreDots", 'i', OI_SAFE }, { "ForwardPath", 'J', OI_NONE }, { "SendMimeErrors", 'j', OI_SAFE }, { "ConnectionCacheSize", 'k', OI_NONE }, { "ConnectionCacheTimeout", 'K', OI_NONE }, { "UseErrorsTo", 'l', OI_NONE }, { "LogLevel", 'L', OI_SAFE }, { "MeToo", 'm', OI_SAFE }, /* no long name, just here to avoid problems in setoption */ { "", 'M', OI_NONE }, { "CheckAliases", 'n', OI_NONE }, { "OldStyleHeaders", 'o', OI_SAFE }, { "DaemonPortOptions", 'O', OI_NONE }, { "PrivacyOptions", 'p', OI_SAFE }, { "PostmasterCopy", 'P', OI_NONE }, { "QueueFactor", 'q', OI_NONE }, { "QueueDirectory", 'Q', OI_NONE }, { "DontPruneRoutes", 'R', OI_NONE }, { "Timeout", 'r', OI_SUBOPT }, { "StatusFile", 'S', OI_NONE }, { "SuperSafe", 's', OI_SAFE }, { "QueueTimeout", 'T', OI_NONE }, { "TimeZoneSpec", 't', OI_NONE }, { "UserDatabaseSpec", 'U', OI_NONE }, { "DefaultUser", 'u', OI_NONE }, { "FallbackMXhost", 'V', OI_NONE }, { "Verbose", 'v', OI_SAFE }, { "TryNullMXList", 'w', OI_NONE }, { "QueueLA", 'x', OI_NONE }, { "RefuseLA", 'X', OI_NONE }, { "RecipientFactor", 'y', OI_NONE }, { "ForkEachJob", 'Y', OI_NONE }, { "ClassFactor", 'z', OI_NONE }, { "RetryFactor", 'Z', OI_NONE }, #define O_QUEUESORTORD 0x81 { "QueueSortOrder", O_QUEUESORTORD, OI_SAFE }, #define O_HOSTSFILE 0x82 { "HostsFile", O_HOSTSFILE, OI_NONE }, #define O_MQA 0x83 { "MinQueueAge", O_MQA, OI_SAFE }, #define O_DEFCHARSET 0x85 { "DefaultCharSet", O_DEFCHARSET, OI_SAFE }, #define O_SSFILE 0x86 { "ServiceSwitchFile", O_SSFILE, OI_NONE }, #define O_DIALDELAY 0x87 { "DialDelay", O_DIALDELAY, OI_SAFE }, #define O_NORCPTACTION 0x88 { "NoRecipientAction", O_NORCPTACTION, OI_SAFE }, #define O_SAFEFILEENV 0x89 { "SafeFileEnvironment", O_SAFEFILEENV, OI_NONE }, #define O_MAXMSGSIZE 0x8a { "MaxMessageSize", O_MAXMSGSIZE, OI_NONE }, #define O_COLONOKINADDR 0x8b { "ColonOkInAddr", O_COLONOKINADDR, OI_SAFE }, #define O_MAXQUEUERUN 0x8c { "MaxQueueRunSize", O_MAXQUEUERUN, OI_SAFE }, #define O_MAXCHILDREN 0x8d { "MaxDaemonChildren", O_MAXCHILDREN, OI_NONE }, #define O_KEEPCNAMES 0x8e { "DontExpandCnames", O_KEEPCNAMES, OI_NONE }, #define O_MUSTQUOTE 0x8f { "MustQuoteChars", O_MUSTQUOTE, OI_NONE }, #define O_SMTPGREETING 0x90 { "SmtpGreetingMessage", O_SMTPGREETING, OI_NONE }, #define O_UNIXFROM 0x91 { "UnixFromLine", O_UNIXFROM, OI_NONE }, #define O_OPCHARS 0x92 { "OperatorChars", O_OPCHARS, OI_NONE }, #define O_DONTINITGRPS 0x93 { "DontInitGroups", O_DONTINITGRPS, OI_NONE }, #define O_SLFH 0x94 { "SingleLineFromHeader", O_SLFH, OI_SAFE }, #define O_ABH 0x95 { "AllowBogusHELO", O_ABH, OI_SAFE }, #define O_CONNTHROT 0x97 { "ConnectionRateThrottle", O_CONNTHROT, OI_NONE }, #define O_UGW 0x99 { "UnsafeGroupWrites", O_UGW, OI_NONE }, #define O_DBLBOUNCE 0x9a { "DoubleBounceAddress", O_DBLBOUNCE, OI_NONE }, #define O_HSDIR 0x9b { "HostStatusDirectory", O_HSDIR, OI_NONE }, #define O_SINGTHREAD 0x9c { "SingleThreadDelivery", O_SINGTHREAD, OI_NONE }, #define O_RUNASUSER 0x9d { "RunAsUser", O_RUNASUSER, OI_NONE }, #define O_DSN_RRT 0x9e { "RrtImpliesDsn", O_DSN_RRT, OI_NONE }, #define O_PIDFILE 0x9f { "PidFile", O_PIDFILE, OI_NONE }, #define O_DONTBLAMESENDMAIL 0xa0 { "DontBlameSendmail", O_DONTBLAMESENDMAIL, OI_NONE }, #define O_DPI 0xa1 { "DontProbeInterfaces", O_DPI, OI_NONE }, #define O_MAXRCPT 0xa2 { "MaxRecipientsPerMessage", O_MAXRCPT, OI_SAFE }, #define O_DEADLETTER 0xa3 { "DeadLetterDrop", O_DEADLETTER, OI_NONE }, #if _FFR_DONTLOCKFILESFORREAD_OPTION # define O_DONTLOCK 0xa4 { "DontLockFilesForRead", O_DONTLOCK, OI_NONE }, #endif /* _FFR_DONTLOCKFILESFORREAD_OPTION */ #define O_MAXALIASRCSN 0xa5 { "MaxAliasRecursion", O_MAXALIASRCSN, OI_NONE }, #define O_CNCTONLYTO 0xa6 { "ConnectOnlyTo", O_CNCTONLYTO, OI_NONE }, #define O_TRUSTUSER 0xa7 { "TrustedUser", O_TRUSTUSER, OI_NONE }, #define O_MAXMIMEHDRLEN 0xa8 { "MaxMimeHeaderLength", O_MAXMIMEHDRLEN, OI_NONE }, #define O_CONTROLSOCKET 0xa9 { "ControlSocketName", O_CONTROLSOCKET, OI_NONE }, #define O_MAXHDRSLEN 0xaa { "MaxHeadersLength", O_MAXHDRSLEN, OI_NONE }, #if _FFR_MAX_FORWARD_ENTRIES # define O_MAXFORWARD 0xab { "MaxForwardEntries", O_MAXFORWARD, OI_NONE }, #endif /* _FFR_MAX_FORWARD_ENTRIES */ #define O_PROCTITLEPREFIX 0xac { "ProcessTitlePrefix", O_PROCTITLEPREFIX, OI_NONE }, #define O_SASLINFO 0xad #if _FFR_ALLOW_SASLINFO { "DefaultAuthInfo", O_SASLINFO, OI_SAFE }, #else /* _FFR_ALLOW_SASLINFO */ { "DefaultAuthInfo", O_SASLINFO, OI_NONE }, #endif /* _FFR_ALLOW_SASLINFO */ #define O_SASLMECH 0xae { "AuthMechanisms", O_SASLMECH, OI_NONE }, #define O_CLIENTPORT 0xaf { "ClientPortOptions", O_CLIENTPORT, OI_NONE }, #define O_DF_BUFSIZE 0xb0 { "DataFileBufferSize", O_DF_BUFSIZE, OI_NONE }, #define O_XF_BUFSIZE 0xb1 { "XscriptFileBufferSize", O_XF_BUFSIZE, OI_NONE }, #define O_LDAPDEFAULTSPEC 0xb2 { "LDAPDefaultSpec", O_LDAPDEFAULTSPEC, OI_NONE }, #define O_SRVCERTFILE 0xb4 { "ServerCertFile", O_SRVCERTFILE, OI_NONE }, #define O_SRVKEYFILE 0xb5 { "ServerKeyFile", O_SRVKEYFILE, OI_NONE }, #define O_CLTCERTFILE 0xb6 { "ClientCertFile", O_CLTCERTFILE, OI_NONE }, #define O_CLTKEYFILE 0xb7 { "ClientKeyFile", O_CLTKEYFILE, OI_NONE }, #define O_CACERTFILE 0xb8 { "CACertFile", O_CACERTFILE, OI_NONE }, #define O_CACERTPATH 0xb9 { "CACertPath", O_CACERTPATH, OI_NONE }, #define O_DHPARAMS 0xba { "DHParameters", O_DHPARAMS, OI_NONE }, #define O_INPUTMILTER 0xbb { "InputMailFilters", O_INPUTMILTER, OI_NONE }, #define O_MILTER 0xbc { "Milter", O_MILTER, OI_SUBOPT }, #define O_SASLOPTS 0xbd { "AuthOptions", O_SASLOPTS, OI_NONE }, #define O_QUEUE_FILE_MODE 0xbe { "QueueFileMode", O_QUEUE_FILE_MODE, OI_NONE }, #if _FFR_TLS_1 # define O_DHPARAMS5 0xbf { "DHParameters512", O_DHPARAMS5, OI_NONE }, # define O_CIPHERLIST 0xc0 { "CipherList", O_CIPHERLIST, OI_NONE }, #endif /* _FFR_TLS_1 */ #define O_RANDFILE 0xc1 { "RandFile", O_RANDFILE, OI_NONE }, #define O_TLS_SRV_OPTS 0xc2 { "TLSSrvOptions", O_TLS_SRV_OPTS, OI_NONE }, #define O_RCPTTHROT 0xc3 { "BadRcptThrottle", O_RCPTTHROT, OI_SAFE }, #define O_DLVR_MIN 0xc4 { "DeliverByMin", O_DLVR_MIN, OI_NONE }, #define O_MAXQUEUECHILDREN 0xc5 { "MaxQueueChildren", O_MAXQUEUECHILDREN, OI_NONE }, #define O_MAXRUNNERSPERQUEUE 0xc6 { "MaxRunnersPerQueue", O_MAXRUNNERSPERQUEUE, OI_NONE }, #define O_DIRECTSUBMODIFIERS 0xc7 { "DirectSubmissionModifiers", O_DIRECTSUBMODIFIERS, OI_NONE }, #define O_NICEQUEUERUN 0xc8 { "NiceQueueRun", O_NICEQUEUERUN, OI_NONE }, #define O_SHMKEY 0xc9 { "SharedMemoryKey", O_SHMKEY, OI_NONE }, #define O_SASLBITS 0xca { "AuthMaxBits", O_SASLBITS, OI_NONE }, #define O_MBDB 0xcb { "MailboxDatabase", O_MBDB, OI_NONE }, #define O_MSQ 0xcc { "UseMSP", O_MSQ, OI_NONE }, #define O_DELAY_LA 0xcd { "DelayLA", O_DELAY_LA, OI_NONE }, #define O_FASTSPLIT 0xce { "FastSplit", O_FASTSPLIT, OI_NONE }, #define O_SOFTBOUNCE 0xcf { "SoftBounce", O_SOFTBOUNCE, OI_NONE }, #define O_SHMKEYFILE 0xd0 { "SharedMemoryKeyFile", O_SHMKEYFILE, OI_NONE }, #define O_REJECTLOGINTERVAL 0xd1 { "RejectLogInterval", O_REJECTLOGINTERVAL, OI_NONE }, #define O_REQUIRES_DIR_FSYNC 0xd2 { "RequiresDirfsync", O_REQUIRES_DIR_FSYNC, OI_NONE }, #define O_CONNECTION_RATE_WINDOW_SIZE 0xd3 { "ConnectionRateWindowSize", O_CONNECTION_RATE_WINDOW_SIZE, OI_NONE }, #define O_CRLFILE 0xd4 { "CRLFile", O_CRLFILE, OI_NONE }, #define O_FALLBACKSMARTHOST 0xd5 { "FallbackSmartHost", O_FALLBACKSMARTHOST, OI_NONE }, #define O_SASLREALM 0xd6 { "AuthRealm", O_SASLREALM, OI_NONE }, #if _FFR_CRLPATH # define O_CRLPATH 0xd7 { "CRLPath", O_CRLPATH, OI_NONE }, #endif /* _FFR_CRLPATH */ #define O_HELONAME 0xd8 { "HeloName", O_HELONAME, OI_NONE }, #if _FFR_MEMSTAT # define O_REFUSELOWMEM 0xd9 { "RefuseLowMem", O_REFUSELOWMEM, OI_NONE }, # define O_QUEUELOWMEM 0xda { "QueueLowMem", O_QUEUELOWMEM, OI_NONE }, # define O_MEMRESOURCE 0xdb { "MemoryResource", O_MEMRESOURCE, OI_NONE }, #endif /* _FFR_MEMSTAT */ #define O_MAXNOOPCOMMANDS 0xdc { "MaxNOOPCommands", O_MAXNOOPCOMMANDS, OI_NONE }, #if _FFR_MSG_ACCEPT # define O_MSG_ACCEPT 0xdd { "MessageAccept", O_MSG_ACCEPT, OI_NONE }, #endif /* _FFR_MSG_ACCEPT */ #if _FFR_QUEUE_RUN_PARANOIA # define O_CHK_Q_RUNNERS 0xde { "CheckQueueRunners", O_CHK_Q_RUNNERS, OI_NONE }, #endif /* _FFR_QUEUE_RUN_PARANOIA */ #if _FFR_EIGHT_BIT_ADDR_OK # if !ALLOW_255 # ERROR FFR_EIGHT_BIT_ADDR_OK requires _ALLOW_255 # endif /* !ALLOW_255 */ # define O_EIGHT_BIT_ADDR_OK 0xdf { "EightBitAddrOK", O_EIGHT_BIT_ADDR_OK, OI_NONE }, #endif /* _FFR_EIGHT_BIT_ADDR_OK */ #if _FFR_ADDR_TYPE_MODES # define O_ADDR_TYPE_MODES 0xe0 { "AddrTypeModes", O_ADDR_TYPE_MODES, OI_NONE }, #endif /* _FFR_ADDR_TYPE_MODES */ #if _FFR_BADRCPT_SHUTDOWN # define O_RCPTSHUTD 0xe1 { "BadRcptShutdown", O_RCPTSHUTD, OI_SAFE }, # define O_RCPTSHUTDG 0xe2 { "BadRcptShutdownGood", O_RCPTSHUTDG, OI_SAFE }, #endif /* _FFR_BADRCPT_SHUTDOWN */ #if STARTTLS && _FFR_TLS_1 # define O_SRV_SSL_OPTIONS 0xe3 { "ServerSSLOptions", O_SRV_SSL_OPTIONS, OI_NONE }, # define O_CLT_SSL_OPTIONS 0xe4 { "ClientSSLOptions", O_CLT_SSL_OPTIONS, OI_NONE }, #endif /* STARTTLS && _FFR_TLS_1 */ #if _FFR_EXPDELAY # define O_MAX_QUEUE_AGE 0xe5 { "MaxQueueAge", O_MAX_QUEUE_AGE, OI_NONE }, #endif /* _FFR_EXPDELAY */ #if _FFR_RCPTTHROTDELAY # define O_RCPTTHROTDELAY 0xe6 { "BadRcptThrottleDelay", O_RCPTTHROTDELAY, OI_SAFE }, #endif /* _FFR_RCPTTHROTDELAY */ #if 0 && _FFR_QOS && defined(SOL_IP) && defined(IP_TOS) # define O_INETQOS 0xe7 /* reserved for FFR_QOS */ { "InetQoS", O_INETQOS, OI_NONE }, #endif +#if STARTTLS && _FFR_FIPSMODE +# define O_FIPSMODE 0xe8 + { "FIPSMode", O_FIPSMODE, OI_NONE }, +#endif /* STARTTLS && _FFR_FIPSMODE */ +#if _FFR_REJECT_NUL_BYTE +# define O_REJECTNUL 0xe9 + { "RejectNUL", O_REJECTNUL, OI_SAFE }, +#endif /* _FFR_REJECT_NUL_BYTE */ { NULL, '\0', OI_NONE } }; #if STARTTLS && _FFR_TLS_1 static struct ssl_options { const char *sslopt_name; /* name of the flag */ long sslopt_bits; /* bits to set/clear */ } SSL_Option[] = { /* these are turned on by default */ #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG { "SSL_OP_MICROSOFT_SESS_ID_BUG", SSL_OP_MICROSOFT_SESS_ID_BUG }, #endif #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG { "SSL_OP_NETSCAPE_CHALLENGE_BUG", SSL_OP_NETSCAPE_CHALLENGE_BUG }, #endif #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG { "SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG }, #endif #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG { "SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG }, #endif #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER { "SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER }, #endif #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING { "SSL_OP_MSIE_SSLV2_RSA_PADDING", SSL_OP_MSIE_SSLV2_RSA_PADDING }, #endif #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG { "SSL_OP_SSLEAY_080_CLIENT_DH_BUG", SSL_OP_SSLEAY_080_CLIENT_DH_BUG }, #endif #ifdef SSL_OP_TLS_D5_BUG { "SSL_OP_TLS_D5_BUG", SSL_OP_TLS_D5_BUG }, #endif #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG { "SSL_OP_TLS_BLOCK_PADDING_BUG", SSL_OP_TLS_BLOCK_PADDING_BUG }, #endif #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS { "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS }, #endif #ifdef SSL_OP_ALL { "SSL_OP_ALL", SSL_OP_ALL }, #endif #ifdef SSL_OP_NO_QUERY_MTU { "SSL_OP_NO_QUERY_MTU", SSL_OP_NO_QUERY_MTU }, #endif #ifdef SSL_OP_COOKIE_EXCHANGE { "SSL_OP_COOKIE_EXCHANGE", SSL_OP_COOKIE_EXCHANGE }, #endif #ifdef SSL_OP_NO_TICKET { "SSL_OP_NO_TICKET", SSL_OP_NO_TICKET }, #endif #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION { "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION }, #endif #ifdef SSL_OP_SINGLE_ECDH_USE { "SSL_OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE }, #endif #ifdef SSL_OP_SINGLE_DH_USE { "SSL_OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE }, #endif #ifdef SSL_OP_EPHEMERAL_RSA { "SSL_OP_EPHEMERAL_RSA", SSL_OP_EPHEMERAL_RSA }, #endif #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE { "SSL_OP_CIPHER_SERVER_PREFERENCE", SSL_OP_CIPHER_SERVER_PREFERENCE }, #endif #ifdef SSL_OP_TLS_ROLLBACK_BUG { "SSL_OP_TLS_ROLLBACK_BUG", SSL_OP_TLS_ROLLBACK_BUG }, #endif #ifdef SSL_OP_NO_SSLv2 { "SSL_OP_NO_SSLv2", SSL_OP_NO_SSLv2 }, #endif #ifdef SSL_OP_NO_SSLv3 { "SSL_OP_NO_SSLv3", SSL_OP_NO_SSLv3 }, #endif #ifdef SSL_OP_NO_TLSv1 { "SSL_OP_NO_TLSv1", SSL_OP_NO_TLSv1 }, #endif #ifdef SSL_OP_PKCS1_CHECK_1 { "SSL_OP_PKCS1_CHECK_1", SSL_OP_PKCS1_CHECK_1 }, #endif #ifdef SSL_OP_PKCS1_CHECK_2 { "SSL_OP_PKCS1_CHECK_2", SSL_OP_PKCS1_CHECK_2 }, #endif #ifdef SSL_OP_NETSCAPE_CA_DN_BUG { "SSL_OP_NETSCAPE_CA_DN_BUG", SSL_OP_NETSCAPE_CA_DN_BUG }, #endif #ifdef SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG { "SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG }, #endif { NULL, 0 } }; #endif /* STARTTLS && _FFR_TLS_1 */ # define CANONIFY(val) # define SET_OPT_DEFAULT(opt, val) opt = val /* set a string option by expanding the value and assigning it */ /* WARNING this belongs ONLY into a case statement! */ #define SET_STRING_EXP(str) \ expand(val, exbuf, sizeof(exbuf), e); \ newval = sm_pstrdup_x(exbuf); \ if (str != NULL) \ sm_free(str); \ CANONIFY(newval); \ str = newval; \ break #define OPTNAME o->o_name == NULL ? "" : o->o_name void setoption(opt, val, safe, sticky, e) int opt; char *val; bool safe; bool sticky; register ENVELOPE *e; { register char *p; register struct optioninfo *o; char *subopt; int mid; bool can_setuid = RunAsUid == 0; auto char *ep; char buf[50]; extern bool Warn_Q_option; #if _FFR_ALLOW_SASLINFO extern unsigned int SubmitMode; #endif /* _FFR_ALLOW_SASLINFO */ #if STARTTLS || SM_CONF_SHM char *newval; char exbuf[MAXLINE]; #endif /* STARTTLS || SM_CONF_SHM */ #if STARTTLS && _FFR_TLS_1 long *pssloptions = NULL; #endif /* STARTTLS && _FFR_TLS_1 */ errno = 0; if (opt == ' ') { /* full word options */ struct optioninfo *sel; p = strchr(val, '='); if (p == NULL) p = &val[strlen(val)]; while (*--p == ' ') continue; while (*++p == ' ') *p = '\0'; if (p == val) { syserr("readcf: null option name"); return; } if (*p == '=') *p++ = '\0'; while (*p == ' ') p++; subopt = strchr(val, '.'); if (subopt != NULL) *subopt++ = '\0'; sel = NULL; for (o = OptionTab; o->o_name != NULL; o++) { if (sm_strncasecmp(o->o_name, val, strlen(val)) != 0) continue; if (strlen(o->o_name) == strlen(val)) { /* completely specified -- this must be it */ sel = NULL; break; } if (sel != NULL) break; sel = o; } if (sel != NULL && o->o_name == NULL) o = sel; else if (o->o_name == NULL) { syserr("readcf: unknown option name %s", val); return; } else if (sel != NULL) { syserr("readcf: ambiguous option name %s (matches %s and %s)", val, sel->o_name, o->o_name); return; } if (strlen(val) != strlen(o->o_name)) { int oldVerbose = Verbose; Verbose = 1; message("Option %s used as abbreviation for %s", val, o->o_name); Verbose = oldVerbose; } opt = o->o_code; val = p; } else { for (o = OptionTab; o->o_name != NULL; o++) { if (o->o_code == opt) break; } if (o->o_name == NULL) { syserr("readcf: unknown option name 0x%x", opt & 0xff); return; } subopt = NULL; } if (subopt != NULL && !bitset(OI_SUBOPT, o->o_flags)) { if (tTd(37, 1)) sm_dprintf("setoption: %s does not support suboptions, ignoring .%s\n", OPTNAME, subopt); subopt = NULL; } if (tTd(37, 1)) { sm_dprintf(isascii(opt) && isprint(opt) ? "setoption %s (%c)%s%s=" : "setoption %s (0x%x)%s%s=", OPTNAME, opt, subopt == NULL ? "" : ".", subopt == NULL ? "" : subopt); xputs(sm_debug_file(), val); } /* ** See if this option is preset for us. */ if (!sticky && bitnset(opt, StickyOpt)) { if (tTd(37, 1)) sm_dprintf(" (ignored)\n"); return; } /* ** Check to see if this option can be specified by this user. */ if (!safe && RealUid == 0) safe = true; if (!safe && !bitset(OI_SAFE, o->o_flags)) { if (opt != 'M' || (val[0] != 'r' && val[0] != 's')) { int dp; if (tTd(37, 1)) sm_dprintf(" (unsafe)"); dp = drop_privileges(true); setstat(dp); } } if (tTd(37, 1)) sm_dprintf("\n"); switch (opt & 0xff) { case '7': /* force seven-bit input */ SevenBitInput = atobool(val); break; case '8': /* handling of 8-bit input */ #if MIME8TO7 switch (*val) { case 'p': /* pass 8 bit, convert MIME */ MimeMode = MM_CVTMIME|MM_PASS8BIT; break; case 'm': /* convert 8-bit, convert MIME */ MimeMode = MM_CVTMIME|MM_MIME8BIT; break; case 's': /* strict adherence */ MimeMode = MM_CVTMIME; break; # if 0 case 'r': /* reject 8-bit, don't convert MIME */ MimeMode = 0; break; case 'j': /* "just send 8" */ MimeMode = MM_PASS8BIT; break; case 'a': /* encode 8 bit if available */ MimeMode = MM_MIME8BIT|MM_PASS8BIT|MM_CVTMIME; break; case 'c': /* convert 8 bit to MIME, never 7 bit */ MimeMode = MM_MIME8BIT; break; # endif /* 0 */ default: syserr("Unknown 8-bit mode %c", *val); finis(false, true, EX_USAGE); } #else /* MIME8TO7 */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires MIME8TO7 support\n", OPTNAME); #endif /* MIME8TO7 */ break; case 'A': /* set default alias file */ if (val[0] == '\0') { char *al; SET_OPT_DEFAULT(al, "aliases"); setalias(al); } else setalias(val); break; case 'a': /* look N minutes for "@:@" in alias file */ if (val[0] == '\0') SafeAlias = 5 MINUTES; else SafeAlias = convtime(val, 'm'); break; case 'B': /* substitution for blank character */ SpaceSub = val[0]; if (SpaceSub == '\0') SpaceSub = ' '; break; case 'b': /* min blocks free on queue fs/max msg size */ p = strchr(val, '/'); if (p != NULL) { *p++ = '\0'; MaxMessageSize = atol(p); } MinBlocksFree = atol(val); break; case 'c': /* don't connect to "expensive" mailers */ NoConnect = atobool(val); break; case 'C': /* checkpoint every N addresses */ if (safe || CheckpointInterval > atoi(val)) CheckpointInterval = atoi(val); break; case 'd': /* delivery mode */ switch (*val) { case '\0': set_delivery_mode(SM_DELIVER, e); break; case SM_QUEUE: /* queue only */ case SM_DEFER: /* queue only and defer map lookups */ case SM_DELIVER: /* do everything */ case SM_FORK: /* fork after verification */ #if _FFR_DM_ONE /* deliver first TA in background, then queue */ case SM_DM_ONE: #endif /* _FFR_DM_ONE */ set_delivery_mode(*val, e); break; default: syserr("Unknown delivery mode %c", *val); finis(false, true, EX_USAGE); } break; case 'E': /* error message header/header file */ if (*val != '\0') ErrMsgFile = newstr(val); break; case 'e': /* set error processing mode */ switch (*val) { case EM_QUIET: /* be silent about it */ case EM_MAIL: /* mail back */ case EM_BERKNET: /* do berknet error processing */ case EM_WRITE: /* write back (or mail) */ case EM_PRINT: /* print errors normally (default) */ e->e_errormode = *val; break; } break; case 'F': /* file mode */ FileMode = atooct(val) & 0777; break; case 'f': /* save Unix-style From lines on front */ SaveFrom = atobool(val); break; case 'G': /* match recipients against GECOS field */ MatchGecos = atobool(val); break; case 'g': /* default gid */ g_opt: if (isascii(*val) && isdigit(*val)) DefGid = atoi(val); else { register struct group *gr; DefGid = -1; gr = getgrnam(val); if (gr == NULL) syserr("readcf: option %c: unknown group %s", opt, val); else DefGid = gr->gr_gid; } break; case 'H': /* help file */ if (val[0] == '\0') { SET_OPT_DEFAULT(HelpFile, "helpfile"); } else { CANONIFY(val); HelpFile = newstr(val); } break; case 'h': /* maximum hop count */ MaxHopCount = atoi(val); break; case 'I': /* use internet domain name server */ #if NAMED_BIND for (p = val; *p != 0; ) { bool clearmode; char *q; struct resolverflags *rfp; while (*p == ' ') p++; if (*p == '\0') break; clearmode = false; if (*p == '-') clearmode = true; else if (*p != '+') p--; p++; q = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; if (sm_strcasecmp(q, "HasWildcardMX") == 0) { HasWildcardMX = !clearmode; continue; } if (sm_strcasecmp(q, "WorkAroundBrokenAAAA") == 0) { WorkAroundBrokenAAAA = !clearmode; continue; } for (rfp = ResolverFlags; rfp->rf_name != NULL; rfp++) { if (sm_strcasecmp(q, rfp->rf_name) == 0) break; } if (rfp->rf_name == NULL) syserr("readcf: I option value %s unrecognized", q); else if (clearmode) _res.options &= ~rfp->rf_bits; else _res.options |= rfp->rf_bits; } if (tTd(8, 2)) sm_dprintf("_res.options = %x, HasWildcardMX = %d\n", (unsigned int) _res.options, HasWildcardMX); #else /* NAMED_BIND */ usrerr("name server (I option) specified but BIND not compiled in"); #endif /* NAMED_BIND */ break; case 'i': /* ignore dot lines in message */ IgnrDot = atobool(val); break; case 'j': /* send errors in MIME (RFC 1341) format */ SendMIMEErrors = atobool(val); break; case 'J': /* .forward search path */ CANONIFY(val); ForwardPath = newstr(val); break; case 'k': /* connection cache size */ MaxMciCache = atoi(val); if (MaxMciCache < 0) MaxMciCache = 0; break; case 'K': /* connection cache timeout */ MciCacheTimeout = convtime(val, 'm'); break; case 'l': /* use Errors-To: header */ UseErrorsTo = atobool(val); break; case 'L': /* log level */ if (safe || LogLevel < atoi(val)) LogLevel = atoi(val); break; case 'M': /* define macro */ sticky = false; mid = macid_parse(val, &ep); if (mid == 0) break; p = newstr(ep); if (!safe) cleanstrcpy(p, p, strlen(p) + 1); macdefine(&CurEnv->e_macro, A_TEMP, mid, p); break; case 'm': /* send to me too */ MeToo = atobool(val); break; case 'n': /* validate RHS in newaliases */ CheckAliases = atobool(val); break; /* 'N' available -- was "net name" */ case 'O': /* daemon options */ if (!setdaemonoptions(val)) syserr("too many daemons defined (%d max)", MAXDAEMONS); break; case 'o': /* assume old style headers */ if (atobool(val)) CurEnv->e_flags |= EF_OLDSTYLE; else CurEnv->e_flags &= ~EF_OLDSTYLE; break; case 'p': /* select privacy level */ p = val; for (;;) { register struct prival *pv; extern struct prival PrivacyValues[]; while (isascii(*p) && (isspace(*p) || ispunct(*p))) p++; if (*p == '\0') break; val = p; while (isascii(*p) && isalnum(*p)) p++; if (*p != '\0') *p++ = '\0'; for (pv = PrivacyValues; pv->pv_name != NULL; pv++) { if (sm_strcasecmp(val, pv->pv_name) == 0) break; } if (pv->pv_name == NULL) syserr("readcf: Op line: %s unrecognized", val); else PrivacyFlags |= pv->pv_flag; } sticky = false; break; case 'P': /* postmaster copy address for returned mail */ PostMasterCopy = newstr(val); break; case 'q': /* slope of queue only function */ QueueFactor = atoi(val); break; case 'Q': /* queue directory */ if (val[0] == '\0') { QueueDir = "mqueue"; } else { QueueDir = newstr(val); } if (RealUid != 0 && !safe) Warn_Q_option = true; break; case 'R': /* don't prune routes */ DontPruneRoutes = atobool(val); break; case 'r': /* read timeout */ if (subopt == NULL) inittimeouts(val, sticky); else settimeout(subopt, val, sticky); break; case 'S': /* status file */ if (val[0] == '\0') { SET_OPT_DEFAULT(StatFile, "statistics"); } else { CANONIFY(val); StatFile = newstr(val); } break; case 's': /* be super safe, even if expensive */ if (tolower(*val) == 'i') SuperSafe = SAFE_INTERACTIVE; else if (tolower(*val) == 'p') #if MILTER SuperSafe = SAFE_REALLY_POSTMILTER; #else /* MILTER */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: SuperSafe=PostMilter requires Milter support (-DMILTER)\n"); #endif /* MILTER */ else SuperSafe = atobool(val) ? SAFE_REALLY : SAFE_NO; break; case 'T': /* queue timeout */ p = strchr(val, '/'); if (p != NULL) { *p++ = '\0'; settimeout("queuewarn", p, sticky); } settimeout("queuereturn", val, sticky); break; case 't': /* time zone name */ TimeZoneSpec = newstr(val); break; case 'U': /* location of user database */ UdbSpec = newstr(val); break; case 'u': /* set default uid */ for (p = val; *p != '\0'; p++) { # if _FFR_DOTTED_USERNAMES if (*p == '/' || *p == ':') # else /* _FFR_DOTTED_USERNAMES */ if (*p == '.' || *p == '/' || *p == ':') # endif /* _FFR_DOTTED_USERNAMES */ { *p++ = '\0'; break; } } if (isascii(*val) && isdigit(*val)) { DefUid = atoi(val); setdefuser(); } else { register struct passwd *pw; DefUid = -1; pw = sm_getpwnam(val); if (pw == NULL) { syserr("readcf: option u: unknown user %s", val); break; } else { DefUid = pw->pw_uid; DefGid = pw->pw_gid; DefUser = newstr(pw->pw_name); } } # ifdef UID_MAX if (DefUid > UID_MAX) { syserr("readcf: option u: uid value (%ld) > UID_MAX (%ld); ignored", (long)DefUid, (long)UID_MAX); break; } # endif /* UID_MAX */ /* handle the group if it is there */ if (*p == '\0') break; val = p; goto g_opt; case 'V': /* fallback MX host */ if (val[0] != '\0') FallbackMX = newstr(val); break; case 'v': /* run in verbose mode */ Verbose = atobool(val) ? 1 : 0; break; case 'w': /* if we are best MX, try host directly */ TryNullMXList = atobool(val); break; /* 'W' available -- was wizard password */ case 'x': /* load avg at which to auto-queue msgs */ QueueLA = atoi(val); break; case 'X': /* load avg at which to auto-reject connections */ RefuseLA = atoi(val); break; case O_DELAY_LA: /* load avg at which to delay connections */ DelayLA = atoi(val); break; case 'y': /* work recipient factor */ WkRecipFact = atoi(val); break; case 'Y': /* fork jobs during queue runs */ ForkQueueRuns = atobool(val); break; case 'z': /* work message class factor */ WkClassFact = atoi(val); break; case 'Z': /* work time factor */ WkTimeFact = atoi(val); break; #if _FFR_QUEUE_GROUP_SORTORDER /* coordinate this with makequeue() */ #endif /* _FFR_QUEUE_GROUP_SORTORDER */ case O_QUEUESORTORD: /* queue sorting order */ switch (*val) { case 'f': /* File Name */ case 'F': QueueSortOrder = QSO_BYFILENAME; break; case 'h': /* Host first */ case 'H': QueueSortOrder = QSO_BYHOST; break; case 'm': /* Modification time */ case 'M': QueueSortOrder = QSO_BYMODTIME; break; case 'p': /* Priority order */ case 'P': QueueSortOrder = QSO_BYPRIORITY; break; case 't': /* Submission time */ case 'T': QueueSortOrder = QSO_BYTIME; break; case 'r': /* Random */ case 'R': QueueSortOrder = QSO_RANDOM; break; #if _FFR_RHS case 's': /* Shuffled host name */ case 'S': QueueSortOrder = QSO_BYSHUFFLE; break; #endif /* _FFR_RHS */ case 'n': /* none */ case 'N': QueueSortOrder = QSO_NONE; break; default: syserr("Invalid queue sort order \"%s\"", val); } break; case O_HOSTSFILE: /* pathname of /etc/hosts file */ CANONIFY(val); HostsFile = newstr(val); break; case O_MQA: /* minimum queue age between deliveries */ MinQueueAge = convtime(val, 'm'); break; #if _FFR_EXPDELAY case O_MAX_QUEUE_AGE: MaxQueueAge = convtime(val, 'm'); break; #endif /* _FFR_EXPDELAY */ case O_DEFCHARSET: /* default character set for mimefying */ DefaultCharSet = newstr(denlstring(val, true, true)); break; case O_SSFILE: /* service switch file */ CANONIFY(val); ServiceSwitchFile = newstr(val); break; case O_DIALDELAY: /* delay for dial-on-demand operation */ DialDelay = convtime(val, 's'); break; case O_NORCPTACTION: /* what to do if no recipient */ if (sm_strcasecmp(val, "none") == 0) NoRecipientAction = NRA_NO_ACTION; else if (sm_strcasecmp(val, "add-to") == 0) NoRecipientAction = NRA_ADD_TO; else if (sm_strcasecmp(val, "add-apparently-to") == 0) NoRecipientAction = NRA_ADD_APPARENTLY_TO; else if (sm_strcasecmp(val, "add-bcc") == 0) NoRecipientAction = NRA_ADD_BCC; else if (sm_strcasecmp(val, "add-to-undisclosed") == 0) NoRecipientAction = NRA_ADD_TO_UNDISCLOSED; else syserr("Invalid NoRecipientAction: %s", val); break; case O_SAFEFILEENV: /* chroot() environ for writing to files */ if (*val == '\0') break; /* strip trailing slashes */ p = val + strlen(val) - 1; while (p >= val && *p == '/') *p-- = '\0'; if (*val == '\0') break; SafeFileEnv = newstr(val); break; case O_MAXMSGSIZE: /* maximum message size */ MaxMessageSize = atol(val); break; case O_COLONOKINADDR: /* old style handling of colon addresses */ ColonOkInAddr = atobool(val); break; case O_MAXQUEUERUN: /* max # of jobs in a single queue run */ MaxQueueRun = atoi(val); break; case O_MAXCHILDREN: /* max # of children of daemon */ MaxChildren = atoi(val); break; case O_MAXQUEUECHILDREN: /* max # of children of daemon */ MaxQueueChildren = atoi(val); break; case O_MAXRUNNERSPERQUEUE: /* max # runners in a queue group */ MaxRunnersPerQueue = atoi(val); break; case O_NICEQUEUERUN: /* nice queue runs */ #if !HASNICE (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: NiceQueueRun set on system that doesn't support nice()\n"); #endif /* !HASNICE */ /* XXX do we want to check the range? > 0 ? */ NiceQueueRun = atoi(val); break; case O_SHMKEY: /* shared memory key */ #if SM_CONF_SHM ShmKey = atol(val); #else /* SM_CONF_SHM */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires shared memory support (-DSM_CONF_SHM)\n", OPTNAME); #endif /* SM_CONF_SHM */ break; case O_SHMKEYFILE: /* shared memory key file */ #if SM_CONF_SHM SET_STRING_EXP(ShmKeyFile); #else /* SM_CONF_SHM */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires shared memory support (-DSM_CONF_SHM)\n", OPTNAME); break; #endif /* SM_CONF_SHM */ #if _FFR_MAX_FORWARD_ENTRIES case O_MAXFORWARD: /* max # of forward entries */ MaxForwardEntries = atoi(val); break; #endif /* _FFR_MAX_FORWARD_ENTRIES */ case O_KEEPCNAMES: /* don't expand CNAME records */ DontExpandCnames = atobool(val); break; case O_MUSTQUOTE: /* must quote these characters in phrases */ (void) sm_strlcpy(buf, "@,;:\\()[]", sizeof(buf)); if (strlen(val) < sizeof(buf) - 10) (void) sm_strlcat(buf, val, sizeof(buf)); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: MustQuoteChars too long, ignored.\n"); MustQuoteChars = newstr(buf); break; case O_SMTPGREETING: /* SMTP greeting message (old $e macro) */ SmtpGreeting = newstr(munchstring(val, NULL, '\0')); break; case O_UNIXFROM: /* UNIX From_ line (old $l macro) */ UnixFromLine = newstr(munchstring(val, NULL, '\0')); break; case O_OPCHARS: /* operator characters (old $o macro) */ if (OperatorChars != NULL) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: OperatorChars is being redefined.\n It should only be set before ruleset definitions.\n"); OperatorChars = newstr(munchstring(val, NULL, '\0')); break; case O_DONTINITGRPS: /* don't call initgroups(3) */ DontInitGroups = atobool(val); break; case O_SLFH: /* make sure from fits on one line */ SingleLineFromHeader = atobool(val); break; case O_ABH: /* allow HELO commands with syntax errors */ AllowBogusHELO = atobool(val); break; case O_CONNTHROT: /* connection rate throttle */ ConnRateThrottle = atoi(val); break; case O_UGW: /* group writable files are unsafe */ if (!atobool(val)) { setbitn(DBS_GROUPWRITABLEFORWARDFILESAFE, DontBlameSendmail); setbitn(DBS_GROUPWRITABLEINCLUDEFILESAFE, DontBlameSendmail); } break; case O_DBLBOUNCE: /* address to which to send double bounces */ DoubleBounceAddr = newstr(val); break; case O_HSDIR: /* persistent host status directory */ if (val[0] != '\0') { CANONIFY(val); HostStatDir = newstr(val); } break; case O_SINGTHREAD: /* single thread deliveries (requires hsdir) */ SingleThreadDelivery = atobool(val); break; case O_RUNASUSER: /* run bulk of code as this user */ for (p = val; *p != '\0'; p++) { # if _FFR_DOTTED_USERNAMES if (*p == '/' || *p == ':') # else /* _FFR_DOTTED_USERNAMES */ if (*p == '.' || *p == '/' || *p == ':') # endif /* _FFR_DOTTED_USERNAMES */ { *p++ = '\0'; break; } } if (isascii(*val) && isdigit(*val)) { if (can_setuid) RunAsUid = atoi(val); } else { register struct passwd *pw; pw = sm_getpwnam(val); if (pw == NULL) { syserr("readcf: option RunAsUser: unknown user %s", val); break; } else if (can_setuid) { if (*p == '\0') RunAsUserName = newstr(val); RunAsUid = pw->pw_uid; RunAsGid = pw->pw_gid; } else if (EffGid == pw->pw_gid) RunAsGid = pw->pw_gid; else if (UseMSP && *p == '\0') (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: RunAsUser for MSP ignored, check group ids (egid=%d, want=%d)\n", (int) EffGid, (int) pw->pw_gid); } # ifdef UID_MAX if (RunAsUid > UID_MAX) { syserr("readcf: option RunAsUser: uid value (%ld) > UID_MAX (%ld); ignored", (long) RunAsUid, (long) UID_MAX); break; } # endif /* UID_MAX */ if (*p != '\0') { if (isascii(*p) && isdigit(*p)) { gid_t runasgid; runasgid = (gid_t) atoi(p); if (can_setuid || EffGid == runasgid) RunAsGid = runasgid; else if (UseMSP) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: RunAsUser for MSP ignored, check group ids (egid=%d, want=%d)\n", (int) EffGid, (int) runasgid); } else { register struct group *gr; gr = getgrnam(p); if (gr == NULL) syserr("readcf: option RunAsUser: unknown group %s", p); else if (can_setuid || EffGid == gr->gr_gid) RunAsGid = gr->gr_gid; else if (UseMSP) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: RunAsUser for MSP ignored, check group ids (egid=%d, want=%d)\n", (int) EffGid, (int) gr->gr_gid); } } if (tTd(47, 5)) sm_dprintf("readcf: RunAsUser = %d:%d\n", (int) RunAsUid, (int) RunAsGid); break; case O_DSN_RRT: RrtImpliesDsn = atobool(val); break; case O_PIDFILE: PSTRSET(PidFile, val); break; case O_DONTBLAMESENDMAIL: p = val; for (;;) { register struct dbsval *dbs; extern struct dbsval DontBlameSendmailValues[]; while (isascii(*p) && (isspace(*p) || ispunct(*p))) p++; if (*p == '\0') break; val = p; while (isascii(*p) && isalnum(*p)) p++; if (*p != '\0') *p++ = '\0'; for (dbs = DontBlameSendmailValues; dbs->dbs_name != NULL; dbs++) { if (sm_strcasecmp(val, dbs->dbs_name) == 0) break; } if (dbs->dbs_name == NULL) syserr("readcf: DontBlameSendmail option: %s unrecognized", val); else if (dbs->dbs_flag == DBS_SAFE) clrbitmap(DontBlameSendmail); else setbitn(dbs->dbs_flag, DontBlameSendmail); } sticky = false; break; case O_DPI: if (sm_strcasecmp(val, "loopback") == 0) DontProbeInterfaces = DPI_SKIPLOOPBACK; else if (atobool(val)) DontProbeInterfaces = DPI_PROBENONE; else DontProbeInterfaces = DPI_PROBEALL; break; case O_MAXRCPT: MaxRcptPerMsg = atoi(val); break; case O_RCPTTHROT: BadRcptThrottle = atoi(val); break; #if _FFR_RCPTTHROTDELAY case O_RCPTTHROTDELAY: BadRcptThrottleDelay = atoi(val); break; #endif /* _FFR_RCPTTHROTDELAY */ case O_DEADLETTER: CANONIFY(val); PSTRSET(DeadLetterDrop, val); break; #if _FFR_DONTLOCKFILESFORREAD_OPTION case O_DONTLOCK: DontLockReadFiles = atobool(val); break; #endif /* _FFR_DONTLOCKFILESFORREAD_OPTION */ case O_MAXALIASRCSN: MaxAliasRecursion = atoi(val); break; case O_CNCTONLYTO: /* XXX should probably use gethostbyname */ #if NETINET || NETINET6 ConnectOnlyTo.sa.sa_family = AF_UNSPEC; # if NETINET6 if (anynet_pton(AF_INET6, val, &ConnectOnlyTo.sin6.sin6_addr) == 1) ConnectOnlyTo.sa.sa_family = AF_INET6; else # endif /* NETINET6 */ # if NETINET { ConnectOnlyTo.sin.sin_addr.s_addr = inet_addr(val); if (ConnectOnlyTo.sin.sin_addr.s_addr != INADDR_NONE) ConnectOnlyTo.sa.sa_family = AF_INET; } # endif /* NETINET */ if (ConnectOnlyTo.sa.sa_family == AF_UNSPEC) { syserr("readcf: option ConnectOnlyTo: invalid IP address %s", val); break; } #endif /* NETINET || NETINET6 */ break; case O_TRUSTUSER: # if !HASFCHOWN && !defined(_FFR_DROP_TRUSTUSER_WARNING) if (!UseMSP) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "readcf: option TrustedUser may cause problems on systems\n which do not support fchown() if UseMSP is not set.\n"); # endif /* !HASFCHOWN && !defined(_FFR_DROP_TRUSTUSER_WARNING) */ if (isascii(*val) && isdigit(*val)) TrustedUid = atoi(val); else { register struct passwd *pw; TrustedUid = 0; pw = sm_getpwnam(val); if (pw == NULL) { syserr("readcf: option TrustedUser: unknown user %s", val); break; } else TrustedUid = pw->pw_uid; } # ifdef UID_MAX if (TrustedUid > UID_MAX) { syserr("readcf: option TrustedUser: uid value (%ld) > UID_MAX (%ld)", (long) TrustedUid, (long) UID_MAX); TrustedUid = 0; } # endif /* UID_MAX */ break; case O_MAXMIMEHDRLEN: p = strchr(val, '/'); if (p != NULL) *p++ = '\0'; MaxMimeHeaderLength = atoi(val); if (p != NULL && *p != '\0') MaxMimeFieldLength = atoi(p); else MaxMimeFieldLength = MaxMimeHeaderLength / 2; if (MaxMimeHeaderLength <= 0) MaxMimeHeaderLength = 0; else if (MaxMimeHeaderLength < 128) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: MaxMimeHeaderLength: header length limit set lower than 128\n"); if (MaxMimeFieldLength <= 0) MaxMimeFieldLength = 0; else if (MaxMimeFieldLength < 40) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: MaxMimeHeaderLength: field length limit set lower than 40\n"); /* ** Headers field values now include leading space, so let's ** adjust the values to be "backward compatible". */ if (MaxMimeHeaderLength > 0) MaxMimeHeaderLength++; if (MaxMimeFieldLength > 0) MaxMimeFieldLength++; break; case O_CONTROLSOCKET: PSTRSET(ControlSocketName, val); break; case O_MAXHDRSLEN: MaxHeadersLength = atoi(val); if (MaxHeadersLength > 0 && MaxHeadersLength < (MAXHDRSLEN / 2)) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: MaxHeadersLength: headers length limit set lower than %d\n", (MAXHDRSLEN / 2)); break; case O_PROCTITLEPREFIX: PSTRSET(ProcTitlePrefix, val); break; #if SASL case O_SASLINFO: # if _FFR_ALLOW_SASLINFO /* ** Allow users to select their own authinfo file ** under certain circumstances, otherwise just ignore ** the option. If the option isn't ignored, several ** commands don't work very well, e.g., mailq. ** However, this is not a "perfect" solution. ** If mail is queued, the authentication info ** will not be used in subsequent delivery attempts. ** If we really want to support this, then it has ** to be stored in the queue file. */ if (!bitset(SUBMIT_MSA, SubmitMode) && RealUid != 0 && RunAsUid != RealUid) break; # endif /* _FFR_ALLOW_SASLINFO */ PSTRSET(SASLInfo, val); break; case O_SASLMECH: if (AuthMechanisms != NULL) sm_free(AuthMechanisms); /* XXX */ if (*val != '\0') AuthMechanisms = newstr(val); else AuthMechanisms = NULL; break; case O_SASLREALM: if (AuthRealm != NULL) sm_free(AuthRealm); if (*val != '\0') AuthRealm = newstr(val); else AuthRealm = NULL; break; case O_SASLOPTS: while (val != NULL && *val != '\0') { switch (*val) { case 'A': SASLOpts |= SASL_AUTH_AUTH; break; case 'a': SASLOpts |= SASL_SEC_NOACTIVE; break; case 'c': SASLOpts |= SASL_SEC_PASS_CREDENTIALS; break; case 'd': SASLOpts |= SASL_SEC_NODICTIONARY; break; case 'f': SASLOpts |= SASL_SEC_FORWARD_SECRECY; break; # if SASL >= 20101 case 'm': SASLOpts |= SASL_SEC_MUTUAL_AUTH; break; # endif /* SASL >= 20101 */ case 'p': SASLOpts |= SASL_SEC_NOPLAINTEXT; break; case 'y': SASLOpts |= SASL_SEC_NOANONYMOUS; break; case ' ': /* ignore */ case '\t': /* ignore */ case ',': /* ignore */ break; default: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s unknown parameter '%c'\n", OPTNAME, (isascii(*val) && isprint(*val)) ? *val : '?'); break; } ++val; val = strpbrk(val, ", \t"); if (val != NULL) ++val; } break; case O_SASLBITS: MaxSLBits = atoi(val); break; #else /* SASL */ case O_SASLINFO: case O_SASLMECH: case O_SASLREALM: case O_SASLOPTS: case O_SASLBITS: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires SASL support (-DSASL)\n", OPTNAME); break; #endif /* SASL */ #if STARTTLS case O_SRVCERTFILE: SET_STRING_EXP(SrvCertFile); case O_SRVKEYFILE: SET_STRING_EXP(SrvKeyFile); case O_CLTCERTFILE: SET_STRING_EXP(CltCertFile); case O_CLTKEYFILE: SET_STRING_EXP(CltKeyFile); case O_CACERTFILE: SET_STRING_EXP(CACertFile); case O_CACERTPATH: SET_STRING_EXP(CACertPath); case O_DHPARAMS: SET_STRING_EXP(DHParams); # if _FFR_TLS_1 case O_DHPARAMS5: SET_STRING_EXP(DHParams5); case O_CIPHERLIST: SET_STRING_EXP(CipherList); case O_SRV_SSL_OPTIONS: pssloptions = &Srv_SSL_Options; case O_CLT_SSL_OPTIONS: if (pssloptions == NULL) pssloptions = &Clt_SSL_Options; for (p = val; *p != 0; ) { bool clearmode; char *q; struct ssl_options *sslopts; while (*p == ' ') p++; if (*p == '\0') break; clearmode = false; if (*p == '-' || *p == '+') clearmode = *p++ == '-'; q = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; for (sslopts = SSL_Option; sslopts->sslopt_name != NULL; sslopts++) { if (sm_strcasecmp(q, sslopts->sslopt_name) == 0) break; } if (sslopts->sslopt_name == NULL) { errno = 0; syserr("readcf: %s option value %s unrecognized", o->o_name, q); } else if (clearmode) *pssloptions &= ~sslopts->sslopt_bits; else *pssloptions |= sslopts->sslopt_bits; } pssloptions = NULL; break; # endif /* _FFR_TLS_1 */ case O_CRLFILE: # if OPENSSL_VERSION_NUMBER > 0x00907000L SET_STRING_EXP(CRLFile); # else /* OPENSSL_VERSION_NUMBER > 0x00907000L */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires at least OpenSSL 0.9.7\n", OPTNAME); break; # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ # if _FFR_CRLPATH case O_CRLPATH: # if OPENSSL_VERSION_NUMBER > 0x00907000L SET_STRING_EXP(CRLPath); # else /* OPENSSL_VERSION_NUMBER > 0x00907000L */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires at least OpenSSL 0.9.7\n", OPTNAME); break; # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ # endif /* _FFR_CRLPATH */ /* ** XXX How about options per daemon/client instead of globally? ** This doesn't work well for some options, e.g., no server cert, ** but fine for others. ** ** XXX Some people may want different certs per server. ** ** See also srvfeatures() */ case O_TLS_SRV_OPTS: while (val != NULL && *val != '\0') { switch (*val) { case 'V': TLS_Srv_Opts |= TLS_I_NO_VRFY; break; # if _FFR_TLS_1 /* ** Server without a cert? That works only if ** AnonDH is enabled as cipher, which is not in the ** default list. Hence the CipherList option must ** be available. Moreover: which clients support this ** besides sendmail with this setting? */ case 'C': TLS_Srv_Opts &= ~TLS_I_SRV_CERT; break; # endif /* _FFR_TLS_1 */ case ' ': /* ignore */ case '\t': /* ignore */ case ',': /* ignore */ break; default: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s unknown parameter '%c'\n", OPTNAME, (isascii(*val) && isprint(*val)) ? *val : '?'); break; } ++val; val = strpbrk(val, ", \t"); if (val != NULL) ++val; } break; case O_RANDFILE: PSTRSET(RandFile, val); break; #else /* STARTTLS */ case O_SRVCERTFILE: case O_SRVKEYFILE: case O_CLTCERTFILE: case O_CLTKEYFILE: case O_CACERTFILE: case O_CACERTPATH: case O_DHPARAMS: # if _FFR_TLS_1 case O_DHPARAMS5: case O_CIPHERLIST: # endif /* _FFR_TLS_1 */ case O_CRLFILE: # if _FFR_CRLPATH case O_CRLPATH: # endif /* _FFR_CRLPATH */ case O_RANDFILE: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires TLS support\n", OPTNAME); break; #endif /* STARTTLS */ +#if STARTTLS && _FFR_FIPSMODE + case O_FIPSMODE: + FipsMode = atobool(val); + break; +#endif /* STARTTLS && _FFR_FIPSMODE */ case O_CLIENTPORT: setclientoptions(val); break; case O_DF_BUFSIZE: DataFileBufferSize = atoi(val); break; case O_XF_BUFSIZE: XscriptFileBufferSize = atoi(val); break; case O_LDAPDEFAULTSPEC: #if LDAPMAP ldapmap_set_defaults(val); #else /* LDAPMAP */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires LDAP support (-DLDAPMAP)\n", OPTNAME); #endif /* LDAPMAP */ break; case O_INPUTMILTER: #if MILTER InputFilterList = newstr(val); #else /* MILTER */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires Milter support (-DMILTER)\n", OPTNAME); #endif /* MILTER */ break; case O_MILTER: #if MILTER milter_set_option(subopt, val, sticky); #else /* MILTER */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires Milter support (-DMILTER)\n", OPTNAME); #endif /* MILTER */ break; case O_QUEUE_FILE_MODE: /* queue file mode */ QueueFileMode = atooct(val) & 0777; break; case O_DLVR_MIN: /* deliver by minimum time */ DeliverByMin = convtime(val, 's'); break; /* modifiers {daemon_flags} for direct submissions */ case O_DIRECTSUBMODIFIERS: { BITMAP256 m; /* ignored */ extern ENVELOPE BlankEnvelope; macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{daemon_flags}"), getmodifiers(val, m)); } break; case O_FASTSPLIT: FastSplit = atoi(val); break; case O_MBDB: Mbdb = newstr(val); break; case O_MSQ: UseMSP = atobool(val); break; case O_SOFTBOUNCE: SoftBounce = atobool(val); break; case O_REJECTLOGINTERVAL: /* time btwn log msgs while refusing */ RejectLogInterval = convtime(val, 'h'); break; case O_REQUIRES_DIR_FSYNC: #if REQUIRES_DIR_FSYNC RequiresDirfsync = atobool(val); #else /* REQUIRES_DIR_FSYNC */ /* silently ignored... required for cf file option */ #endif /* REQUIRES_DIR_FSYNC */ break; case O_CONNECTION_RATE_WINDOW_SIZE: ConnectionRateWindowSize = convtime(val, 's'); break; case O_FALLBACKSMARTHOST: /* fallback smart host */ if (val[0] != '\0') FallbackSmartHost = newstr(val); break; case O_HELONAME: HeloName = newstr(val); break; #if _FFR_MEMSTAT case O_REFUSELOWMEM: RefuseLowMem = atoi(val); break; case O_QUEUELOWMEM: QueueLowMem = atoi(val); break; case O_MEMRESOURCE: MemoryResource = newstr(val); break; #endif /* _FFR_MEMSTAT */ case O_MAXNOOPCOMMANDS: MaxNOOPCommands = atoi(val); break; #if _FFR_MSG_ACCEPT case O_MSG_ACCEPT: MessageAccept = newstr(val); break; #endif /* _FFR_MSG_ACCEPT */ #if _FFR_QUEUE_RUN_PARANOIA case O_CHK_Q_RUNNERS: CheckQueueRunners = atoi(val); break; #endif /* _FFR_QUEUE_RUN_PARANOIA */ #if _FFR_EIGHT_BIT_ADDR_OK case O_EIGHT_BIT_ADDR_OK: EightBitAddrOK = atobool(val); break; #endif /* _FFR_EIGHT_BIT_ADDR_OK */ #if _FFR_ADDR_TYPE_MODES case O_ADDR_TYPE_MODES: AddrTypeModes = atobool(val); break; #endif /* _FFR_ADDR_TYPE_MODES */ #if _FFR_BADRCPT_SHUTDOWN case O_RCPTSHUTD: BadRcptShutdown = atoi(val); break; case O_RCPTSHUTDG: BadRcptShutdownGood = atoi(val); break; #endif /* _FFR_BADRCPT_SHUTDOWN */ + +#if _FFR_REJECT_NUL_BYTE + case O_REJECTNUL: + RejectNUL = atobool(val); + break; +#endif /* _FFR_REJECT_NUL_BYTE */ default: if (tTd(37, 1)) { if (isascii(opt) && isprint(opt)) sm_dprintf("Warning: option %c unknown\n", opt); else sm_dprintf("Warning: option 0x%x unknown\n", opt); } break; } /* ** Options with suboptions are responsible for taking care ** of sticky-ness (e.g., that a command line setting is kept ** when reading in the sendmail.cf file). This has to be done ** when the suboptions are parsed since each suboption must be ** sticky, not the root option. */ if (sticky && !bitset(OI_SUBOPT, o->o_flags)) setbitn(opt, StickyOpt); } /* ** SETCLASS -- set a string into a class ** ** Parameters: ** class -- the class to put the string in. ** str -- the string to enter ** ** Returns: ** none. ** ** Side Effects: ** puts the word into the symbol table. */ void setclass(class, str) int class; char *str; { register STAB *s; if ((str[0] & 0377) == MATCHCLASS) { int mid; str++; mid = macid(str); if (mid == 0) return; if (tTd(37, 8)) sm_dprintf("setclass(%s, $=%s)\n", macname(class), macname(mid)); copy_class(mid, class); } else { if (tTd(37, 8)) sm_dprintf("setclass(%s, %s)\n", macname(class), str); s = stab(str, ST_CLASS, ST_ENTER); setbitn(bitidx(class), s->s_class); } } /* ** MAKEMAPENTRY -- create a map entry ** ** Parameters: ** line -- the config file line ** ** Returns: ** A pointer to the map that has been created. ** NULL if there was a syntax error. ** ** Side Effects: ** Enters the map into the dictionary. */ MAP * makemapentry(line) char *line; { register char *p; char *mapname; char *classname; register STAB *s; STAB *class; for (p = line; isascii(*p) && isspace(*p); p++) continue; if (!(isascii(*p) && isalnum(*p))) { syserr("readcf: config K line: no map name"); return NULL; } mapname = p; while ((isascii(*++p) && isalnum(*p)) || *p == '_' || *p == '.') continue; if (*p != '\0') *p++ = '\0'; while (isascii(*p) && isspace(*p)) p++; if (!(isascii(*p) && isalnum(*p))) { syserr("readcf: config K line, map %s: no map class", mapname); return NULL; } classname = p; while (isascii(*++p) && isalnum(*p)) continue; if (*p != '\0') *p++ = '\0'; while (isascii(*p) && isspace(*p)) p++; /* look up the class */ class = stab(classname, ST_MAPCLASS, ST_FIND); if (class == NULL) { syserr("readcf: map %s: class %s not available", mapname, classname); return NULL; } /* enter the map */ s = stab(mapname, ST_MAP, ST_ENTER); s->s_map.map_class = &class->s_mapclass; s->s_map.map_mname = newstr(mapname); if (class->s_mapclass.map_parse(&s->s_map, p)) s->s_map.map_mflags |= MF_VALID; if (tTd(37, 5)) { sm_dprintf("map %s, class %s, flags %lx, file %s,\n", s->s_map.map_mname, s->s_map.map_class->map_cname, s->s_map.map_mflags, s->s_map.map_file); sm_dprintf("\tapp %s, domain %s, rebuild %s\n", s->s_map.map_app, s->s_map.map_domain, s->s_map.map_rebuild); } return &s->s_map; } /* ** STRTORWSET -- convert string to rewriting set number ** ** Parameters: ** p -- the pointer to the string to decode. ** endp -- if set, store the trailing delimiter here. ** stabmode -- ST_ENTER to create this entry, ST_FIND if ** it must already exist. ** ** Returns: ** The appropriate ruleset number. ** -1 if it is not valid (error already printed) */ int strtorwset(p, endp, stabmode) char *p; char **endp; int stabmode; { int ruleset; static int nextruleset = MAXRWSETS; while (isascii(*p) && isspace(*p)) p++; if (!isascii(*p)) { syserr("invalid ruleset name: \"%.20s\"", p); return -1; } if (isdigit(*p)) { ruleset = strtol(p, endp, 10); if (ruleset >= MAXRWSETS / 2 || ruleset < 0) { syserr("bad ruleset %d (%d max)", ruleset, MAXRWSETS / 2); ruleset = -1; } } else { STAB *s; char delim; char *q = NULL; q = p; while (*p != '\0' && isascii(*p) && (isalnum(*p) || *p == '_')) p++; if (q == p || !(isascii(*q) && isalpha(*q))) { /* no valid characters */ syserr("invalid ruleset name: \"%.20s\"", q); return -1; } while (isascii(*p) && isspace(*p)) *p++ = '\0'; delim = *p; if (delim != '\0') *p = '\0'; s = stab(q, ST_RULESET, stabmode); if (delim != '\0') *p = delim; if (s == NULL) return -1; if (stabmode == ST_ENTER && delim == '=') { while (isascii(*++p) && isspace(*p)) continue; if (!(isascii(*p) && isdigit(*p))) { syserr("bad ruleset definition \"%s\" (number required after `=')", q); ruleset = -1; } else { ruleset = strtol(p, endp, 10); if (ruleset >= MAXRWSETS / 2 || ruleset < 0) { syserr("bad ruleset number %d in \"%s\" (%d max)", ruleset, q, MAXRWSETS / 2); ruleset = -1; } } } else { if (endp != NULL) *endp = p; if (s->s_ruleset >= 0) ruleset = s->s_ruleset; else if ((ruleset = --nextruleset) < MAXRWSETS / 2) { syserr("%s: too many named rulesets (%d max)", q, MAXRWSETS / 2); ruleset = -1; } } if (s->s_ruleset >= 0 && ruleset >= 0 && ruleset != s->s_ruleset) { syserr("%s: ruleset changed value (old %d, new %d)", q, s->s_ruleset, ruleset); ruleset = s->s_ruleset; } else if (ruleset >= 0) { s->s_ruleset = ruleset; } if (stabmode == ST_ENTER && ruleset >= 0) { char *h = NULL; if (RuleSetNames[ruleset] != NULL) sm_free(RuleSetNames[ruleset]); /* XXX */ if (delim != '\0' && (h = strchr(q, delim)) != NULL) *h = '\0'; RuleSetNames[ruleset] = newstr(q); if (delim == '/' && h != NULL) *h = delim; /* put back delim */ } } return ruleset; } /* ** SETTIMEOUT -- set an individual timeout ** ** Parameters: ** name -- the name of the timeout. ** val -- the value of the timeout. ** sticky -- if set, don't let other setoptions override ** this value. ** ** Returns: ** none. */ /* set if Timeout sub-option is stuck */ static BITMAP256 StickyTimeoutOpt; static struct timeoutinfo { char *to_name; /* long name of timeout */ unsigned char to_code; /* code for option */ } TimeOutTab[] = { #define TO_INITIAL 0x01 { "initial", TO_INITIAL }, #define TO_MAIL 0x02 { "mail", TO_MAIL }, #define TO_RCPT 0x03 { "rcpt", TO_RCPT }, #define TO_DATAINIT 0x04 { "datainit", TO_DATAINIT }, #define TO_DATABLOCK 0x05 { "datablock", TO_DATABLOCK }, #define TO_DATAFINAL 0x06 { "datafinal", TO_DATAFINAL }, #define TO_COMMAND 0x07 { "command", TO_COMMAND }, #define TO_RSET 0x08 { "rset", TO_RSET }, #define TO_HELO 0x09 { "helo", TO_HELO }, #define TO_QUIT 0x0A { "quit", TO_QUIT }, #define TO_MISC 0x0B { "misc", TO_MISC }, #define TO_IDENT 0x0C { "ident", TO_IDENT }, #define TO_FILEOPEN 0x0D { "fileopen", TO_FILEOPEN }, #define TO_CONNECT 0x0E { "connect", TO_CONNECT }, #define TO_ICONNECT 0x0F { "iconnect", TO_ICONNECT }, #define TO_QUEUEWARN 0x10 { "queuewarn", TO_QUEUEWARN }, { "queuewarn.*", TO_QUEUEWARN }, #define TO_QUEUEWARN_NORMAL 0x11 { "queuewarn.normal", TO_QUEUEWARN_NORMAL }, #define TO_QUEUEWARN_URGENT 0x12 { "queuewarn.urgent", TO_QUEUEWARN_URGENT }, #define TO_QUEUEWARN_NON_URGENT 0x13 { "queuewarn.non-urgent", TO_QUEUEWARN_NON_URGENT }, #define TO_QUEUERETURN 0x14 { "queuereturn", TO_QUEUERETURN }, { "queuereturn.*", TO_QUEUERETURN }, #define TO_QUEUERETURN_NORMAL 0x15 { "queuereturn.normal", TO_QUEUERETURN_NORMAL }, #define TO_QUEUERETURN_URGENT 0x16 { "queuereturn.urgent", TO_QUEUERETURN_URGENT }, #define TO_QUEUERETURN_NON_URGENT 0x17 { "queuereturn.non-urgent", TO_QUEUERETURN_NON_URGENT }, #define TO_HOSTSTATUS 0x18 { "hoststatus", TO_HOSTSTATUS }, #define TO_RESOLVER_RETRANS 0x19 { "resolver.retrans", TO_RESOLVER_RETRANS }, #define TO_RESOLVER_RETRANS_NORMAL 0x1A { "resolver.retrans.normal", TO_RESOLVER_RETRANS_NORMAL }, #define TO_RESOLVER_RETRANS_FIRST 0x1B { "resolver.retrans.first", TO_RESOLVER_RETRANS_FIRST }, #define TO_RESOLVER_RETRY 0x1C { "resolver.retry", TO_RESOLVER_RETRY }, #define TO_RESOLVER_RETRY_NORMAL 0x1D { "resolver.retry.normal", TO_RESOLVER_RETRY_NORMAL }, #define TO_RESOLVER_RETRY_FIRST 0x1E { "resolver.retry.first", TO_RESOLVER_RETRY_FIRST }, #define TO_CONTROL 0x1F { "control", TO_CONTROL }, #define TO_LHLO 0x20 { "lhlo", TO_LHLO }, #define TO_AUTH 0x21 { "auth", TO_AUTH }, #define TO_STARTTLS 0x22 { "starttls", TO_STARTTLS }, #define TO_ACONNECT 0x23 { "aconnect", TO_ACONNECT }, #define TO_QUEUEWARN_DSN 0x24 { "queuewarn.dsn", TO_QUEUEWARN_DSN }, #define TO_QUEUERETURN_DSN 0x25 { "queuereturn.dsn", TO_QUEUERETURN_DSN }, { NULL, 0 }, }; static void settimeout(name, val, sticky) char *name; char *val; bool sticky; { register struct timeoutinfo *to; int i, addopts; time_t toval; if (tTd(37, 2)) sm_dprintf("settimeout(%s = %s)", name, val); for (to = TimeOutTab; to->to_name != NULL; to++) { if (sm_strcasecmp(to->to_name, name) == 0) break; } if (to->to_name == NULL) { errno = 0; /* avoid bogus error text */ syserr("settimeout: invalid timeout %s", name); return; } /* ** See if this option is preset for us. */ if (!sticky && bitnset(to->to_code, StickyTimeoutOpt)) { if (tTd(37, 2)) sm_dprintf(" (ignored)\n"); return; } if (tTd(37, 2)) sm_dprintf("\n"); toval = convtime(val, 'm'); addopts = 0; switch (to->to_code) { case TO_INITIAL: TimeOuts.to_initial = toval; break; case TO_MAIL: TimeOuts.to_mail = toval; break; case TO_RCPT: TimeOuts.to_rcpt = toval; break; case TO_DATAINIT: TimeOuts.to_datainit = toval; break; case TO_DATABLOCK: TimeOuts.to_datablock = toval; break; case TO_DATAFINAL: TimeOuts.to_datafinal = toval; break; case TO_COMMAND: TimeOuts.to_nextcommand = toval; break; case TO_RSET: TimeOuts.to_rset = toval; break; case TO_HELO: TimeOuts.to_helo = toval; break; case TO_QUIT: TimeOuts.to_quit = toval; break; case TO_MISC: TimeOuts.to_miscshort = toval; break; case TO_IDENT: TimeOuts.to_ident = toval; break; case TO_FILEOPEN: TimeOuts.to_fileopen = toval; break; case TO_CONNECT: TimeOuts.to_connect = toval; break; case TO_ICONNECT: TimeOuts.to_iconnect = toval; break; case TO_ACONNECT: TimeOuts.to_aconnect = toval; break; case TO_QUEUEWARN: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_NORMAL] = toval; TimeOuts.to_q_warning[TOC_URGENT] = toval; TimeOuts.to_q_warning[TOC_NONURGENT] = toval; TimeOuts.to_q_warning[TOC_DSN] = toval; addopts = 2; break; case TO_QUEUEWARN_NORMAL: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_NORMAL] = toval; break; case TO_QUEUEWARN_URGENT: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_URGENT] = toval; break; case TO_QUEUEWARN_NON_URGENT: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_NONURGENT] = toval; break; case TO_QUEUEWARN_DSN: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_DSN] = toval; break; case TO_QUEUERETURN: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_NORMAL] = toval; TimeOuts.to_q_return[TOC_URGENT] = toval; TimeOuts.to_q_return[TOC_NONURGENT] = toval; TimeOuts.to_q_return[TOC_DSN] = toval; addopts = 2; break; case TO_QUEUERETURN_NORMAL: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_NORMAL] = toval; break; case TO_QUEUERETURN_URGENT: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_URGENT] = toval; break; case TO_QUEUERETURN_NON_URGENT: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_NONURGENT] = toval; break; case TO_QUEUERETURN_DSN: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_DSN] = toval; break; case TO_HOSTSTATUS: MciInfoTimeout = toval; break; case TO_RESOLVER_RETRANS: toval = convtime(val, 's'); TimeOuts.res_retrans[RES_TO_DEFAULT] = toval; TimeOuts.res_retrans[RES_TO_FIRST] = toval; TimeOuts.res_retrans[RES_TO_NORMAL] = toval; addopts = 2; break; case TO_RESOLVER_RETRY: i = atoi(val); TimeOuts.res_retry[RES_TO_DEFAULT] = i; TimeOuts.res_retry[RES_TO_FIRST] = i; TimeOuts.res_retry[RES_TO_NORMAL] = i; addopts = 2; break; case TO_RESOLVER_RETRANS_NORMAL: TimeOuts.res_retrans[RES_TO_NORMAL] = convtime(val, 's'); break; case TO_RESOLVER_RETRY_NORMAL: TimeOuts.res_retry[RES_TO_NORMAL] = atoi(val); break; case TO_RESOLVER_RETRANS_FIRST: TimeOuts.res_retrans[RES_TO_FIRST] = convtime(val, 's'); break; case TO_RESOLVER_RETRY_FIRST: TimeOuts.res_retry[RES_TO_FIRST] = atoi(val); break; case TO_CONTROL: TimeOuts.to_control = toval; break; case TO_LHLO: TimeOuts.to_lhlo = toval; break; #if SASL case TO_AUTH: TimeOuts.to_auth = toval; break; #endif /* SASL */ #if STARTTLS case TO_STARTTLS: TimeOuts.to_starttls = toval; break; #endif /* STARTTLS */ default: syserr("settimeout: invalid timeout %s", name); break; } if (sticky) { for (i = 0; i <= addopts; i++) setbitn(to->to_code + i, StickyTimeoutOpt); } } /* ** INITTIMEOUTS -- parse and set timeout values ** ** Parameters: ** val -- a pointer to the values. If NULL, do initial ** settings. ** sticky -- if set, don't let other setoptions override ** this suboption value. ** ** Returns: ** none. ** ** Side Effects: ** Initializes the TimeOuts structure */ void inittimeouts(val, sticky) register char *val; bool sticky; { register char *p; if (tTd(37, 2)) sm_dprintf("inittimeouts(%s)\n", val == NULL ? "" : val); if (val == NULL) { TimeOuts.to_connect = (time_t) 0 SECONDS; TimeOuts.to_aconnect = (time_t) 0 SECONDS; TimeOuts.to_iconnect = (time_t) 0 SECONDS; TimeOuts.to_initial = (time_t) 5 MINUTES; TimeOuts.to_helo = (time_t) 5 MINUTES; TimeOuts.to_mail = (time_t) 10 MINUTES; TimeOuts.to_rcpt = (time_t) 1 HOUR; TimeOuts.to_datainit = (time_t) 5 MINUTES; TimeOuts.to_datablock = (time_t) 1 HOUR; TimeOuts.to_datafinal = (time_t) 1 HOUR; TimeOuts.to_rset = (time_t) 5 MINUTES; TimeOuts.to_quit = (time_t) 2 MINUTES; TimeOuts.to_nextcommand = (time_t) 1 HOUR; TimeOuts.to_miscshort = (time_t) 2 MINUTES; #if IDENTPROTO TimeOuts.to_ident = (time_t) 5 SECONDS; #else /* IDENTPROTO */ TimeOuts.to_ident = (time_t) 0 SECONDS; #endif /* IDENTPROTO */ TimeOuts.to_fileopen = (time_t) 60 SECONDS; TimeOuts.to_control = (time_t) 2 MINUTES; TimeOuts.to_lhlo = (time_t) 2 MINUTES; #if SASL TimeOuts.to_auth = (time_t) 10 MINUTES; #endif /* SASL */ #if STARTTLS TimeOuts.to_starttls = (time_t) 1 HOUR; #endif /* STARTTLS */ if (tTd(37, 5)) { sm_dprintf("Timeouts:\n"); sm_dprintf(" connect = %ld\n", (long) TimeOuts.to_connect); sm_dprintf(" aconnect = %ld\n", (long) TimeOuts.to_aconnect); sm_dprintf(" initial = %ld\n", (long) TimeOuts.to_initial); sm_dprintf(" helo = %ld\n", (long) TimeOuts.to_helo); sm_dprintf(" mail = %ld\n", (long) TimeOuts.to_mail); sm_dprintf(" rcpt = %ld\n", (long) TimeOuts.to_rcpt); sm_dprintf(" datainit = %ld\n", (long) TimeOuts.to_datainit); sm_dprintf(" datablock = %ld\n", (long) TimeOuts.to_datablock); sm_dprintf(" datafinal = %ld\n", (long) TimeOuts.to_datafinal); sm_dprintf(" rset = %ld\n", (long) TimeOuts.to_rset); sm_dprintf(" quit = %ld\n", (long) TimeOuts.to_quit); sm_dprintf(" nextcommand = %ld\n", (long) TimeOuts.to_nextcommand); sm_dprintf(" miscshort = %ld\n", (long) TimeOuts.to_miscshort); sm_dprintf(" ident = %ld\n", (long) TimeOuts.to_ident); sm_dprintf(" fileopen = %ld\n", (long) TimeOuts.to_fileopen); sm_dprintf(" lhlo = %ld\n", (long) TimeOuts.to_lhlo); sm_dprintf(" control = %ld\n", (long) TimeOuts.to_control); } return; } for (;; val = p) { while (isascii(*val) && isspace(*val)) val++; if (*val == '\0') break; for (p = val; *p != '\0' && *p != ','; p++) continue; if (*p != '\0') *p++ = '\0'; if (isascii(*val) && isdigit(*val)) { /* old syntax -- set everything */ TimeOuts.to_mail = convtime(val, 'm'); TimeOuts.to_rcpt = TimeOuts.to_mail; TimeOuts.to_datainit = TimeOuts.to_mail; TimeOuts.to_datablock = TimeOuts.to_mail; TimeOuts.to_datafinal = TimeOuts.to_mail; TimeOuts.to_nextcommand = TimeOuts.to_mail; if (sticky) { setbitn(TO_MAIL, StickyTimeoutOpt); setbitn(TO_RCPT, StickyTimeoutOpt); setbitn(TO_DATAINIT, StickyTimeoutOpt); setbitn(TO_DATABLOCK, StickyTimeoutOpt); setbitn(TO_DATAFINAL, StickyTimeoutOpt); setbitn(TO_COMMAND, StickyTimeoutOpt); } continue; } else { register char *q = strchr(val, ':'); if (q == NULL && (q = strchr(val, '=')) == NULL) { /* syntax error */ continue; } *q++ = '\0'; settimeout(val, q, sticky); } } } Index: head/contrib/sendmail/src/recipient.c =================================================================== --- head/contrib/sendmail/src/recipient.c (revision 249728) +++ head/contrib/sendmail/src/recipient.c (revision 249729) @@ -1,2072 +1,2072 @@ /* * Copyright (c) 1998-2003, 2006 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: recipient.c,v 8.349 2007/07/10 17:01:22 ca Exp $") +SM_RCSID("@(#)$Id: recipient.c,v 8.350 2013/03/12 15:24:54 ca Exp $") static void includetimeout __P((int)); static ADDRESS *self_reference __P((ADDRESS *)); static int sortexpensive __P((ADDRESS *, ADDRESS *)); static int sortbysignature __P((ADDRESS *, ADDRESS *)); static int sorthost __P((ADDRESS *, ADDRESS *)); typedef int sortfn_t __P((ADDRESS *, ADDRESS *)); /* ** SORTHOST -- strcmp()-like func for host portion of an ADDRESS ** ** Parameters: ** xx -- first ADDRESS ** yy -- second ADDRESS ** ** Returns: ** <0 when xx->q_host is less than yy->q_host ** >0 when xx->q_host is greater than yy->q_host ** 0 when equal */ static int sorthost(xx, yy) register ADDRESS *xx; register ADDRESS *yy; { #if _FFR_HOST_SORT_REVERSE /* XXX maybe compare hostnames from the end? */ return sm_strrevcasecmp(xx->q_host, yy->q_host); #else /* _FFR_HOST_SORT_REVERSE */ return sm_strcasecmp(xx->q_host, yy->q_host); #endif /* _FFR_HOST_SORT_REVERSE */ } /* ** SORTEXPENSIVE -- strcmp()-like func for expensive mailers ** ** The mailer has been noted already as "expensive" for 'xx'. This ** will give a result relative to 'yy'. Expensive mailers get rated ** "greater than" non-expensive mailers because during the delivery phase ** it will get queued -- no use it getting in the way of less expensive ** recipients. We avoid an MX RR lookup when both 'xx' and 'yy' are ** expensive since an MX RR lookup happens when extracted from the queue ** later. ** ** Parameters: ** xx -- first ADDRESS ** yy -- second ADDRESS ** ** Returns: ** <0 when xx->q_host is less than yy->q_host and both are ** expensive ** >0 when xx->q_host is greater than yy->q_host, or when ** 'yy' is non-expensive ** 0 when equal (by expense and q_host) */ static int sortexpensive(xx, yy) ADDRESS *xx; ADDRESS *yy; { if (!bitnset(M_EXPENSIVE, yy->q_mailer->m_flags)) return 1; /* xx should go later */ #if _FFR_HOST_SORT_REVERSE /* XXX maybe compare hostnames from the end? */ return sm_strrevcasecmp(xx->q_host, yy->q_host); #else /* _FFR_HOST_SORT_REVERSE */ return sm_strcasecmp(xx->q_host, yy->q_host); #endif /* _FFR_HOST_SORT_REVERSE */ } /* ** SORTBYSIGNATURE -- a strcmp()-like func for q_mailer and q_host in ADDRESS ** ** Parameters: ** xx -- first ADDRESS ** yy -- second ADDRESS ** ** Returns: ** 0 when the "signature"'s are same ** <0 when xx->q_signature is less than yy->q_signature ** >0 when xx->q_signature is greater than yy->q_signature ** ** Side Effect: ** May set ADDRESS pointer for q_signature if not already set. */ static int sortbysignature(xx, yy) ADDRESS *xx; ADDRESS *yy; { register int ret; /* Let's avoid redoing the signature over and over again */ if (xx->q_signature == NULL) xx->q_signature = hostsignature(xx->q_mailer, xx->q_host); if (yy->q_signature == NULL) yy->q_signature = hostsignature(yy->q_mailer, yy->q_host); ret = strcmp(xx->q_signature, yy->q_signature); /* ** If the two signatures are the same then we will return a sort ** value based on 'q_user'. But note that we have reversed xx and yy ** on purpose. This additional compare helps reduce the number of ** sameaddr() calls and loops in recipient() for the case when ** the rcpt list has been provided already in-order. */ if (ret == 0) return strcmp(yy->q_user, xx->q_user); else return ret; } /* ** SENDTOLIST -- Designate a send list. ** ** The parameter is a comma-separated list of people to send to. ** This routine arranges to send to all of them. ** ** Parameters: ** list -- the send list. ** ctladdr -- the address template for the person to ** send to -- effective uid/gid are important. ** This is typically the alias that caused this ** expansion. ** sendq -- a pointer to the head of a queue to put ** these people into. ** aliaslevel -- the current alias nesting depth -- to ** diagnose loops. ** e -- the envelope in which to add these recipients. ** ** Returns: ** The number of addresses actually on the list. */ /* q_flags bits inherited from ctladdr */ #define QINHERITEDBITS (QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY|QHASNOTIFY) int sendtolist(list, ctladdr, sendq, aliaslevel, e) char *list; ADDRESS *ctladdr; ADDRESS **sendq; int aliaslevel; register ENVELOPE *e; { register char *p; register ADDRESS *SM_NONVOLATILE al; /* list of addresses to send to */ SM_NONVOLATILE char delimiter; /* the address delimiter */ SM_NONVOLATILE int naddrs; SM_NONVOLATILE int i; char *endp; char *oldto = e->e_to; char *SM_NONVOLATILE bufp; char buf[MAXNAME + 1]; if (list == NULL) { syserr("sendtolist: null list"); return 0; } if (tTd(25, 1)) { sm_dprintf("sendto: %s\n ctladdr=", list); printaddr(sm_debug_file(), ctladdr, false); } /* heuristic to determine old versus new style addresses */ if (ctladdr == NULL && (strchr(list, ',') != NULL || strchr(list, ';') != NULL || strchr(list, '<') != NULL || strchr(list, '(') != NULL)) e->e_flags &= ~EF_OLDSTYLE; delimiter = ' '; if (!bitset(EF_OLDSTYLE, e->e_flags) || ctladdr != NULL) delimiter = ','; al = NULL; naddrs = 0; /* make sure we have enough space to copy the string */ i = strlen(list) + 1; if (i <= sizeof(buf)) { bufp = buf; i = sizeof(buf); } else bufp = sm_malloc_x(i); endp = bufp + i; SM_TRY { (void) sm_strlcpy(bufp, denlstring(list, false, true), i); macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r"); for (p = bufp; *p != '\0'; ) { auto char *delimptr; register ADDRESS *a; SM_ASSERT(p < endp); /* parse the address */ while ((isascii(*p) && isspace(*p)) || *p == ',') p++; SM_ASSERT(p < endp); a = parseaddr(p, NULLADDR, RF_COPYALL, delimiter, &delimptr, e, true); p = delimptr; SM_ASSERT(p < endp); if (a == NULL) continue; a->q_next = al; a->q_alias = ctladdr; /* arrange to inherit attributes from parent */ if (ctladdr != NULL) { ADDRESS *b; /* self reference test */ if (sameaddr(ctladdr, a)) { if (tTd(27, 5)) { sm_dprintf("sendtolist: QSELFREF "); printaddr(sm_debug_file(), ctladdr, false); } ctladdr->q_flags |= QSELFREF; } /* check for address loops */ b = self_reference(a); if (b != NULL) { b->q_flags |= QSELFREF; if (tTd(27, 5)) { sm_dprintf("sendtolist: QSELFREF "); printaddr(sm_debug_file(), b, false); } if (a != b) { if (tTd(27, 5)) { sm_dprintf("sendtolist: QS_DONTSEND "); printaddr(sm_debug_file(), a, false); } a->q_state = QS_DONTSEND; b->q_flags |= a->q_flags & QNOTREMOTE; continue; } } /* full name */ if (a->q_fullname == NULL) a->q_fullname = ctladdr->q_fullname; /* various flag bits */ a->q_flags &= ~QINHERITEDBITS; a->q_flags |= ctladdr->q_flags & QINHERITEDBITS; /* DSN recipient information */ a->q_finalrcpt = ctladdr->q_finalrcpt; a->q_orcpt = ctladdr->q_orcpt; } al = a; } /* arrange to send to everyone on the local send list */ while (al != NULL) { register ADDRESS *a = al; al = a->q_next; a = recipient(a, sendq, aliaslevel, e); naddrs++; } } SM_FINALLY { e->e_to = oldto; if (bufp != buf) sm_free(bufp); macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL); } SM_END_TRY return naddrs; } #if MILTER /* ** REMOVEFROMLIST -- Remove addresses from a send list. ** ** The parameter is a comma-separated list of recipients to remove. ** Note that it only deletes matching addresses. If those addresses ** have been expanded already in the sendq, it won't mark the ** expanded recipients as QS_REMOVED. ** ** Parameters: ** list -- the list to remove. ** sendq -- a pointer to the head of a queue to remove ** these addresses from. ** e -- the envelope in which to remove these recipients. ** ** Returns: ** The number of addresses removed from the list. ** */ int removefromlist(list, sendq, e) char *list; ADDRESS **sendq; ENVELOPE *e; { SM_NONVOLATILE char delimiter; /* the address delimiter */ SM_NONVOLATILE int naddrs; SM_NONVOLATILE int i; char *p; char *oldto = e->e_to; char *SM_NONVOLATILE bufp; char buf[MAXNAME + 1]; if (list == NULL) { syserr("removefromlist: null list"); return 0; } if (tTd(25, 1)) sm_dprintf("removefromlist: %s\n", list); /* heuristic to determine old versus new style addresses */ if (strchr(list, ',') != NULL || strchr(list, ';') != NULL || strchr(list, '<') != NULL || strchr(list, '(') != NULL) e->e_flags &= ~EF_OLDSTYLE; delimiter = ' '; if (!bitset(EF_OLDSTYLE, e->e_flags)) delimiter = ','; naddrs = 0; /* make sure we have enough space to copy the string */ i = strlen(list) + 1; if (i <= sizeof(buf)) { bufp = buf; i = sizeof(buf); } else bufp = sm_malloc_x(i); SM_TRY { (void) sm_strlcpy(bufp, denlstring(list, false, true), i); #if _FFR_ADDR_TYPE_MODES if (AddrTypeModes) macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r d"); else #endif /* _FFR_ADDR_TYPE_MODES */ macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r"); for (p = bufp; *p != '\0'; ) { ADDRESS a; /* parsed address to be removed */ ADDRESS *q; ADDRESS **pq; char *delimptr; /* parse the address */ while ((isascii(*p) && isspace(*p)) || *p == ',') p++; if (parseaddr(p, &a, RF_COPYALL|RF_RM_ADDR, delimiter, &delimptr, e, true) == NULL) { p = delimptr; continue; } p = delimptr; for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next) { if (!QS_IS_DEAD(q->q_state) && (sameaddr(q, &a) || strcmp(q->q_paddr, a.q_paddr) == 0)) { if (tTd(25, 5)) { sm_dprintf("removefromlist: QS_REMOVED "); printaddr(sm_debug_file(), &a, false); } q->q_state = QS_REMOVED; naddrs++; break; } } } } SM_FINALLY { e->e_to = oldto; if (bufp != buf) sm_free(bufp); macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL); } SM_END_TRY return naddrs; } #endif /* MILTER */ /* ** RECIPIENT -- Designate a message recipient ** Saves the named person for future mailing (after some checks). ** ** Parameters: ** new -- the (preparsed) address header for the recipient. ** sendq -- a pointer to the head of a queue to put the ** recipient in. Duplicate suppression is done ** in this queue. ** aliaslevel -- the current alias nesting depth. ** e -- the current envelope. ** ** Returns: ** The actual address in the queue. This will be "a" if ** the address is not a duplicate, else the original address. ** */ ADDRESS * recipient(new, sendq, aliaslevel, e) register ADDRESS *new; register ADDRESS **sendq; int aliaslevel; register ENVELOPE *e; { register ADDRESS *q; ADDRESS **pq; ADDRESS **prev; register struct mailer *m; register char *p; int i, buflen; bool quoted; /* set if the addr has a quote bit */ bool insert; int findusercount; bool initialdontsend; char *buf; char buf0[MAXNAME + 1]; /* unquoted image of the user name */ sortfn_t *sortfn; p = NULL; quoted = false; insert = false; findusercount = 0; initialdontsend = QS_IS_DEAD(new->q_state); e->e_to = new->q_paddr; m = new->q_mailer; errno = 0; if (aliaslevel == 0) new->q_flags |= QPRIMARY; if (tTd(26, 1)) { sm_dprintf("\nrecipient (%d): ", aliaslevel); printaddr(sm_debug_file(), new, false); } /* if this is primary, use it as original recipient */ if (new->q_alias == NULL) { if (e->e_origrcpt == NULL) e->e_origrcpt = new->q_paddr; else if (e->e_origrcpt != new->q_paddr) e->e_origrcpt = ""; } /* find parent recipient for finalrcpt and orcpt */ for (q = new; q->q_alias != NULL; q = q->q_alias) continue; /* find final recipient DSN address */ if (new->q_finalrcpt == NULL && e->e_from.q_mailer != NULL) { char frbuf[MAXLINE]; p = e->e_from.q_mailer->m_addrtype; if (p == NULL) p = "rfc822"; if (sm_strcasecmp(p, "rfc822") != 0) { (void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s", q->q_mailer->m_addrtype, q->q_user); } else if (strchr(q->q_user, '@') != NULL) { (void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s", p, q->q_user); } else if (strchr(q->q_paddr, '@') != NULL) { char *qp; bool b; qp = q->q_paddr; /* strip brackets from address */ b = false; if (*qp == '<') { b = qp[strlen(qp) - 1] == '>'; if (b) qp[strlen(qp) - 1] = '\0'; qp++; } (void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.800s", p, qp); /* undo damage */ if (b) qp[strlen(qp)] = '>'; } else { (void) sm_snprintf(frbuf, sizeof(frbuf), "%s; %.700s@%.100s", p, q->q_user, MyHostName); } new->q_finalrcpt = sm_rpool_strdup_x(e->e_rpool, frbuf); } #if _FFR_GEN_ORCPT /* set ORCPT DSN arg if not already set */ if (new->q_orcpt == NULL) { /* check for an existing ORCPT */ if (q->q_orcpt != NULL) new->q_orcpt = q->q_orcpt; else { /* make our own */ bool b = false; char *qp; char obuf[MAXLINE]; if (e->e_from.q_mailer != NULL) p = e->e_from.q_mailer->m_addrtype; if (p == NULL) p = "rfc822"; (void) sm_strlcpyn(obuf, sizeof(obuf), 2, p, ";"); qp = q->q_paddr; /* FFR: Needs to strip comments from stdin addrs */ /* strip brackets from address */ if (*qp == '<') { b = qp[strlen(qp) - 1] == '>'; if (b) qp[strlen(qp) - 1] = '\0'; qp++; } p = xtextify(denlstring(qp, true, false), "="); if (sm_strlcat(obuf, p, sizeof(obuf)) >= sizeof(obuf)) { /* if too big, don't use it */ obuf[0] = '\0'; } /* undo damage */ if (b) qp[strlen(qp)] = '>'; if (obuf[0] != '\0') new->q_orcpt = sm_rpool_strdup_x(e->e_rpool, obuf); } } #endif /* _FFR_GEN_ORCPT */ /* break aliasing loops */ if (aliaslevel > MaxAliasRecursion) { new->q_state = QS_BADADDR; new->q_status = "5.4.6"; if (new->q_alias != NULL) { new->q_alias->q_state = QS_BADADDR; new->q_alias->q_status = "5.4.6"; } if ((SuprErrs || !LogUsrErrs) && LogLevel > 0) { sm_syslog(LOG_ERR, e->e_id, "aliasing/forwarding loop broken: %s (%d aliases deep; %d max)", FileName != NULL ? FileName : "", aliaslevel, MaxAliasRecursion); } usrerrenh(new->q_status, "554 aliasing/forwarding loop broken (%d aliases deep; %d max)", aliaslevel, MaxAliasRecursion); return new; } /* ** Finish setting up address structure. */ /* get unquoted user for file, program or user.name check */ i = strlen(new->q_user); if (i >= sizeof(buf0)) { buflen = i + 1; buf = xalloc(buflen); } else { buf = buf0; buflen = sizeof(buf0); } (void) sm_strlcpy(buf, new->q_user, buflen); for (p = buf; *p != '\0' && !quoted; p++) { if (*p == '\\') quoted = true; } stripquotes(buf); /* check for direct mailing to restricted mailers */ if (m == ProgMailer) { if (new->q_alias == NULL || UseMSP || bitset(EF_UNSAFE, e->e_flags)) { new->q_state = QS_BADADDR; new->q_status = "5.7.1"; usrerrenh(new->q_status, "550 Cannot mail directly to programs"); } else if (bitset(QBOGUSSHELL, new->q_alias->q_flags)) { new->q_state = QS_BADADDR; new->q_status = "5.7.1"; if (new->q_alias->q_ruser == NULL) usrerrenh(new->q_status, "550 UID %d is an unknown user: cannot mail to programs", new->q_alias->q_uid); else usrerrenh(new->q_status, "550 User %s@%s doesn't have a valid shell for mailing to programs", new->q_alias->q_ruser, MyHostName); } else if (bitset(QUNSAFEADDR, new->q_alias->q_flags)) { new->q_state = QS_BADADDR; new->q_status = "5.7.1"; new->q_rstatus = "550 Unsafe for mailing to programs"; usrerrenh(new->q_status, "550 Address %s is unsafe for mailing to programs", new->q_alias->q_paddr); } } /* ** Look up this person in the recipient list. ** If they are there already, return, otherwise continue. ** If the list is empty, just add it. Notice the cute ** hack to make from addresses suppress things correctly: ** the QS_DUPLICATE state will be set in the send list. ** [Please note: the emphasis is on "hack."] */ prev = NULL; /* ** If this message is going to the queue or FastSplit is set ** and it is the first try and the envelope hasn't split, then we ** avoid doing an MX RR lookup now because one will be done when the ** message is extracted from the queue later. It can go to the queue ** because all messages are going to the queue or this mailer of ** the current recipient is marked expensive. */ if (UseMSP || WILL_BE_QUEUED(e->e_sendmode) || (!bitset(EF_SPLIT, e->e_flags) && e->e_ntries == 0 && FastSplit > 0)) sortfn = sorthost; else if (NoConnect && bitnset(M_EXPENSIVE, new->q_mailer->m_flags)) sortfn = sortexpensive; else sortfn = sortbysignature; for (pq = sendq; (q = *pq) != NULL; pq = &q->q_next) { /* ** If address is "less than" it should be inserted now. ** If address is "greater than" current comparison it'll ** insert later in the list; so loop again (if possible). ** If address is "equal" (different equal than sameaddr() ** call) then check if sameaddr() will be true. ** Because this list is now sorted, it'll mean fewer ** comparisons and fewer loops which is important for more ** recipients. */ i = (*sortfn)(new, q); if (i == 0) /* equal */ { /* ** Sortbysignature() has said that the two have ** equal MX RR's and the same user. Calling sameaddr() ** now checks if the two hosts are as identical as the ** MX RR's are (which might not be the case) ** before saying these are the identical addresses. */ if (sameaddr(q, new) && (bitset(QRCPTOK, q->q_flags) || !bitset(QPRIMARY, q->q_flags))) { if (tTd(26, 1)) { sm_dprintf("%s in sendq: ", new->q_paddr); printaddr(sm_debug_file(), q, false); } if (!bitset(QPRIMARY, q->q_flags)) { if (!QS_IS_DEAD(new->q_state)) message("duplicate suppressed"); else q->q_state = QS_DUPLICATE; q->q_flags |= new->q_flags; } else if (bitset(QSELFREF, q->q_flags) || q->q_state == QS_REMOVED) { /* ** If an earlier milter removed the ** address, a later one can still add ** it back. */ q->q_state = new->q_state; q->q_flags |= new->q_flags; } new = q; goto done; } } else if (i < 0) /* less than */ { insert = true; break; } prev = pq; } /* pq should point to an address, never NULL */ SM_ASSERT(pq != NULL); /* add address on list */ if (insert) { /* ** insert before 'pq'. Only possible when at least 1 ** ADDRESS is in the list already. */ new->q_next = *pq; if (prev == NULL) *sendq = new; /* To be the first ADDRESS */ else (*prev)->q_next = new; } else { /* ** Place in list at current 'pq' position. Possible ** when there are 0 or more ADDRESS's in the list. */ new->q_next = NULL; *pq = new; } /* added a new address: clear split flag */ e->e_flags &= ~EF_SPLIT; /* ** Alias the name and handle special mailer types. */ trylocaluser: if (tTd(29, 7)) { sm_dprintf("at trylocaluser: "); printaddr(sm_debug_file(), new, false); } if (!QS_IS_OK(new->q_state)) { if (QS_IS_UNDELIVERED(new->q_state)) e->e_nrcpts++; goto testselfdestruct; } if (m == InclMailer) { new->q_state = QS_INCLUDED; if (new->q_alias == NULL || UseMSP || bitset(EF_UNSAFE, e->e_flags)) { new->q_state = QS_BADADDR; new->q_status = "5.7.1"; usrerrenh(new->q_status, "550 Cannot mail directly to :include:s"); } else { int ret; message("including file %s", new->q_user); ret = include(new->q_user, false, new, sendq, aliaslevel, e); if (transienterror(ret)) { if (LogLevel > 2) sm_syslog(LOG_ERR, e->e_id, "include %s: transient error: %s", shortenstring(new->q_user, MAXSHORTSTR), sm_errstring(ret)); new->q_state = QS_QUEUEUP; usrerr("451 4.2.4 Cannot open %s: %s", shortenstring(new->q_user, MAXSHORTSTR), sm_errstring(ret)); } else if (ret != 0) { new->q_state = QS_BADADDR; new->q_status = "5.2.4"; usrerrenh(new->q_status, "550 Cannot open %s: %s", shortenstring(new->q_user, MAXSHORTSTR), sm_errstring(ret)); } } } else if (m == FileMailer) { /* check if allowed */ if (new->q_alias == NULL || UseMSP || bitset(EF_UNSAFE, e->e_flags)) { new->q_state = QS_BADADDR; new->q_status = "5.7.1"; usrerrenh(new->q_status, "550 Cannot mail directly to files"); } else if (bitset(QBOGUSSHELL, new->q_alias->q_flags)) { new->q_state = QS_BADADDR; new->q_status = "5.7.1"; if (new->q_alias->q_ruser == NULL) usrerrenh(new->q_status, "550 UID %d is an unknown user: cannot mail to files", new->q_alias->q_uid); else usrerrenh(new->q_status, "550 User %s@%s doesn't have a valid shell for mailing to files", new->q_alias->q_ruser, MyHostName); } else if (bitset(QUNSAFEADDR, new->q_alias->q_flags)) { new->q_state = QS_BADADDR; new->q_status = "5.7.1"; new->q_rstatus = "550 Unsafe for mailing to files"; usrerrenh(new->q_status, "550 Address %s is unsafe for mailing to files", new->q_alias->q_paddr); } } /* try aliasing */ if (!quoted && QS_IS_OK(new->q_state) && bitnset(M_ALIASABLE, m->m_flags)) alias(new, sendq, aliaslevel, e); #if USERDB /* if not aliased, look it up in the user database */ if (!bitset(QNOTREMOTE, new->q_flags) && QS_IS_SENDABLE(new->q_state) && bitnset(M_CHECKUDB, m->m_flags)) { if (udbexpand(new, sendq, aliaslevel, e) == EX_TEMPFAIL) { new->q_state = QS_QUEUEUP; if (e->e_message == NULL) e->e_message = sm_rpool_strdup_x(e->e_rpool, "Deferred: user database error"); if (new->q_message == NULL) new->q_message = "Deferred: user database error"; if (LogLevel > 8) sm_syslog(LOG_INFO, e->e_id, "deferred: udbexpand: %s", sm_errstring(errno)); message("queued (user database error): %s", sm_errstring(errno)); e->e_nrcpts++; goto testselfdestruct; } } #endif /* USERDB */ /* ** If we have a level two config file, then pass the name through ** Ruleset 5 before sending it off. Ruleset 5 has the right ** to rewrite it to another mailer. This gives us a hook ** after local aliasing has been done. */ if (tTd(29, 5)) { sm_dprintf("recipient: testing local? cl=%d, rr5=%p\n\t", ConfigLevel, RewriteRules[5]); printaddr(sm_debug_file(), new, false); } if (ConfigLevel >= 2 && RewriteRules[5] != NULL && bitnset(M_TRYRULESET5, m->m_flags) && !bitset(QNOTREMOTE, new->q_flags) && QS_IS_OK(new->q_state)) { maplocaluser(new, sendq, aliaslevel + 1, e); } /* ** If it didn't get rewritten to another mailer, go ahead ** and deliver it. */ if (QS_IS_OK(new->q_state) && bitnset(M_HASPWENT, m->m_flags)) { auto bool fuzzy; SM_MBDB_T user; int status; /* warning -- finduser may trash buf */ status = finduser(buf, &fuzzy, &user); switch (status) { case EX_TEMPFAIL: new->q_state = QS_QUEUEUP; new->q_status = "4.5.2"; giveresponse(EX_TEMPFAIL, new->q_status, m, NULL, new->q_alias, (time_t) 0, e, new); break; default: new->q_state = QS_BADADDR; new->q_status = "5.1.1"; new->q_rstatus = "550 5.1.1 User unknown"; giveresponse(EX_NOUSER, new->q_status, m, NULL, new->q_alias, (time_t) 0, e, new); break; case EX_OK: if (fuzzy) { /* name was a fuzzy match */ new->q_user = sm_rpool_strdup_x(e->e_rpool, user.mbdb_name); if (findusercount++ > 3) { new->q_state = QS_BADADDR; new->q_status = "5.4.6"; usrerrenh(new->q_status, "554 aliasing/forwarding loop for %s broken", user.mbdb_name); goto done; } /* see if it aliases */ (void) sm_strlcpy(buf, user.mbdb_name, buflen); goto trylocaluser; } if (*user.mbdb_homedir == '\0') new->q_home = NULL; else if (strcmp(user.mbdb_homedir, "/") == 0) new->q_home = ""; else new->q_home = sm_rpool_strdup_x(e->e_rpool, user.mbdb_homedir); if (user.mbdb_uid != SM_NO_UID) { new->q_uid = user.mbdb_uid; new->q_gid = user.mbdb_gid; new->q_flags |= QGOODUID; } new->q_ruser = sm_rpool_strdup_x(e->e_rpool, user.mbdb_name); if (user.mbdb_fullname[0] != '\0') new->q_fullname = sm_rpool_strdup_x(e->e_rpool, user.mbdb_fullname); if (!usershellok(user.mbdb_name, user.mbdb_shell)) { new->q_flags |= QBOGUSSHELL; } if (bitset(EF_VRFYONLY, e->e_flags)) { /* don't do any more now */ new->q_state = QS_VERIFIED; } else if (!quoted) forward(new, sendq, aliaslevel, e); } } if (!QS_IS_DEAD(new->q_state)) e->e_nrcpts++; testselfdestruct: new->q_flags |= QTHISPASS; if (tTd(26, 8)) { sm_dprintf("testselfdestruct: "); printaddr(sm_debug_file(), new, false); if (tTd(26, 10)) { sm_dprintf("SENDQ:\n"); printaddr(sm_debug_file(), *sendq, true); sm_dprintf("----\n"); } } if (new->q_alias == NULL && new != &e->e_from && QS_IS_DEAD(new->q_state)) { for (q = *sendq; q != NULL; q = q->q_next) { if (!QS_IS_DEAD(q->q_state)) break; } if (q == NULL) { new->q_state = QS_BADADDR; new->q_status = "5.4.6"; usrerrenh(new->q_status, "554 aliasing/forwarding loop broken"); } } done: new->q_flags |= QTHISPASS; if (buf != buf0) sm_free(buf); /* XXX leak if above code raises exception */ /* ** If we are at the top level, check to see if this has ** expanded to exactly one address. If so, it can inherit ** the primaryness of the address. ** ** While we're at it, clear the QTHISPASS bits. */ if (aliaslevel == 0) { int nrcpts = 0; ADDRESS *only = NULL; for (q = *sendq; q != NULL; q = q->q_next) { if (bitset(QTHISPASS, q->q_flags) && QS_IS_SENDABLE(q->q_state)) { nrcpts++; only = q; } q->q_flags &= ~QTHISPASS; } if (nrcpts == 1) { /* check to see if this actually got a new owner */ q = only; while ((q = q->q_alias) != NULL) { if (q->q_owner != NULL) break; } if (q == NULL) only->q_flags |= QPRIMARY; } else if (!initialdontsend && nrcpts > 0) { /* arrange for return receipt */ e->e_flags |= EF_SENDRECEIPT; new->q_flags |= QEXPANDED; if (e->e_xfp != NULL && bitset(QPINGONSUCCESS, new->q_flags)) (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s... expanded to multiple addresses\n", new->q_paddr); } } new->q_flags |= QRCPTOK; (void) sm_snprintf(buf0, sizeof(buf0), "%d", e->e_nrcpts); macdefine(&e->e_macro, A_TEMP, macid("{nrcpts}"), buf0); return new; } /* ** FINDUSER -- find the password entry for a user. ** ** This looks a lot like getpwnam, except that it may want to ** do some fancier pattern matching in /etc/passwd. ** ** This routine contains most of the time of many sendmail runs. ** It deserves to be optimized. ** ** Parameters: ** name -- the name to match against. ** fuzzyp -- an outarg that is set to true if this entry ** was found using the fuzzy matching algorithm; ** set to false otherwise. ** user -- structure to fill in if user is found ** ** Returns: ** On success, fill in *user, set *fuzzyp and return EX_OK. ** If the user was not found, return EX_NOUSER. ** On error, return EX_TEMPFAIL or EX_OSERR. ** ** Side Effects: ** may modify name. */ int finduser(name, fuzzyp, user) char *name; bool *fuzzyp; SM_MBDB_T *user; { #if MATCHGECOS register struct passwd *pw; #endif /* MATCHGECOS */ register char *p; bool tryagain; int status; if (tTd(29, 4)) sm_dprintf("finduser(%s): ", name); *fuzzyp = false; #if HESIOD /* DEC Hesiod getpwnam accepts numeric strings -- short circuit it */ for (p = name; *p != '\0'; p++) if (!isascii(*p) || !isdigit(*p)) break; if (*p == '\0') { if (tTd(29, 4)) sm_dprintf("failed (numeric input)\n"); return EX_NOUSER; } #endif /* HESIOD */ /* look up this login name using fast path */ status = sm_mbdb_lookup(name, user); if (status != EX_NOUSER) { if (tTd(29, 4)) sm_dprintf("%s (non-fuzzy)\n", sm_strexit(status)); return status; } /* try mapping it to lower case */ tryagain = false; for (p = name; *p != '\0'; p++) { if (isascii(*p) && isupper(*p)) { *p = tolower(*p); tryagain = true; } } if (tryagain && (status = sm_mbdb_lookup(name, user)) != EX_NOUSER) { if (tTd(29, 4)) sm_dprintf("%s (lower case)\n", sm_strexit(status)); *fuzzyp = true; return status; } #if MATCHGECOS /* see if fuzzy matching allowed */ if (!MatchGecos) { if (tTd(29, 4)) sm_dprintf("not found (fuzzy disabled)\n"); return EX_NOUSER; } /* search for a matching full name instead */ for (p = name; *p != '\0'; p++) { if (*p == (SpaceSub & 0177) || *p == '_') *p = ' '; } (void) setpwent(); while ((pw = getpwent()) != NULL) { char buf[MAXNAME + 1]; # if 0 if (sm_strcasecmp(pw->pw_name, name) == 0) { if (tTd(29, 4)) sm_dprintf("found (case wrapped)\n"); break; } # endif /* 0 */ sm_pwfullname(pw->pw_gecos, pw->pw_name, buf, sizeof(buf)); if (strchr(buf, ' ') != NULL && sm_strcasecmp(buf, name) == 0) { if (tTd(29, 4)) sm_dprintf("fuzzy matches %s\n", pw->pw_name); message("sending to login name %s", pw->pw_name); break; } } if (pw != NULL) *fuzzyp = true; else if (tTd(29, 4)) sm_dprintf("no fuzzy match found\n"); # if DEC_OSF_BROKEN_GETPWENT /* DEC OSF/1 3.2 or earlier */ endpwent(); # endif /* DEC_OSF_BROKEN_GETPWENT */ if (pw == NULL) return EX_NOUSER; sm_mbdb_frompw(user, pw); return EX_OK; #else /* MATCHGECOS */ if (tTd(29, 4)) sm_dprintf("not found (fuzzy disabled)\n"); return EX_NOUSER; #endif /* MATCHGECOS */ } /* ** WRITABLE -- predicate returning if the file is writable. ** ** This routine must duplicate the algorithm in sys/fio.c. ** Unfortunately, we cannot use the access call since we ** won't necessarily be the real uid when we try to ** actually open the file. ** ** Notice that ANY file with ANY execute bit is automatically ** not writable. This is also enforced by mailfile. ** ** Parameters: ** filename -- the file name to check. ** ctladdr -- the controlling address for this file. ** flags -- SFF_* flags to control the function. ** ** Returns: ** true -- if we will be able to write this file. ** false -- if we cannot write this file. ** ** Side Effects: ** none. */ bool writable(filename, ctladdr, flags) char *filename; ADDRESS *ctladdr; long flags; { uid_t euid = 0; gid_t egid = 0; char *user = NULL; if (tTd(44, 5)) sm_dprintf("writable(%s, 0x%lx)\n", filename, flags); /* ** File does exist -- check that it is writable. */ if (geteuid() != 0) { euid = geteuid(); egid = getegid(); user = NULL; } else if (ctladdr != NULL) { euid = ctladdr->q_uid; egid = ctladdr->q_gid; user = ctladdr->q_user; } else if (bitset(SFF_RUNASREALUID, flags)) { euid = RealUid; egid = RealGid; user = RealUserName; } else if (FileMailer != NULL && !bitset(SFF_ROOTOK, flags)) { if (FileMailer->m_uid == NO_UID) { euid = DefUid; user = DefUser; } else { euid = FileMailer->m_uid; user = NULL; } if (FileMailer->m_gid == NO_GID) egid = DefGid; else egid = FileMailer->m_gid; } else { euid = egid = 0; user = NULL; } if (!bitset(SFF_ROOTOK, flags)) { if (euid == 0) { euid = DefUid; user = DefUser; } if (egid == 0) egid = DefGid; } if (geteuid() == 0 && (ctladdr == NULL || !bitset(QGOODUID, ctladdr->q_flags))) flags |= SFF_SETUIDOK; if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail)) flags |= SFF_NOSLINK; if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail)) flags |= SFF_NOHLINK; errno = safefile(filename, euid, egid, user, flags, S_IWRITE, NULL); return errno == 0; } /* ** INCLUDE -- handle :include: specification. ** ** Parameters: ** fname -- filename to include. ** forwarding -- if true, we are reading a .forward file. ** if false, it's a :include: file. ** ctladdr -- address template to use to fill in these ** addresses -- effective user/group id are ** the important things. ** sendq -- a pointer to the head of the send queue ** to put these addresses in. ** aliaslevel -- the alias nesting depth. ** e -- the current envelope. ** ** Returns: ** open error status ** ** Side Effects: ** reads the :include: file and sends to everyone ** listed in that file. ** ** Security Note: ** If you have restricted chown (that is, you can't ** give a file away), it is reasonable to allow programs ** and files called from this :include: file to be to be ** run as the owner of the :include: file. This is bogus ** if there is any chance of someone giving away a file. ** We assume that pre-POSIX systems can give away files. ** ** There is an additional restriction that if you ** forward to a :include: file, it will not take on ** the ownership of the :include: file. This may not ** be necessary, but shouldn't hurt. */ static jmp_buf CtxIncludeTimeout; int include(fname, forwarding, ctladdr, sendq, aliaslevel, e) char *fname; bool forwarding; ADDRESS *ctladdr; ADDRESS **sendq; int aliaslevel; ENVELOPE *e; { SM_FILE_T *volatile fp = NULL; char *oldto = e->e_to; char *oldfilename = FileName; int oldlinenumber = LineNumber; register SM_EVENT *ev = NULL; int nincludes; int mode; volatile bool maxreached = false; register ADDRESS *ca; volatile uid_t saveduid; volatile gid_t savedgid; volatile uid_t uid; volatile gid_t gid; char *volatile user; int rval = 0; volatile long sfflags = SFF_REGONLY; register char *p; bool safechown = false; volatile bool safedir = false; struct stat st; char buf[MAXLINE]; if (tTd(27, 2)) sm_dprintf("include(%s)\n", fname); if (tTd(27, 4)) sm_dprintf(" ruid=%d euid=%d\n", (int) getuid(), (int) geteuid()); if (tTd(27, 14)) { sm_dprintf("ctladdr "); printaddr(sm_debug_file(), ctladdr, false); } if (tTd(27, 9)) sm_dprintf("include: old uid = %d/%d\n", (int) getuid(), (int) geteuid()); if (forwarding) { sfflags |= SFF_MUSTOWN|SFF_ROOTOK; if (!bitnset(DBS_GROUPWRITABLEFORWARDFILE, DontBlameSendmail)) sfflags |= SFF_NOGWFILES; if (!bitnset(DBS_WORLDWRITABLEFORWARDFILE, DontBlameSendmail)) sfflags |= SFF_NOWWFILES; } else { if (!bitnset(DBS_GROUPWRITABLEINCLUDEFILE, DontBlameSendmail)) sfflags |= SFF_NOGWFILES; if (!bitnset(DBS_WORLDWRITABLEINCLUDEFILE, DontBlameSendmail)) sfflags |= SFF_NOWWFILES; } /* ** If RunAsUser set, won't be able to run programs as user ** so mark them as unsafe unless the administrator knows better. */ if ((geteuid() != 0 || RunAsUid != 0) && !bitnset(DBS_NONROOTSAFEADDR, DontBlameSendmail)) { if (tTd(27, 4)) sm_dprintf("include: not safe (euid=%d, RunAsUid=%d)\n", (int) geteuid(), (int) RunAsUid); ctladdr->q_flags |= QUNSAFEADDR; } ca = getctladdr(ctladdr); if (ca == NULL || (ca->q_uid == DefUid && ca->q_gid == 0)) { uid = DefUid; gid = DefGid; user = DefUser; } else { uid = ca->q_uid; gid = ca->q_gid; user = ca->q_user; } #if MAILER_SETUID_METHOD != USE_SETUID saveduid = geteuid(); savedgid = getegid(); if (saveduid == 0) { if (!DontInitGroups) { if (initgroups(user, gid) == -1) { rval = EAGAIN; syserr("include: initgroups(%s, %d) failed", user, gid); goto resetuid; } } else { GIDSET_T gidset[1]; gidset[0] = gid; if (setgroups(1, gidset) == -1) { rval = EAGAIN; syserr("include: setgroups() failed"); goto resetuid; } } if (gid != 0 && setgid(gid) < -1) { rval = EAGAIN; syserr("setgid(%d) failure", gid); goto resetuid; } if (uid != 0) { # if MAILER_SETUID_METHOD == USE_SETEUID if (seteuid(uid) < 0) { rval = EAGAIN; syserr("seteuid(%d) failure (real=%d, eff=%d)", uid, (int) getuid(), (int) geteuid()); goto resetuid; } # endif /* MAILER_SETUID_METHOD == USE_SETEUID */ # if MAILER_SETUID_METHOD == USE_SETREUID if (setreuid(0, uid) < 0) { rval = EAGAIN; syserr("setreuid(0, %d) failure (real=%d, eff=%d)", uid, (int) getuid(), (int) geteuid()); goto resetuid; } # endif /* MAILER_SETUID_METHOD == USE_SETREUID */ } } #endif /* MAILER_SETUID_METHOD != USE_SETUID */ if (tTd(27, 9)) sm_dprintf("include: new uid = %d/%d\n", (int) getuid(), (int) geteuid()); /* ** If home directory is remote mounted but server is down, ** this can hang or give errors; use a timeout to avoid this */ if (setjmp(CtxIncludeTimeout) != 0) { ctladdr->q_state = QS_QUEUEUP; errno = 0; /* return pseudo-error code */ rval = E_SM_OPENTIMEOUT; goto resetuid; } if (TimeOuts.to_fileopen > 0) ev = sm_setevent(TimeOuts.to_fileopen, includetimeout, 0); else ev = NULL; /* check for writable parent directory */ p = strrchr(fname, '/'); if (p != NULL) { int ret; *p = '\0'; ret = safedirpath(fname, uid, gid, user, sfflags|SFF_SAFEDIRPATH, 0, 0); if (ret == 0) { /* in safe directory: relax chown & link rules */ safedir = true; sfflags |= SFF_NOPATHCHECK; } else { if (bitnset((forwarding ? DBS_FORWARDFILEINUNSAFEDIRPATH : DBS_INCLUDEFILEINUNSAFEDIRPATH), DontBlameSendmail)) sfflags |= SFF_NOPATHCHECK; else if (bitnset((forwarding ? DBS_FORWARDFILEINGROUPWRITABLEDIRPATH : DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH), DontBlameSendmail) && ret == E_SM_GWDIR) { setbitn(DBS_GROUPWRITABLEDIRPATHSAFE, DontBlameSendmail); ret = safedirpath(fname, uid, gid, user, sfflags|SFF_SAFEDIRPATH, 0, 0); clrbitn(DBS_GROUPWRITABLEDIRPATHSAFE, DontBlameSendmail); if (ret == 0) sfflags |= SFF_NOPATHCHECK; else sfflags |= SFF_SAFEDIRPATH; } else sfflags |= SFF_SAFEDIRPATH; if (ret > E_PSEUDOBASE && !bitnset((forwarding ? DBS_FORWARDFILEINUNSAFEDIRPATHSAFE : DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE), DontBlameSendmail)) { if (LogLevel > 11) sm_syslog(LOG_INFO, e->e_id, "%s: unsafe directory path, marked unsafe", shortenstring(fname, MAXSHORTSTR)); ctladdr->q_flags |= QUNSAFEADDR; } } *p = '/'; } /* allow links only in unwritable directories */ if (!safedir && !bitnset((forwarding ? DBS_LINKEDFORWARDFILEINWRITABLEDIR : DBS_LINKEDINCLUDEFILEINWRITABLEDIR), DontBlameSendmail)) sfflags |= SFF_NOLINK; rval = safefile(fname, uid, gid, user, sfflags, S_IREAD, &st); if (rval != 0) { /* don't use this :include: file */ if (tTd(27, 4)) sm_dprintf("include: not safe (uid=%d): %s\n", (int) uid, sm_errstring(rval)); } else if ((fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, fname, SM_IO_RDONLY, NULL)) == NULL) { rval = errno; if (tTd(27, 4)) sm_dprintf("include: open: %s\n", sm_errstring(rval)); } else if (filechanged(fname, sm_io_getinfo(fp,SM_IO_WHAT_FD, NULL), &st)) { rval = E_SM_FILECHANGE; if (tTd(27, 4)) sm_dprintf("include: file changed after open\n"); } if (ev != NULL) sm_clrevent(ev); resetuid: #if HASSETREUID || USESETEUID if (saveduid == 0) { if (uid != 0) { # if USESETEUID if (seteuid(0) < 0) syserr("!seteuid(0) failure (real=%d, eff=%d)", (int) getuid(), (int) geteuid()); # else /* USESETEUID */ if (setreuid(-1, 0) < 0) syserr("!setreuid(-1, 0) failure (real=%d, eff=%d)", (int) getuid(), (int) geteuid()); if (setreuid(RealUid, 0) < 0) syserr("!setreuid(%d, 0) failure (real=%d, eff=%d)", (int) RealUid, (int) getuid(), (int) geteuid()); # endif /* USESETEUID */ } if (setgid(savedgid) < 0) syserr("!setgid(%d) failure (real=%d eff=%d)", (int) savedgid, (int) getgid(), (int) getegid()); } #endif /* HASSETREUID || USESETEUID */ if (tTd(27, 9)) sm_dprintf("include: reset uid = %d/%d\n", (int) getuid(), (int) geteuid()); if (rval == E_SM_OPENTIMEOUT) usrerr("451 4.4.1 open timeout on %s", fname); if (fp == NULL) return rval; if (fstat(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), &st) < 0) { rval = errno; syserr("Cannot fstat %s!", fname); (void) sm_io_close(fp, SM_TIME_DEFAULT); return rval; } /* if path was writable, check to avoid file giveaway tricks */ safechown = chownsafe(sm_io_getinfo(fp, SM_IO_WHAT_FD, NULL), safedir); if (tTd(27, 6)) sm_dprintf("include: parent of %s is %s, chown is %ssafe\n", fname, safedir ? "safe" : "dangerous", safechown ? "" : "un"); /* if no controlling user or coming from an alias delivery */ if (safechown && (ca == NULL || (ca->q_uid == DefUid && ca->q_gid == 0))) { ctladdr->q_uid = st.st_uid; ctladdr->q_gid = st.st_gid; ctladdr->q_flags |= QGOODUID; } if (ca != NULL && ca->q_uid == st.st_uid) { /* optimization -- avoid getpwuid if we already have info */ ctladdr->q_flags |= ca->q_flags & QBOGUSSHELL; ctladdr->q_ruser = ca->q_ruser; } else if (!forwarding) { register struct passwd *pw; pw = sm_getpwuid(st.st_uid); if (pw == NULL) { ctladdr->q_uid = st.st_uid; ctladdr->q_flags |= QBOGUSSHELL; } else { char *sh; ctladdr->q_ruser = sm_rpool_strdup_x(e->e_rpool, pw->pw_name); if (safechown) sh = pw->pw_shell; else sh = "/SENDMAIL/ANY/SHELL/"; if (!usershellok(pw->pw_name, sh)) { if (LogLevel > 11) sm_syslog(LOG_INFO, e->e_id, "%s: user %s has bad shell %s, marked %s", shortenstring(fname, MAXSHORTSTR), pw->pw_name, sh, safechown ? "bogus" : "unsafe"); if (safechown) ctladdr->q_flags |= QBOGUSSHELL; else ctladdr->q_flags |= QUNSAFEADDR; } } } if (bitset(EF_VRFYONLY, e->e_flags)) { /* don't do any more now */ ctladdr->q_state = QS_VERIFIED; e->e_nrcpts++; (void) sm_io_close(fp, SM_TIME_DEFAULT); return rval; } /* ** Check to see if some bad guy can write this file ** ** Group write checking could be more clever, e.g., ** guessing as to which groups are actually safe ("sys" ** may be; "user" probably is not). */ mode = S_IWOTH; if (!bitnset((forwarding ? DBS_GROUPWRITABLEFORWARDFILESAFE : DBS_GROUPWRITABLEINCLUDEFILESAFE), DontBlameSendmail)) mode |= S_IWGRP; if (bitset(mode, st.st_mode)) { if (tTd(27, 6)) sm_dprintf("include: %s is %s writable, marked unsafe\n", shortenstring(fname, MAXSHORTSTR), bitset(S_IWOTH, st.st_mode) ? "world" : "group"); if (LogLevel > 11) sm_syslog(LOG_INFO, e->e_id, "%s: %s writable %s file, marked unsafe", shortenstring(fname, MAXSHORTSTR), bitset(S_IWOTH, st.st_mode) ? "world" : "group", forwarding ? "forward" : ":include:"); ctladdr->q_flags |= QUNSAFEADDR; } /* read the file -- each line is a comma-separated list. */ FileName = fname; LineNumber = 0; ctladdr->q_flags &= ~QSELFREF; nincludes = 0; - while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL && + while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0 && !maxreached) { fixcrlf(buf, true); LineNumber++; if (buf[0] == '#' || buf[0] == '\0') continue; /* #@# introduces a comment anywhere */ /* for Japanese character sets */ for (p = buf; (p = strchr(++p, '#')) != NULL; ) { if (p[1] == '@' && p[2] == '#' && isascii(p[-1]) && isspace(p[-1]) && (p[3] == '\0' || (isascii(p[3]) && isspace(p[3])))) { --p; while (p > buf && isascii(p[-1]) && isspace(p[-1])) --p; p[0] = '\0'; break; } } if (buf[0] == '\0') continue; e->e_to = NULL; message("%s to %s", forwarding ? "forwarding" : "sending", buf); if (forwarding && LogLevel > 10) sm_syslog(LOG_INFO, e->e_id, "forward %.200s => %s", oldto, shortenstring(buf, MAXSHORTSTR)); nincludes += sendtolist(buf, ctladdr, sendq, aliaslevel + 1, e); if (forwarding && MaxForwardEntries > 0 && nincludes >= MaxForwardEntries) { /* just stop reading and processing further entries */ #if 0 /* additional: (?) */ ctladdr->q_state = QS_DONTSEND; #endif /* 0 */ syserr("Attempt to forward to more than %d addresses (in %s)!", MaxForwardEntries, fname); maxreached = true; } } if (sm_io_error(fp) && tTd(27, 3)) sm_dprintf("include: read error: %s\n", sm_errstring(errno)); if (nincludes > 0 && !bitset(QSELFREF, ctladdr->q_flags)) { if (aliaslevel <= MaxAliasRecursion || ctladdr->q_state != QS_BADADDR) { ctladdr->q_state = QS_DONTSEND; if (tTd(27, 5)) { sm_dprintf("include: QS_DONTSEND "); printaddr(sm_debug_file(), ctladdr, false); } } } (void) sm_io_close(fp, SM_TIME_DEFAULT); FileName = oldfilename; LineNumber = oldlinenumber; e->e_to = oldto; return rval; } static void includetimeout(ignore) int ignore; { /* ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ errno = ETIMEDOUT; longjmp(CtxIncludeTimeout, 1); } /* ** SENDTOARGV -- send to an argument vector. ** ** Parameters: ** argv -- argument vector to send to. ** e -- the current envelope. ** ** Returns: ** none. ** ** Side Effects: ** puts all addresses on the argument vector onto the ** send queue. */ void sendtoargv(argv, e) register char **argv; register ENVELOPE *e; { register char *p; while ((p = *argv++) != NULL) (void) sendtolist(p, NULLADDR, &e->e_sendqueue, 0, e); } /* ** GETCTLADDR -- get controlling address from an address header. ** ** If none, get one corresponding to the effective userid. ** ** Parameters: ** a -- the address to find the controller of. ** ** Returns: ** the controlling address. */ ADDRESS * getctladdr(a) register ADDRESS *a; { while (a != NULL && !bitset(QGOODUID, a->q_flags)) a = a->q_alias; return a; } /* ** SELF_REFERENCE -- check to see if an address references itself ** ** The check is done through a chain of aliases. If it is part of ** a loop, break the loop at the "best" address, that is, the one ** that exists as a real user. ** ** This is to handle the case of: ** awc: Andrew.Chang ** Andrew.Chang: awc@mail.server ** which is a problem only on mail.server. ** ** Parameters: ** a -- the address to check. ** ** Returns: ** The address that should be retained. */ static ADDRESS * self_reference(a) ADDRESS *a; { ADDRESS *b; /* top entry in self ref loop */ ADDRESS *c; /* entry that point to a real mail box */ if (tTd(27, 1)) sm_dprintf("self_reference(%s)\n", a->q_paddr); for (b = a->q_alias; b != NULL; b = b->q_alias) { if (sameaddr(a, b)) break; } if (b == NULL) { if (tTd(27, 1)) sm_dprintf("\t... no self ref\n"); return NULL; } /* ** Pick the first address that resolved to a real mail box ** i.e has a mbdb entry. The returned value will be marked ** QSELFREF in recipient(), which in turn will disable alias() ** from marking it as QS_IS_DEAD(), which mean it will be used ** as a deliverable address. ** ** The 2 key thing to note here are: ** 1) we are in a recursive call sequence: ** alias->sendtolist->recipient->alias ** 2) normally, when we return back to alias(), the address ** will be marked QS_EXPANDED, since alias() assumes the ** expanded form will be used instead of the current address. ** This behaviour is turned off if the address is marked ** QSELFREF. We set QSELFREF when we return to recipient(). */ c = a; while (c != NULL) { if (tTd(27, 10)) sm_dprintf(" %s", c->q_user); if (bitnset(M_HASPWENT, c->q_mailer->m_flags)) { SM_MBDB_T user; if (tTd(27, 2)) sm_dprintf("\t... getpwnam(%s)... ", c->q_user); if (sm_mbdb_lookup(c->q_user, &user) == EX_OK) { if (tTd(27, 2)) sm_dprintf("found\n"); /* ought to cache results here */ if (sameaddr(b, c)) return b; else return c; } if (tTd(27, 2)) sm_dprintf("failed\n"); } else { /* if local delivery, compare usernames */ if (bitnset(M_LOCALMAILER, c->q_mailer->m_flags) && b->q_mailer == c->q_mailer) { if (tTd(27, 2)) sm_dprintf("\t... local match (%s)\n", c->q_user); if (sameaddr(b, c)) return b; else return c; } } if (tTd(27, 10)) sm_dprintf("\n"); c = c->q_alias; } if (tTd(27, 1)) sm_dprintf("\t... cannot break loop for \"%s\"\n", a->q_paddr); return NULL; } Index: head/contrib/sendmail/src/savemail.c =================================================================== --- head/contrib/sendmail/src/savemail.c (revision 249728) +++ head/contrib/sendmail/src/savemail.c (revision 249729) @@ -1,1773 +1,1816 @@ /* - * Copyright (c) 1998-2003, 2006 Sendmail, Inc. and its suppliers. + * Copyright (c) 1998-2003, 2006, 2012, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: savemail.c,v 8.315 2012/02/27 17:43:03 gshapiro Exp $") +SM_RCSID("@(#)$Id: savemail.c,v 8.318 2013/03/12 15:24:54 ca Exp $") static bool errbody __P((MCI *, ENVELOPE *, char *)); static bool pruneroute __P((char *)); /* ** SAVEMAIL -- Save mail on error ** ** If mailing back errors, mail it back to the originator ** together with an error message; otherwise, just put it in ** dead.letter in the user's home directory (if he exists on ** this machine). ** ** Parameters: ** e -- the envelope containing the message in error. ** sendbody -- if true, also send back the body of the ** message; otherwise just send the header. ** ** Returns: ** true if savemail panic'ed, (i.e., the data file should ** be preserved by dropenvelope()) ** ** Side Effects: ** Saves the letter, by writing or mailing it back to the ** sender, or by putting it in dead.letter in her home ** directory. */ /* defines for state machine */ #define ESM_REPORT 0 /* report to sender's terminal */ #define ESM_MAIL 1 /* mail back to sender */ #define ESM_QUIET 2 /* mail has already been returned */ #define ESM_DEADLETTER 3 /* save in ~/dead.letter */ #define ESM_POSTMASTER 4 /* return to postmaster */ #define ESM_DEADLETTERDROP 5 /* save in DeadLetterDrop */ #define ESM_PANIC 6 /* call loseqfile() */ #define ESM_DONE 7 /* message is successfully delivered */ bool savemail(e, sendbody) register ENVELOPE *e; bool sendbody; { register SM_FILE_T *fp; bool panic = false; int state; auto ADDRESS *q = NULL; register char *p; MCI mcibuf; int flags; long sff; char buf[MAXLINE + 1]; char dlbuf[MAXPATHLEN]; SM_MBDB_T user; if (tTd(6, 1)) { sm_dprintf("\nsavemail, errormode = %c, id = %s, ExitStat = %d\n e_from=", e->e_errormode, e->e_id == NULL ? "NONE" : e->e_id, ExitStat); printaddr(sm_debug_file(), &e->e_from, false); } if (e->e_id == NULL) { /* can't return a message with no id */ return panic; } /* ** In the unhappy event we don't know who to return the mail ** to, make someone up. */ if (e->e_from.q_paddr == NULL) { e->e_sender = "Postmaster"; if (parseaddr(e->e_sender, &e->e_from, RF_COPYPARSE|RF_SENDERADDR, '\0', NULL, e, false) == NULL) { syserr("553 5.3.5 Cannot parse Postmaster!"); finis(true, true, EX_SOFTWARE); } } e->e_to = NULL; /* ** Basic state machine. ** ** This machine runs through the following states: ** ** ESM_QUIET Errors have already been printed iff the ** sender is local. ** ESM_REPORT Report directly to the sender's terminal. ** ESM_MAIL Mail response to the sender. ** ESM_DEADLETTER Save response in ~/dead.letter. ** ESM_POSTMASTER Mail response to the postmaster. ** ESM_DEADLETTERDROP ** If DeadLetterDrop set, save it there. ** ESM_PANIC Save response anywhere possible. */ /* determine starting state */ switch (e->e_errormode) { case EM_WRITE: state = ESM_REPORT; break; case EM_BERKNET: case EM_MAIL: state = ESM_MAIL; break; case EM_PRINT: case '\0': state = ESM_QUIET; break; case EM_QUIET: /* no need to return anything at all */ return panic; default: syserr("554 5.3.0 savemail: bogus errormode x%x", e->e_errormode); state = ESM_MAIL; break; } /* if this is already an error response, send to postmaster */ if (bitset(EF_RESPONSE, e->e_flags)) { if (e->e_parent != NULL && bitset(EF_RESPONSE, e->e_parent->e_flags)) { /* got an error sending a response -- can it */ return panic; } state = ESM_POSTMASTER; } while (state != ESM_DONE) { if (tTd(6, 5)) sm_dprintf(" state %d\n", state); switch (state) { case ESM_QUIET: if (bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags)) state = ESM_DEADLETTER; else state = ESM_MAIL; break; case ESM_REPORT: /* ** If the user is still logged in on the same terminal, ** then write the error messages back to hir (sic). */ #if USE_TTYPATH p = ttypath(); #else /* USE_TTYPATH */ p = NULL; #endif /* USE_TTYPATH */ if (p == NULL || sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, p, SM_IO_WRONLY, NULL, smioout) == NULL) { state = ESM_MAIL; break; } expand("\201n", buf, sizeof(buf), e); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\r\nMessage from %s...\r\n", buf); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Errors occurred while sending mail.\r\n"); if (e->e_xfp != NULL) { (void) bfrewind(e->e_xfp); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Transcript follows:\r\n"); while (sm_io_fgets(e->e_xfp, SM_TIME_DEFAULT, - buf, sizeof(buf)) != NULL && + buf, sizeof(buf)) >= 0 && !sm_io_error(smioout)) (void) sm_io_fputs(smioout, SM_TIME_DEFAULT, buf); } else { syserr("Cannot open %s", queuename(e, XSCRPT_LETTER)); (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Transcript of session is unavailable.\r\n"); } (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Original message will be saved in dead.letter.\r\n"); state = ESM_DEADLETTER; break; case ESM_MAIL: /* ** If mailing back, do it. ** Throw away all further output. Don't alias, ** since this could cause loops, e.g., if joe ** mails to joe@x, and for some reason the network ** for @x is down, then the response gets sent to ** joe@x, which gives a response, etc. Also force ** the mail to be delivered even if a version of ** it has already been sent to the sender. ** ** If this is a configuration or local software ** error, send to the local postmaster as well, ** since the originator can't do anything ** about it anyway. Note that this is a full ** copy of the message (intentionally) so that ** the Postmaster can forward things along. */ if (ExitStat == EX_CONFIG || ExitStat == EX_SOFTWARE) { (void) sendtolist("postmaster", NULLADDR, &e->e_errorqueue, 0, e); } if (!emptyaddr(&e->e_from)) { char from[TOBUFSIZE]; if (sm_strlcpy(from, e->e_from.q_paddr, sizeof(from)) >= sizeof(from)) { state = ESM_POSTMASTER; break; } if (!DontPruneRoutes) (void) pruneroute(from); (void) sendtolist(from, NULLADDR, &e->e_errorqueue, 0, e); } /* ** Deliver a non-delivery report to the ** Postmaster-designate (not necessarily ** Postmaster). This does not include the ** body of the message, for privacy reasons. ** You really shouldn't need this. */ e->e_flags |= EF_PM_NOTIFY; /* check to see if there are any good addresses */ for (q = e->e_errorqueue; q != NULL; q = q->q_next) { if (QS_IS_SENDABLE(q->q_state)) break; } if (q == NULL) { /* this is an error-error */ state = ESM_POSTMASTER; break; } if (returntosender(e->e_message, e->e_errorqueue, sendbody ? RTSF_SEND_BODY : RTSF_NO_BODY, e) == 0) { state = ESM_DONE; break; } /* didn't work -- return to postmaster */ state = ESM_POSTMASTER; break; case ESM_POSTMASTER: /* ** Similar to previous case, but to system postmaster. */ q = NULL; expand(DoubleBounceAddr, buf, sizeof(buf), e); /* ** Just drop it on the floor if DoubleBounceAddr ** expands to an empty string. */ if (*buf == '\0') { state = ESM_DONE; break; } if (sendtolist(buf, NULLADDR, &q, 0, e) <= 0) { syserr("553 5.3.0 cannot parse %s!", buf); ExitStat = EX_SOFTWARE; state = ESM_DEADLETTERDROP; break; } flags = RTSF_PM_BOUNCE; if (sendbody) flags |= RTSF_SEND_BODY; if (returntosender(e->e_message, q, flags, e) == 0) { state = ESM_DONE; break; } /* didn't work -- last resort */ state = ESM_DEADLETTERDROP; break; case ESM_DEADLETTER: /* ** Save the message in dead.letter. ** If we weren't mailing back, and the user is ** local, we should save the message in ** ~/dead.letter so that the poor person doesn't ** have to type it over again -- and we all know ** what poor typists UNIX users are. */ p = NULL; if (bitnset(M_HASPWENT, e->e_from.q_mailer->m_flags)) { if (e->e_from.q_home != NULL) p = e->e_from.q_home; else if (sm_mbdb_lookup(e->e_from.q_user, &user) == EX_OK && *user.mbdb_homedir != '\0') p = user.mbdb_homedir; } if (p == NULL || e->e_dfp == NULL) { /* no local directory or no data file */ state = ESM_MAIL; break; } /* we have a home directory; write dead.letter */ macdefine(&e->e_macro, A_TEMP, 'z', p); /* get the sender for the UnixFromLine */ p = macvalue('g', e); macdefine(&e->e_macro, A_PERM, 'g', e->e_sender); expand("\201z/dead.letter", dlbuf, sizeof(dlbuf), e); sff = SFF_CREAT|SFF_REGONLY|SFF_RUNASREALUID; if (RealUid == 0) sff |= SFF_ROOTOK; e->e_to = dlbuf; if (writable(dlbuf, NULL, sff) && mailfile(dlbuf, FileMailer, NULL, sff, e) == EX_OK) { int oldverb = Verbose; if (OpMode != MD_DAEMON && OpMode != MD_SMTP) Verbose = 1; if (Verbose > 0) message("Saved message in %s", dlbuf); Verbose = oldverb; macdefine(&e->e_macro, A_PERM, 'g', p); state = ESM_DONE; break; } macdefine(&e->e_macro, A_PERM, 'g', p); state = ESM_MAIL; break; case ESM_DEADLETTERDROP: /* ** Log the mail in DeadLetterDrop file. */ if (e->e_class < 0) { state = ESM_DONE; break; } if ((SafeFileEnv != NULL && SafeFileEnv[0] != '\0') || DeadLetterDrop == NULL || DeadLetterDrop[0] == '\0') { state = ESM_PANIC; break; } sff = SFF_CREAT|SFF_REGONLY|SFF_ROOTOK|SFF_OPENASROOT|SFF_MUSTOWN; if (!writable(DeadLetterDrop, NULL, sff) || (fp = safefopen(DeadLetterDrop, O_WRONLY|O_APPEND, FileMode, sff)) == NULL) { state = ESM_PANIC; break; } memset(&mcibuf, '\0', sizeof(mcibuf)); mcibuf.mci_out = fp; mcibuf.mci_mailer = FileMailer; if (bitnset(M_7BITS, FileMailer->m_flags)) mcibuf.mci_flags |= MCIF_7BIT; /* get the sender for the UnixFromLine */ p = macvalue('g', e); macdefine(&e->e_macro, A_PERM, 'g', e->e_sender); if (!putfromline(&mcibuf, e) || !(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER) || !(*e->e_putbody)(&mcibuf, e, NULL) || !putline("\n", &mcibuf) || sm_io_flush(fp, SM_TIME_DEFAULT) == SM_IO_EOF || sm_io_error(fp) || sm_io_close(fp, SM_TIME_DEFAULT) < 0) state = ESM_PANIC; else { int oldverb = Verbose; if (OpMode != MD_DAEMON && OpMode != MD_SMTP) Verbose = 1; if (Verbose > 0) message("Saved message in %s", DeadLetterDrop); Verbose = oldverb; if (LogLevel > 3) sm_syslog(LOG_NOTICE, e->e_id, "Saved message in %s", DeadLetterDrop); state = ESM_DONE; } macdefine(&e->e_macro, A_PERM, 'g', p); break; default: syserr("554 5.3.5 savemail: unknown state %d", state); /* FALLTHROUGH */ case ESM_PANIC: /* leave the locked queue & transcript files around */ loseqfile(e, "savemail panic"); panic = true; errno = 0; syserr("554 savemail: cannot save rejected email anywhere"); state = ESM_DONE; break; } } return panic; } /* ** RETURNTOSENDER -- return a message to the sender with an error. ** ** Parameters: ** msg -- the explanatory message. ** returnq -- the queue of people to send the message to. ** flags -- flags tweaking the operation: ** RTSF_SENDBODY -- include body of message (otherwise ** just send the header). ** RTSF_PMBOUNCE -- this is a postmaster bounce. ** e -- the current envelope. ** ** Returns: ** zero -- if everything went ok. ** else -- some error. ** ** Side Effects: ** Returns the current message to the sender via mail. */ #define MAXRETURNS 6 /* max depth of returning messages */ #define ERRORFUDGE 1024 /* nominal size of error message text */ int returntosender(msg, returnq, flags, e) char *msg; ADDRESS *returnq; int flags; register ENVELOPE *e; { int ret; register ENVELOPE *ee; ENVELOPE *oldcur = CurEnv; ENVELOPE errenvelope; static int returndepth = 0; register ADDRESS *q; char *p; char buf[MAXNAME + 1]; if (returnq == NULL) return -1; if (msg == NULL) msg = "Unable to deliver mail"; if (tTd(6, 1)) { sm_dprintf("\n*** Return To Sender: msg=\"%s\", depth=%d, e=%p, returnq=", msg, returndepth, e); printaddr(sm_debug_file(), returnq, true); if (tTd(6, 20)) { sm_dprintf("Sendq="); printaddr(sm_debug_file(), e->e_sendqueue, true); } } if (++returndepth >= MAXRETURNS) { if (returndepth != MAXRETURNS) syserr("554 5.3.0 returntosender: infinite recursion on %s", returnq->q_paddr); /* don't "unrecurse" and fake a clean exit */ /* returndepth--; */ return 0; } macdefine(&e->e_macro, A_PERM, 'g', e->e_sender); macdefine(&e->e_macro, A_PERM, 'u', NULL); /* initialize error envelope */ ee = newenvelope(&errenvelope, e, sm_rpool_new_x(NULL)); macdefine(&ee->e_macro, A_PERM, 'a', "\201b"); macdefine(&ee->e_macro, A_PERM, 'r', ""); macdefine(&ee->e_macro, A_PERM, 's', "localhost"); macdefine(&ee->e_macro, A_PERM, '_', "localhost"); clrsessenvelope(ee); ee->e_puthdr = putheader; ee->e_putbody = errbody; ee->e_flags |= EF_RESPONSE|EF_METOO; if (!bitset(EF_OLDSTYLE, e->e_flags)) ee->e_flags &= ~EF_OLDSTYLE; if (bitset(EF_DONT_MIME, e->e_flags)) { ee->e_flags |= EF_DONT_MIME; /* ** If we can't convert to MIME and we don't pass ** 8-bit, we can't send the body. */ if (bitset(EF_HAS8BIT, e->e_flags) && !bitset(MM_PASS8BIT, MimeMode)) flags &= ~RTSF_SEND_BODY; } ee->e_sendqueue = returnq; ee->e_msgsize = 0; if (bitset(RTSF_SEND_BODY, flags) && !bitset(PRIV_NOBODYRETN, PrivacyFlags)) ee->e_msgsize = ERRORFUDGE + e->e_msgsize; else ee->e_flags |= EF_NO_BODY_RETN; if (!setnewqueue(ee)) { syserr("554 5.3.0 returntosender: cannot select queue for %s", returnq->q_paddr); ExitStat = EX_UNAVAILABLE; returndepth--; return -1; } initsys(ee); #if NAMED_BIND _res.retry = TimeOuts.res_retry[RES_TO_FIRST]; _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST]; #endif /* NAMED_BIND */ for (q = returnq; q != NULL; q = q->q_next) { if (QS_IS_BADADDR(q->q_state)) continue; q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS); q->q_flags |= QPINGONFAILURE; if (!QS_IS_DEAD(q->q_state)) ee->e_nrcpts++; if (q->q_alias == NULL) addheader("To", q->q_paddr, 0, ee, true); } if (LogLevel > 5) { if (bitset(EF_RESPONSE, e->e_flags)) p = "return to sender"; else if (bitset(EF_WARNING, e->e_flags)) p = "sender notify"; else if (bitset(RTSF_PM_BOUNCE, flags)) p = "postmaster notify"; else p = "DSN"; sm_syslog(LOG_INFO, e->e_id, "%s: %s: %s", ee->e_id, p, shortenstring(msg, MAXSHORTSTR)); } if (SendMIMEErrors) { addheader("MIME-Version", "1.0", 0, ee, true); (void) sm_snprintf(buf, sizeof(buf), "%s.%ld/%.100s", ee->e_id, (long)curtime(), MyHostName); ee->e_msgboundary = sm_rpool_strdup_x(ee->e_rpool, buf); (void) sm_snprintf(buf, sizeof(buf), #if DSN "multipart/report; report-type=delivery-status;\n\tboundary=\"%s\"", #else /* DSN */ "multipart/mixed; boundary=\"%s\"", #endif /* DSN */ ee->e_msgboundary); addheader("Content-Type", buf, 0, ee, true); p = hvalue("Content-Transfer-Encoding", e->e_header); if (p != NULL && sm_strcasecmp(p, "binary") != 0) p = NULL; if (p == NULL && bitset(EF_HAS8BIT, e->e_flags)) p = "8bit"; if (p != NULL) addheader("Content-Transfer-Encoding", p, 0, ee, true); } if (strncmp(msg, "Warning:", 8) == 0) { addheader("Subject", msg, 0, ee, true); p = "warning-timeout"; } else if (strncmp(msg, "Postmaster warning:", 19) == 0) { addheader("Subject", msg, 0, ee, true); p = "postmaster-warning"; } else if (strcmp(msg, "Return receipt") == 0) { addheader("Subject", msg, 0, ee, true); p = "return-receipt"; } else if (bitset(RTSF_PM_BOUNCE, flags)) { (void) sm_snprintf(buf, sizeof(buf), "Postmaster notify: see transcript for details"); addheader("Subject", buf, 0, ee, true); p = "postmaster-notification"; } else { (void) sm_snprintf(buf, sizeof(buf), "Returned mail: see transcript for details"); addheader("Subject", buf, 0, ee, true); p = "failure"; } (void) sm_snprintf(buf, sizeof(buf), "auto-generated (%s)", p); addheader("Auto-Submitted", buf, 0, ee, true); /* fake up an address header for the from person */ expand("\201n", buf, sizeof(buf), e); if (parseaddr(buf, &ee->e_from, RF_COPYALL|RF_SENDERADDR, '\0', NULL, e, false) == NULL) { syserr("553 5.3.5 Can't parse myself!"); ExitStat = EX_SOFTWARE; returndepth--; return -1; } ee->e_from.q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS); ee->e_from.q_flags |= QPINGONFAILURE; ee->e_sender = ee->e_from.q_paddr; /* push state into submessage */ CurEnv = ee; macdefine(&ee->e_macro, A_PERM, 'f', "\201n"); macdefine(&ee->e_macro, A_PERM, 'x', "Mail Delivery Subsystem"); eatheader(ee, true, true); /* mark statistics */ markstats(ee, NULLADDR, STATS_NORMAL); /* actually deliver the error message */ sendall(ee, SM_DELIVER); (void) dropenvelope(ee, true, false); /* check for delivery errors */ ret = -1; if (ee->e_parent == NULL || !bitset(EF_RESPONSE, ee->e_parent->e_flags)) { ret = 0; } else { for (q = ee->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_ATTEMPTED(q->q_state)) { ret = 0; break; } } } /* restore state */ sm_rpool_free(ee->e_rpool); CurEnv = oldcur; returndepth--; return ret; } /* ** ERRBODY -- output the body of an error message. ** ** Typically this is a copy of the transcript plus a copy of the ** original offending message. ** ** Parameters: ** mci -- the mailer connection information. ** e -- the envelope we are working in. ** separator -- any possible MIME separator (unused). ** ** Returns: ** true iff body was written successfully ** ** Side Effects: ** Outputs the body of an error message. */ /* ARGSUSED2 */ static bool errbody(mci, e, separator) register MCI *mci; register ENVELOPE *e; char *separator; { bool printheader; bool sendbody; bool pm_notify; int save_errno; register SM_FILE_T *xfile; char *p; register ADDRESS *q = NULL; char actual[MAXLINE]; char buf[MAXLINE]; if (bitset(MCIF_INHEADER, mci->mci_flags)) { if (!putline("", mci)) goto writeerr; mci->mci_flags &= ~MCIF_INHEADER; } if (e->e_parent == NULL) { syserr("errbody: null parent"); if (!putline(" ----- Original message lost -----\n", mci)) goto writeerr; return true; } /* ** Output MIME header. */ if (e->e_msgboundary != NULL) { (void) sm_strlcpyn(buf, sizeof(buf), 2, "--", e->e_msgboundary); if (!putline("This is a MIME-encapsulated message", mci) || !putline("", mci) || !putline(buf, mci) || !putline("", mci)) goto writeerr; } /* ** Output introductory information. */ pm_notify = false; p = hvalue("subject", e->e_header); if (p != NULL && strncmp(p, "Postmaster ", 11) == 0) pm_notify = true; else { for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_BADADDR(q->q_state)) break; } } if (!pm_notify && q == NULL && !bitset(EF_FATALERRS|EF_SENDRECEIPT, e->e_parent->e_flags)) { if (!putline(" **********************************************", mci) || !putline(" ** THIS IS A WARNING MESSAGE ONLY **", mci) || !putline(" ** YOU DO NOT NEED TO RESEND YOUR MESSAGE **", mci) || !putline(" **********************************************", mci) || !putline("", mci)) goto writeerr; } (void) sm_snprintf(buf, sizeof(buf), "The original message was received at %s", arpadate(ctime(&e->e_parent->e_ctime))); if (!putline(buf, mci)) goto writeerr; expand("from \201_", buf, sizeof(buf), e->e_parent); if (!putline(buf, mci)) goto writeerr; /* include id in postmaster copies */ if (pm_notify && e->e_parent->e_id != NULL) { (void) sm_strlcpyn(buf, sizeof(buf), 2, "with id ", e->e_parent->e_id); if (!putline(buf, mci)) goto writeerr; } if (!putline("", mci)) goto writeerr; /* ** Output error message header (if specified and available). */ if (ErrMsgFile != NULL && !bitset(EF_SENDRECEIPT, e->e_parent->e_flags)) { if (*ErrMsgFile == '/') { long sff = SFF_ROOTOK|SFF_REGONLY; if (DontLockReadFiles) sff |= SFF_NOLOCK; if (!bitnset(DBS_ERRORHEADERINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_SAFEDIRPATH; xfile = safefopen(ErrMsgFile, O_RDONLY, 0444, sff); if (xfile != NULL) { while (sm_io_fgets(xfile, SM_TIME_DEFAULT, buf, - sizeof(buf)) != NULL) + sizeof(buf)) >= 0) { int lbs; bool putok; char *lbp; lbs = sizeof(buf); lbp = translate_dollars(buf, buf, &lbs); expand(lbp, lbp, lbs, e); putok = putline(lbp, mci); if (lbp != buf) sm_free(lbp); if (!putok) goto writeerr; } (void) sm_io_close(xfile, SM_TIME_DEFAULT); if (!putline("\n", mci)) goto writeerr; } } else { expand(ErrMsgFile, buf, sizeof(buf), e); if (!putline(buf, mci) || !putline("", mci)) goto writeerr; } } /* ** Output message introduction */ /* permanent fatal errors */ printheader = true; for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next) { if (!QS_IS_BADADDR(q->q_state) || !bitset(QPINGONFAILURE, q->q_flags)) continue; if (printheader) { if (!putline(" ----- The following addresses had permanent fatal errors -----", mci)) goto writeerr; printheader = false; } (void) sm_strlcpy(buf, shortenstring(q->q_paddr, MAXSHORTSTR), sizeof(buf)); if (!putline(buf, mci)) goto writeerr; if (q->q_rstatus != NULL) { (void) sm_snprintf(buf, sizeof(buf), " (reason: %s)", shortenstring(exitstat(q->q_rstatus), MAXSHORTSTR)); if (!putline(buf, mci)) goto writeerr; } if (q->q_alias != NULL) { (void) sm_snprintf(buf, sizeof(buf), " (expanded from: %s)", shortenstring(q->q_alias->q_paddr, MAXSHORTSTR)); if (!putline(buf, mci)) goto writeerr; } } if (!printheader && !putline("", mci)) goto writeerr; /* transient non-fatal errors */ printheader = true; for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_BADADDR(q->q_state) || !bitset(QPRIMARY, q->q_flags) || !bitset(QBYNDELAY, q->q_flags) || !bitset(QDELAYED, q->q_flags)) continue; if (printheader) { if (!putline(" ----- The following addresses had transient non-fatal errors -----", mci)) goto writeerr; printheader = false; } (void) sm_strlcpy(buf, shortenstring(q->q_paddr, MAXSHORTSTR), sizeof(buf)); if (!putline(buf, mci)) goto writeerr; if (q->q_alias != NULL) { (void) sm_snprintf(buf, sizeof(buf), " (expanded from: %s)", shortenstring(q->q_alias->q_paddr, MAXSHORTSTR)); if (!putline(buf, mci)) goto writeerr; } } if (!printheader && !putline("", mci)) goto writeerr; /* successful delivery notifications */ printheader = true; for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next) { if (QS_IS_BADADDR(q->q_state) || !bitset(QPRIMARY, q->q_flags) || bitset(QBYNDELAY, q->q_flags) || bitset(QDELAYED, q->q_flags)) continue; else if (bitset(QBYNRELAY, q->q_flags)) p = "Deliver-By notify: relayed"; else if (bitset(QBYTRACE, q->q_flags)) p = "Deliver-By trace: relayed"; else if (!bitset(QPINGONSUCCESS, q->q_flags)) continue; else if (bitset(QRELAYED, q->q_flags)) p = "relayed to non-DSN-aware mailer"; else if (bitset(QDELIVERED, q->q_flags)) { if (bitset(QEXPANDED, q->q_flags)) p = "successfully delivered to mailing list"; else p = "successfully delivered to mailbox"; } else if (bitset(QEXPANDED, q->q_flags)) p = "expanded by alias"; else continue; if (printheader) { if (!putline(" ----- The following addresses had successful delivery notifications -----", mci)) goto writeerr; printheader = false; } (void) sm_snprintf(buf, sizeof(buf), "%s (%s)", shortenstring(q->q_paddr, MAXSHORTSTR), p); if (!putline(buf, mci)) goto writeerr; if (q->q_alias != NULL) { (void) sm_snprintf(buf, sizeof(buf), " (expanded from: %s)", shortenstring(q->q_alias->q_paddr, MAXSHORTSTR)); if (!putline(buf, mci)) goto writeerr; } } if (!printheader && !putline("", mci)) goto writeerr; /* ** Output transcript of errors */ (void) sm_io_flush(smioout, SM_TIME_DEFAULT); if (e->e_parent->e_xfp == NULL) { if (!putline(" ----- Transcript of session is unavailable -----\n", mci)) goto writeerr; } else { + int blen; + printheader = true; (void) bfrewind(e->e_parent->e_xfp); if (e->e_xfp != NULL) (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT); - while (sm_io_fgets(e->e_parent->e_xfp, SM_TIME_DEFAULT, buf, - sizeof(buf)) != NULL) + while ((blen = sm_io_fgets(e->e_parent->e_xfp, SM_TIME_DEFAULT, + buf, sizeof(buf))) >= 0) { if (printheader && !putline(" ----- Transcript of session follows -----\n", mci)) goto writeerr; printheader = false; - if (!putline(buf, mci)) + if (!putxline(buf, blen, mci, PXLF_MAPFROM)) goto writeerr; } } errno = 0; #if DSN /* ** Output machine-readable version. */ if (e->e_msgboundary != NULL) { (void) sm_strlcpyn(buf, sizeof(buf), 2, "--", e->e_msgboundary); if (!putline("", mci) || !putline(buf, mci) || !putline("Content-Type: message/delivery-status", mci) || !putline("", mci)) goto writeerr; /* ** Output per-message information. */ /* original envelope id from MAIL FROM: line */ if (e->e_parent->e_envid != NULL) { (void) sm_snprintf(buf, sizeof(buf), "Original-Envelope-Id: %.800s", xuntextify(e->e_parent->e_envid)); if (!putline(buf, mci)) goto writeerr; } /* Reporting-MTA: is us (required) */ (void) sm_snprintf(buf, sizeof(buf), "Reporting-MTA: dns; %.800s", MyHostName); if (!putline(buf, mci)) goto writeerr; /* DSN-Gateway: not relevant since we are not translating */ /* Received-From-MTA: shows where we got this message from */ if (RealHostName != NULL) { /* XXX use $s for type? */ if (e->e_parent->e_from.q_mailer == NULL || (p = e->e_parent->e_from.q_mailer->m_mtatype) == NULL) p = "dns"; (void) sm_snprintf(buf, sizeof(buf), "Received-From-MTA: %s; %.800s", p, RealHostName); if (!putline(buf, mci)) goto writeerr; } /* Arrival-Date: -- when it arrived here */ (void) sm_strlcpyn(buf, sizeof(buf), 2, "Arrival-Date: ", arpadate(ctime(&e->e_parent->e_ctime))); if (!putline(buf, mci)) goto writeerr; /* Deliver-By-Date: -- when it should have been delivered */ if (IS_DLVR_BY(e->e_parent)) { time_t dbyd; dbyd = e->e_parent->e_ctime + e->e_parent->e_deliver_by; (void) sm_strlcpyn(buf, sizeof(buf), 2, "Deliver-By-Date: ", arpadate(ctime(&dbyd))); if (!putline(buf, mci)) goto writeerr; } /* ** Output per-address information. */ for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next) { char *action; if (QS_IS_BADADDR(q->q_state)) { /* RFC 1891, 6.2.6 (b) */ if (bitset(QHASNOTIFY, q->q_flags) && !bitset(QPINGONFAILURE, q->q_flags)) continue; action = "failed"; } else if (!bitset(QPRIMARY, q->q_flags)) continue; else if (bitset(QDELIVERED, q->q_flags)) { if (bitset(QEXPANDED, q->q_flags)) action = "delivered (to mailing list)"; else action = "delivered (to mailbox)"; } else if (bitset(QRELAYED, q->q_flags)) action = "relayed (to non-DSN-aware mailer)"; else if (bitset(QEXPANDED, q->q_flags)) action = "expanded (to multi-recipient alias)"; else if (bitset(QDELAYED, q->q_flags)) action = "delayed"; else if (bitset(QBYTRACE, q->q_flags)) action = "relayed (Deliver-By trace mode)"; else if (bitset(QBYNDELAY, q->q_flags)) action = "delayed (Deliver-By notify mode)"; else if (bitset(QBYNRELAY, q->q_flags)) action = "relayed (Deliver-By notify mode)"; else continue; if (!putline("", mci)) goto writeerr; /* Original-Recipient: -- passed from on high */ if (q->q_orcpt != NULL) { - (void) sm_snprintf(buf, sizeof(buf), - "Original-Recipient: %.800s", - q->q_orcpt); - if (!putline(buf, mci)) - goto writeerr; + p = strchr(q->q_orcpt, ';'); + + /* + ** p == NULL shouldn't happen due to + ** check in srvrsmtp.c + ** we could log an error in this case. + */ + + if (p != NULL) + { + *p = '\0'; + (void) sm_snprintf(buf, sizeof(buf), + "Original-Recipient: %.100s;%.700s", + q->q_orcpt, xuntextify(p + 1)); + *p = ';'; + if (!putline(buf, mci)) + goto writeerr; + } } /* Figure out actual recipient */ actual[0] = '\0'; if (q->q_user[0] != '\0') { if (q->q_mailer != NULL && q->q_mailer->m_addrtype != NULL) p = q->q_mailer->m_addrtype; else p = "rfc822"; if (sm_strcasecmp(p, "rfc822") == 0 && strchr(q->q_user, '@') == NULL) { (void) sm_snprintf(actual, sizeof(actual), "%s; %.700s@%.100s", p, q->q_user, MyHostName); } else { (void) sm_snprintf(actual, sizeof(actual), "%s; %.800s", p, q->q_user); } } /* Final-Recipient: -- the name from the RCPT command */ if (q->q_finalrcpt == NULL) { /* should never happen */ sm_syslog(LOG_ERR, e->e_id, "returntosender: q_finalrcpt is NULL"); /* try to fall back to the actual recipient */ if (actual[0] != '\0') q->q_finalrcpt = sm_rpool_strdup_x(e->e_rpool, actual); } if (q->q_finalrcpt != NULL) { (void) sm_snprintf(buf, sizeof(buf), "Final-Recipient: %s", q->q_finalrcpt); if (!putline(buf, mci)) goto writeerr; } /* X-Actual-Recipient: -- the real problem address */ if (actual[0] != '\0' && q->q_finalrcpt != NULL && !bitset(PRIV_NOACTUALRECIPIENT, PrivacyFlags) && strcmp(actual, q->q_finalrcpt) != 0) { (void) sm_snprintf(buf, sizeof(buf), "X-Actual-Recipient: %s", actual); if (!putline(buf, mci)) goto writeerr; } /* Action: -- what happened? */ (void) sm_strlcpyn(buf, sizeof(buf), 2, "Action: ", action); if (!putline(buf, mci)) goto writeerr; /* Status: -- what _really_ happened? */ if (q->q_status != NULL) p = q->q_status; else if (QS_IS_BADADDR(q->q_state)) p = "5.0.0"; else if (QS_IS_QUEUEUP(q->q_state)) p = "4.0.0"; else p = "2.0.0"; (void) sm_strlcpyn(buf, sizeof(buf), 2, "Status: ", p); if (!putline(buf, mci)) goto writeerr; /* Remote-MTA: -- who was I talking to? */ if (q->q_statmta != NULL) { if (q->q_mailer == NULL || (p = q->q_mailer->m_mtatype) == NULL) p = "dns"; (void) sm_snprintf(buf, sizeof(buf), "Remote-MTA: %s; %.800s", p, q->q_statmta); p = &buf[strlen(buf) - 1]; if (*p == '.') *p = '\0'; if (!putline(buf, mci)) goto writeerr; } /* Diagnostic-Code: -- actual result from other end */ if (q->q_rstatus != NULL) { if (q->q_mailer == NULL || (p = q->q_mailer->m_diagtype) == NULL) p = "smtp"; (void) sm_snprintf(buf, sizeof(buf), "Diagnostic-Code: %s; %.800s", p, q->q_rstatus); if (!putline(buf, mci)) goto writeerr; } /* Last-Attempt-Date: -- fine granularity */ if (q->q_statdate == (time_t) 0L) q->q_statdate = curtime(); (void) sm_strlcpyn(buf, sizeof(buf), 2, "Last-Attempt-Date: ", arpadate(ctime(&q->q_statdate))); if (!putline(buf, mci)) goto writeerr; /* Will-Retry-Until: -- for delayed messages only */ if (QS_IS_QUEUEUP(q->q_state)) { time_t xdate; xdate = e->e_parent->e_ctime + TimeOuts.to_q_return[e->e_parent->e_timeoutclass]; (void) sm_strlcpyn(buf, sizeof(buf), 2, "Will-Retry-Until: ", arpadate(ctime(&xdate))); if (!putline(buf, mci)) goto writeerr; } } } #endif /* DSN */ /* ** Output text of original message */ if (!putline("", mci)) goto writeerr; if (bitset(EF_HAS_DF, e->e_parent->e_flags)) { sendbody = !bitset(EF_NO_BODY_RETN, e->e_parent->e_flags) && !bitset(EF_NO_BODY_RETN, e->e_flags); if (e->e_msgboundary == NULL) { if (!putline( sendbody ? " ----- Original message follows -----\n" : " ----- Message header follows -----\n", mci)) { goto writeerr; } } else { (void) sm_strlcpyn(buf, sizeof(buf), 2, "--", e->e_msgboundary); if (!putline(buf, mci)) goto writeerr; (void) sm_strlcpyn(buf, sizeof(buf), 2, "Content-Type: ", sendbody ? "message/rfc822" : "text/rfc822-headers"); if (!putline(buf, mci)) goto writeerr; p = hvalue("Content-Transfer-Encoding", e->e_parent->e_header); if (p != NULL && sm_strcasecmp(p, "binary") != 0) p = NULL; if (p == NULL && bitset(EF_HAS8BIT, e->e_parent->e_flags)) p = "8bit"; if (p != NULL) { (void) sm_snprintf(buf, sizeof(buf), "Content-Transfer-Encoding: %s", p); if (!putline(buf, mci)) goto writeerr; } } if (!putline("", mci)) goto writeerr; save_errno = errno; if (!putheader(mci, e->e_parent->e_header, e->e_parent, M87F_OUTER)) goto writeerr; errno = save_errno; if (sendbody) { if (!putbody(mci, e->e_parent, e->e_msgboundary)) goto writeerr; } else if (e->e_msgboundary == NULL) { if (!putline("", mci) || !putline(" ----- Message body suppressed -----", mci)) { goto writeerr; } } } else if (e->e_msgboundary == NULL) { if (!putline(" ----- No message was collected -----\n", mci)) goto writeerr; } if (e->e_msgboundary != NULL) { (void) sm_strlcpyn(buf, sizeof(buf), 3, "--", e->e_msgboundary, "--"); if (!putline("", mci) || !putline(buf, mci)) goto writeerr; } if (!putline("", mci) || sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF) goto writeerr; /* ** Cleanup and exit */ if (errno != 0) { writeerr: syserr("errbody: I/O error"); return false; } return true; } /* ** SMTPTODSN -- convert SMTP to DSN status code ** ** Parameters: ** smtpstat -- the smtp status code (e.g., 550). ** ** Returns: ** The DSN version of the status code. ** ** Storage Management: ** smtptodsn() returns a pointer to a character string literal, ** which will remain valid forever, and thus does not need to ** be copied. Current code relies on this property. */ char * smtptodsn(smtpstat) int smtpstat; { if (smtpstat < 0) return "4.4.2"; switch (smtpstat) { case 450: /* Req mail action not taken: mailbox unavailable */ return "4.2.0"; case 451: /* Req action aborted: local error in processing */ return "4.3.0"; case 452: /* Req action not taken: insufficient sys storage */ return "4.3.1"; case 500: /* Syntax error, command unrecognized */ return "5.5.2"; case 501: /* Syntax error in parameters or arguments */ return "5.5.4"; case 502: /* Command not implemented */ return "5.5.1"; case 503: /* Bad sequence of commands */ return "5.5.1"; case 504: /* Command parameter not implemented */ return "5.5.4"; case 550: /* Req mail action not taken: mailbox unavailable */ return "5.2.0"; case 551: /* User not local; please try <...> */ return "5.1.6"; case 552: /* Req mail action aborted: exceeded storage alloc */ return "5.2.2"; case 553: /* Req action not taken: mailbox name not allowed */ return "5.1.0"; case 554: /* Transaction failed */ return "5.0.0"; } if (REPLYTYPE(smtpstat) == 2) return "2.0.0"; if (REPLYTYPE(smtpstat) == 4) return "4.0.0"; return "5.0.0"; } /* ** XTEXTIFY -- take regular text and turn it into DSN-style xtext ** ** Parameters: ** t -- the text to convert. ** taboo -- additional characters that must be encoded. ** ** Returns: ** The xtext-ified version of the same string. */ char * xtextify(t, taboo) register char *t; char *taboo; { register char *p; int l; int nbogus; static char *bp = NULL; static int bplen = 0; if (taboo == NULL) taboo = ""; /* figure out how long this xtext will have to be */ nbogus = l = 0; for (p = t; *p != '\0'; p++) { register int c = (*p & 0xff); /* ASCII dependence here -- this is the way the spec words it */ if (c < '!' || c > '~' || c == '+' || c == '\\' || c == '(' || strchr(taboo, c) != NULL) nbogus++; l++; } if (nbogus < 0) { /* since nbogus is ssize_t and wrapped, 2 * size_t would wrap */ syserr("!xtextify string too long"); } if (nbogus == 0) return t; l += nbogus * 2 + 1; /* now allocate space if necessary for the new string */ if (l > bplen) { if (bp != NULL) sm_free(bp); /* XXX */ bp = sm_pmalloc_x(l); bplen = l; } /* ok, copy the text with byte expansion */ for (p = bp; *t != '\0'; ) { register int c = (*t++ & 0xff); /* ASCII dependence here -- this is the way the spec words it */ if (c < '!' || c > '~' || c == '+' || c == '\\' || c == '(' || strchr(taboo, c) != NULL) { *p++ = '+'; *p++ = "0123456789ABCDEF"[c >> 4]; *p++ = "0123456789ABCDEF"[c & 0xf]; } else *p++ = c; } *p = '\0'; return bp; } /* ** XUNTEXTIFY -- take xtext and turn it into plain text ** ** Parameters: ** t -- the xtextified text. ** ** Returns: ** The decoded text. No attempt is made to deal with ** null strings in the resulting text. */ char * xuntextify(t) register char *t; { register char *p; int l; static char *bp = NULL; static int bplen = 0; /* heuristic -- if no plus sign, just return the input */ if (strchr(t, '+') == NULL) return t; /* xtext is always longer than decoded text */ l = strlen(t); if (l > bplen) { if (bp != NULL) sm_free(bp); /* XXX */ bp = xalloc(l); bplen = l; } /* ok, copy the text with byte compression */ for (p = bp; *t != '\0'; t++) { register int c = *t & 0xff; if (c != '+') { *p++ = c; continue; } c = *++t & 0xff; if (!isascii(c) || !isxdigit(c)) { /* error -- first digit is not hex */ usrerr("bogus xtext: +%c", c); t--; continue; } if (isdigit(c)) c -= '0'; else if (isupper(c)) c -= 'A' - 10; else c -= 'a' - 10; *p = c << 4; c = *++t & 0xff; if (!isascii(c) || !isxdigit(c)) { /* error -- second digit is not hex */ usrerr("bogus xtext: +%x%c", *p >> 4, c); t--; continue; } if (isdigit(c)) c -= '0'; else if (isupper(c)) c -= 'A' - 10; else c -= 'a' - 10; *p++ |= c; } *p = '\0'; return bp; } /* ** XTEXTOK -- check if a string is legal xtext ** ** Xtext is used in Delivery Status Notifications. The spec was ** taken from RFC 1891, ``SMTP Service Extension for Delivery ** Status Notifications''. ** ** Parameters: ** s -- the string to check. ** ** Returns: ** true -- if 's' is legal xtext. ** false -- if it has any illegal characters in it. */ bool xtextok(s) char *s; { int c; while ((c = *s++) != '\0') { if (c == '+') { c = *s++; if (!isascii(c) || !isxdigit(c)) return false; c = *s++; if (!isascii(c) || !isxdigit(c)) return false; } else if (c < '!' || c > '~' || c == '=') + return false; + } + return true; +} + +/* +** ISATOM -- check if a string is an "atom" +** +** Parameters: +** s -- the string to check. +** +** Returns: +** true -- iff s is an atom +*/ + +bool +isatom(s) + const char *s; +{ + int c; + + if (s == NULL || *s == '\0') + return false; + while ((c = *s++) != '\0') + { + if (strchr("()<>@,;:\\.[]\"", c) != NULL) + return false; + if (c < '!' || c > '~') return false; } return true; } /* ** PRUNEROUTE -- prune an RFC-822 source route ** ** Trims down a source route to the last internet-registered hop. ** This is encouraged by RFC 1123 section 5.3.3. ** ** Parameters: ** addr -- the address ** ** Returns: ** true -- address was modified ** false -- address could not be pruned ** ** Side Effects: ** modifies addr in-place */ static bool pruneroute(addr) char *addr; { #if NAMED_BIND char *start, *at, *comma; char c; int braclev; int rcode; int i; char hostbuf[BUFSIZ]; char *mxhosts[MAXMXHOSTS + 1]; /* check to see if this is really a route-addr */ if (*addr != '<' || addr[1] != '@' || addr[strlen(addr) - 1] != '>') return false; /* ** Can't simply find the first ':' is the address might be in the ** form: "<@[IPv6:::1]:user@host>" and the first ':' in inside ** the IPv6 address. */ start = addr; braclev = 0; while (*start != '\0') { if (*start == ':' && braclev <= 0) break; else if (*start == '[') braclev++; else if (*start == ']' && braclev > 0) braclev--; start++; } if (braclev > 0 || *start != ':') return false; at = strrchr(addr, '@'); if (at == NULL || at < start) return false; /* slice off the angle brackets */ i = strlen(at + 1); if (i >= sizeof(hostbuf)) return false; (void) sm_strlcpy(hostbuf, at + 1, sizeof(hostbuf)); hostbuf[i - 1] = '\0'; while (start != NULL) { if (getmxrr(hostbuf, mxhosts, NULL, false, &rcode, true, NULL) > 0) { (void) sm_strlcpy(addr + 1, start + 1, strlen(addr) - 1); return true; } c = *start; *start = '\0'; comma = strrchr(addr, ','); if (comma != NULL && comma[1] == '@' && strlen(comma + 2) < sizeof(hostbuf)) (void) sm_strlcpy(hostbuf, comma + 2, sizeof(hostbuf)); else comma = NULL; *start = c; start = comma; } #endif /* NAMED_BIND */ return false; } Index: head/contrib/sendmail/src/sendmail.h =================================================================== --- head/contrib/sendmail/src/sendmail.h (revision 249728) +++ head/contrib/sendmail/src/sendmail.h (revision 249729) @@ -1,2779 +1,2788 @@ /* - * Copyright (c) 1998-2012 Sendmail, Inc. and its suppliers. + * Copyright (c) 1998-2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. */ /* ** SENDMAIL.H -- MTA-specific definitions for sendmail. */ #ifndef _SENDMAIL_H # define _SENDMAIL_H 1 #ifndef MILTER # define MILTER 1 /* turn on MILTER by default */ #endif /* MILTER */ #ifdef _DEFINE # define EXTERN #else /* _DEFINE */ # define EXTERN extern #endif /* _DEFINE */ #include #include #include #include #include #include #include #include # ifdef EX_OK # undef EX_OK /* for SVr4.2 SMP */ # endif /* EX_OK */ #include "sendmail/sendmail.h" /* profiling? */ #if MONCONTROL # define SM_PROF(x) moncontrol(x) #else /* MONCONTROL */ # define SM_PROF(x) #endif /* MONCONTROL */ #ifdef _DEFINE # ifndef lint -SM_UNUSED(static char SmailId[]) = "@(#)$Id: sendmail.h,v 8.1096 2012/11/16 20:25:03 ca Exp $"; +SM_UNUSED(static char SmailId[]) = "@(#)$Id: sendmail.h,v 8.1101 2013/03/15 17:54:12 ca Exp $"; # endif /* ! lint */ #endif /* _DEFINE */ #include "bf.h" #include "timers.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef LOG # include #endif /* LOG */ # if NETINET || NETINET6 || NETUNIX || NETISO || NETNS || NETX25 # include # endif /* NETINET || NETINET6 || NETUNIX || NETISO || NETNS || NETX25 */ # if NETUNIX # include # endif /* NETUNIX */ # if NETINET || NETINET6 # include # endif /* NETINET || NETINET6 */ # if NETINET6 /* ** There is no standard yet for IPv6 includes. ** Specify OS specific implementation in conf.h */ # endif /* NETINET6 */ # if NETISO # include # endif /* NETISO */ # if NETNS # include # endif /* NETNS */ # if NETX25 # include # endif /* NETX25 */ # if NAMED_BIND # include # ifdef NOERROR # undef NOERROR /* avoid conflict */ # endif /* NOERROR */ # include # else /* NAMED_BIND */ # undef SM_SET_H_ERRNO # define SM_SET_H_ERRNO(err) # endif /* NAMED_BIND */ # if HESIOD # include # if !defined(HES_ER_OK) || defined(HESIOD_INTERFACES) # define HESIOD_INIT /* support for the new interface */ # endif /* !defined(HES_ER_OK) || defined(HESIOD_INTERFACES) */ # endif /* HESIOD */ #if STARTTLS # include # if !TLS_NO_RSA -# define RSA_KEYLENGTH 512 +# if _FFR_FIPSMODE +# define RSA_KEYLENGTH 1024 +# else /* _FFR_FIPSMODE */ +# define RSA_KEYLENGTH 512 +# endif /* _FFR_FIPSMODE */ # endif /* !TLS_NO_RSA */ #endif /* STARTTLS */ #if SASL /* include the sasl include files if we have them */ # if SASL == 2 || SASL >= 20000 # include # include # include # if SASL_VERSION_FULL < 0x020119 typedef int (*sasl_callback_ft)(void); # endif # else /* SASL == 2 || SASL >= 20000 */ # include # include typedef int (*sasl_callback_ft)(void); # endif /* SASL == 2 || SASL >= 20000 */ # if defined(SASL_VERSION_MAJOR) && defined(SASL_VERSION_MINOR) && defined(SASL_VERSION_STEP) # define SASL_VERSION (SASL_VERSION_MAJOR * 10000) + (SASL_VERSION_MINOR * 100) + SASL_VERSION_STEP # if SASL == 1 || SASL == 2 # undef SASL # define SASL SASL_VERSION # else /* SASL == 1 || SASL == 2 */ # if SASL != SASL_VERSION ERROR README: -DSASL (SASL) does not agree with the version of the CYRUS_SASL library (SASL_VERSION) ERROR README: see README! # endif /* SASL != SASL_VERSION */ # endif /* SASL == 1 || SASL == 2 */ # else /* defined(SASL_VERSION_MAJOR) && defined(SASL_VERSION_MINOR) && defined(SASL_VERSION_STEP) */ # if SASL == 1 ERROR README: please set -DSASL to the version of the CYRUS_SASL library ERROR README: see README! # endif /* SASL == 1 */ # endif /* defined(SASL_VERSION_MAJOR) && defined(SASL_VERSION_MINOR) && defined(SASL_VERSION_STEP) */ #endif /* SASL */ /* ** Following are "sort of" configuration constants, but they should ** be pretty solid on most architectures today. They have to be ** defined after because some versions of that ** file also define them. In all cases, we can't use sizeof because ** some systems (e.g., Crays) always treat everything as being at ** least 64 bits. */ #ifndef INADDRSZ # define INADDRSZ 4 /* size of an IPv4 address in bytes */ #endif /* ! INADDRSZ */ #ifndef IN6ADDRSZ # define IN6ADDRSZ 16 /* size of an IPv6 address in bytes */ #endif /* ! IN6ADDRSZ */ #ifndef INT16SZ # define INT16SZ 2 /* size of a 16 bit integer in bytes */ #endif /* ! INT16SZ */ #ifndef INT32SZ # define INT32SZ 4 /* size of a 32 bit integer in bytes */ #endif /* ! INT32SZ */ #ifndef INADDR_LOOPBACK # define INADDR_LOOPBACK 0x7f000001 /* loopback address */ #endif /* ! INADDR_LOOPBACK */ /* ** Error return from inet_addr(3), in case not defined in /usr/include. */ #ifndef INADDR_NONE # define INADDR_NONE 0xffffffff #endif /* ! INADDR_NONE */ /* (f)open() modes for queue files */ # define QF_O_EXTRA 0 /* ** An 'argument class' describes the storage allocation status ** of an object pointed to by an argument to a function. */ typedef enum { A_HEAP, /* the storage was allocated by malloc, and the * ownership of the storage is ceded by the caller * to the called function. */ A_TEMP, /* The storage is temporary, and is only guaranteed * to be valid for the duration of the function call. */ A_PERM /* The storage is 'permanent': this might mean static * storage, or rpool storage. */ } ARGCLASS_T; /* forward references for prototypes */ typedef struct envelope ENVELOPE; typedef struct mailer MAILER; typedef struct queuegrp QUEUEGRP; /* ** Address structure. ** Addresses are stored internally in this structure. */ struct address { char *q_paddr; /* the printname for the address */ char *q_user; /* user name */ char *q_ruser; /* real user name, or NULL if q_user */ char *q_host; /* host name */ struct mailer *q_mailer; /* mailer to use */ unsigned long q_flags; /* status flags, see below */ uid_t q_uid; /* user-id of receiver (if known) */ gid_t q_gid; /* group-id of receiver (if known) */ char *q_home; /* home dir (local mailer only) */ char *q_fullname; /* full name if known */ struct address *q_next; /* chain */ struct address *q_alias; /* address this results from */ char *q_owner; /* owner of q_alias */ struct address *q_tchain; /* temporary use chain */ #if PIPELINING struct address *q_pchain; /* chain for pipelining */ #endif /* PIPELINING */ char *q_finalrcpt; /* Final-Recipient: DSN header */ char *q_orcpt; /* ORCPT parameter from RCPT TO: line */ char *q_status; /* status code for DSNs */ char *q_rstatus; /* remote status message for DSNs */ time_t q_statdate; /* date of status messages */ char *q_statmta; /* MTA generating q_rstatus */ short q_state; /* address state, see below */ char *q_signature; /* MX-based sorting value */ int q_qgrp; /* index into queue groups */ int q_qdir; /* queue directory inside group */ char *q_message; /* error message */ }; typedef struct address ADDRESS; /* bit values for q_flags */ #define QGOODUID 0x00000001 /* the q_uid q_gid fields are good */ #define QPRIMARY 0x00000002 /* set from RCPT or argv */ #define QNOTREMOTE 0x00000004 /* address not for remote forwarding */ #define QSELFREF 0x00000008 /* this address references itself */ #define QBOGUSSHELL 0x00000010 /* user has no valid shell listed */ #define QUNSAFEADDR 0x00000020 /* address acquired via unsafe path */ #define QPINGONSUCCESS 0x00000040 /* give return on successful delivery */ #define QPINGONFAILURE 0x00000080 /* give return on failure */ #define QPINGONDELAY 0x00000100 /* give return on message delay */ #define QHASNOTIFY 0x00000200 /* propagate notify parameter */ #define QRELAYED 0x00000400 /* DSN: relayed to non-DSN aware sys */ #define QEXPANDED 0x00000800 /* DSN: undergone list expansion */ #define QDELIVERED 0x00001000 /* DSN: successful final delivery */ #define QDELAYED 0x00002000 /* DSN: message delayed */ #define QALIAS 0x00004000 /* expanded alias */ #define QBYTRACE 0x00008000 /* DeliverBy: trace */ #define QBYNDELAY 0x00010000 /* DeliverBy: notify, delay */ #define QBYNRELAY 0x00020000 /* DeliverBy: notify, relayed */ #define QTHISPASS 0x40000000 /* temp: address set this pass */ #define QRCPTOK 0x80000000 /* recipient() processed address */ #define Q_PINGFLAGS (QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY) /* values for q_state */ #define QS_OK 0 /* address ok (for now)/not yet tried */ #define QS_SENT 1 /* good address, delivery complete */ #define QS_BADADDR 2 /* illegal address */ #define QS_QUEUEUP 3 /* save address in queue */ #define QS_RETRY 4 /* retry delivery for next MX */ #define QS_VERIFIED 5 /* verified, but not expanded */ /* ** Notice: all of the following values are variations of QS_DONTSEND. ** If new states are added, they must be inserted in the proper place! ** See the macro definition of QS_IS_DEAD() down below. */ #define QS_DONTSEND 6 /* don't send to this address */ #define QS_EXPANDED 7 /* expanded */ #define QS_SENDER 8 /* message sender (MeToo) */ #define QS_CLONED 9 /* addr cloned to split envelope */ #define QS_DISCARDED 10 /* rcpt discarded (EF_DISCARD) */ #define QS_REPLACED 11 /* maplocaluser()/UserDB replaced */ #define QS_REMOVED 12 /* removed (removefromlist()) */ #define QS_DUPLICATE 13 /* duplicate suppressed */ #define QS_INCLUDED 14 /* :include: delivery */ #define QS_FATALERR 15 /* fatal error, don't deliver */ /* address state testing primitives */ #define QS_IS_OK(s) ((s) == QS_OK) #define QS_IS_SENT(s) ((s) == QS_SENT) #define QS_IS_BADADDR(s) ((s) == QS_BADADDR) #define QS_IS_QUEUEUP(s) ((s) == QS_QUEUEUP) #define QS_IS_RETRY(s) ((s) == QS_RETRY) #define QS_IS_VERIFIED(s) ((s) == QS_VERIFIED) #define QS_IS_EXPANDED(s) ((s) == QS_EXPANDED) #define QS_IS_REMOVED(s) ((s) == QS_REMOVED) #define QS_IS_UNDELIVERED(s) ((s) == QS_OK || \ (s) == QS_QUEUEUP || \ (s) == QS_RETRY || \ (s) == QS_VERIFIED) #define QS_IS_UNMARKED(s) ((s) == QS_OK || \ (s) == QS_RETRY) #define QS_IS_SENDABLE(s) ((s) == QS_OK || \ (s) == QS_QUEUEUP || \ (s) == QS_RETRY) #define QS_IS_ATTEMPTED(s) ((s) == QS_QUEUEUP || \ (s) == QS_RETRY || \ (s) == QS_SENT || \ (s) == QS_DISCARDED) #define QS_IS_DEAD(s) ((s) >= QS_DONTSEND) #define QS_IS_TEMPFAIL(s) ((s) == QS_QUEUEUP || (s) == QS_RETRY) #define NULLADDR ((ADDRESS *) NULL) extern ADDRESS NullAddress; /* a null (template) address [main.c] */ /* functions */ extern void cataddr __P((char **, char **, char *, int, int, bool)); extern char *crackaddr __P((char *, ENVELOPE *)); extern bool emptyaddr __P((ADDRESS *)); extern ADDRESS *getctladdr __P((ADDRESS *)); extern int include __P((char *, bool, ADDRESS *, ADDRESS **, int, ENVELOPE *)); extern bool invalidaddr __P((char *, char *, bool)); extern ADDRESS *parseaddr __P((char *, ADDRESS *, int, int, char **, ENVELOPE *, bool)); extern char **prescan __P((char *, int, char[], int, char **, unsigned char *, bool)); extern void printaddr __P((SM_FILE_T *, ADDRESS *, bool)); extern ADDRESS *recipient __P((ADDRESS *, ADDRESS **, int, ENVELOPE *)); extern char *remotename __P((char *, MAILER *, int, int *, ENVELOPE *)); extern int rewrite __P((char **, int, int, ENVELOPE *, int)); extern bool sameaddr __P((ADDRESS *, ADDRESS *)); extern int sendtolist __P((char *, ADDRESS *, ADDRESS **, int, ENVELOPE *)); #if MILTER extern int removefromlist __P((char *, ADDRESS **, ENVELOPE *)); #endif /* MILTER */ extern void setsender __P((char *, ENVELOPE *, char **, int, bool)); typedef void esmtp_args_F __P((ADDRESS *, char *, char *, ENVELOPE *)); extern void parse_esmtp_args __P((ENVELOPE *, ADDRESS *, char *, char *, char *, char *args[], esmtp_args_F)); extern esmtp_args_F mail_esmtp_args; extern esmtp_args_F rcpt_esmtp_args; extern void reset_mail_esmtp_args __P((ENVELOPE *)); /* macro to simplify the common call to rewrite() */ #define REWRITE(pvp, rs, env) rewrite(pvp, rs, 0, env, MAXATOM) /* ** Token Tables for prescan */ extern unsigned char ExtTokenTab[256]; /* external strings */ extern unsigned char IntTokenTab[256]; /* internal strings */ /* ** Mailer definition structure. ** Every mailer known to the system is declared in this ** structure. It defines the pathname of the mailer, some ** flags associated with it, and the argument vector to ** pass to it. The flags are defined in conf.c ** ** The argument vector is expanded before actual use. All ** words except the first are passed through the macro ** processor. */ struct mailer { char *m_name; /* symbolic name of this mailer */ char *m_mailer; /* pathname of the mailer to use */ char *m_mtatype; /* type of this MTA */ char *m_addrtype; /* type for addresses */ char *m_diagtype; /* type for diagnostics */ BITMAP256 m_flags; /* status flags, see below */ short m_mno; /* mailer number internally */ short m_nice; /* niceness to run at (mostly for prog) */ char **m_argv; /* template argument vector */ short m_sh_rwset; /* rewrite set: sender header addresses */ short m_se_rwset; /* rewrite set: sender envelope addresses */ short m_rh_rwset; /* rewrite set: recipient header addresses */ short m_re_rwset; /* rewrite set: recipient envelope addresses */ char *m_eol; /* end of line string */ long m_maxsize; /* size limit on message to this mailer */ int m_linelimit; /* max # characters per line */ int m_maxdeliveries; /* max deliveries per mailer connection */ char *m_execdir; /* directory to chdir to before execv */ char *m_rootdir; /* directory to chroot to before execv */ uid_t m_uid; /* UID to run as */ gid_t m_gid; /* GID to run as */ char *m_defcharset; /* default character set */ time_t m_wait; /* timeout to wait for end */ int m_maxrcpt; /* max recipients per envelope client-side */ short m_qgrp; /* queue group for this mailer */ }; /* bits for m_flags */ #define M_ESMTP 'a' /* run Extended SMTP */ #define M_ALIASABLE 'A' /* user can be LHS of an alias */ #define M_BLANKEND 'b' /* ensure blank line at end of message */ #define M_STRIPBACKSL 'B' /* strip all leading backslashes from user */ #define M_NOCOMMENT 'c' /* don't include comment part of address */ #define M_CANONICAL 'C' /* make addresses canonical "u@dom" */ #define M_NOBRACKET 'd' /* never angle bracket envelope route-addrs */ /* 'D' CF: include Date: */ #define M_EXPENSIVE 'e' /* it costs to use this mailer.... */ #define M_ESCFROM 'E' /* escape From lines to >From */ #define M_FOPT 'f' /* mailer takes picky -f flag */ /* 'F' CF: include From: or Resent-From: */ #define M_NO_NULL_FROM 'g' /* sender of errors should be $g */ #define M_HST_UPPER 'h' /* preserve host case distinction */ #define M_PREHEAD 'H' /* MAIL11V3: preview headers */ #define M_UDBENVELOPE 'i' /* do udbsender rewriting on envelope */ #define M_INTERNAL 'I' /* SMTP to another sendmail site */ #define M_UDBRECIPIENT 'j' /* do udbsender rewriting on recipient lines */ #define M_NOLOOPCHECK 'k' /* don't check for loops in HELO command */ #define M_CHUNKING 'K' /* CHUNKING: reserved for future use */ #define M_LOCALMAILER 'l' /* delivery is to this host */ #define M_LIMITS 'L' /* must enforce SMTP line limits */ #define M_MUSER 'm' /* can handle multiple users at once */ /* 'M' CF: include Message-Id: */ #define M_NHDR 'n' /* don't insert From line */ #define M_MANYSTATUS 'N' /* MAIL11V3: DATA returns multi-status */ #define M_RUNASRCPT 'o' /* always run mailer as recipient */ #define M_FROMPATH 'p' /* use reverse-path in MAIL FROM: */ /* 'P' CF: include Return-Path: */ #define M_VRFY250 'q' /* VRFY command returns 250 instead of 252 */ #define M_ROPT 'r' /* mailer takes picky -r flag */ #define M_SECURE_PORT 'R' /* try to send on a reserved TCP port */ #define M_STRIPQ 's' /* strip quote chars from user/host */ #define M_SPECIFIC_UID 'S' /* run as specific uid/gid */ #define M_USR_UPPER 'u' /* preserve user case distinction */ #define M_UGLYUUCP 'U' /* this wants an ugly UUCP from line */ #define M_CONTENT_LEN 'v' /* add Content-Length: header (SVr4) */ /* 'V' UIUC: !-relativize all addresses */ #define M_HASPWENT 'w' /* check for /etc/passwd entry */ #define M_NOHOSTSTAT 'W' /* ignore long term host status information */ /* 'x' CF: include Full-Name: */ #define M_XDOT 'X' /* use hidden-dot algorithm */ #define M_LMTP 'z' /* run Local Mail Transport Protocol */ #define M_DIALDELAY 'Z' /* apply dial delay sleeptime */ #define M_NOMX '0' /* turn off MX lookups */ #define M_NONULLS '1' /* don't send null bytes */ #define M_FSMTP '2' /* force SMTP (no ESMTP even if offered) */ #define M_EBCDIC '3' /* extend Q-P encoding for EBCDIC */ #define M_TRYRULESET5 '5' /* use ruleset 5 after local aliasing */ #define M_7BITHDRS '6' /* strip headers to 7 bits even in 8 bit path */ #define M_7BITS '7' /* use 7-bit path */ #define M_8BITS '8' /* force "just send 8" behaviour */ #define M_MAKE8BIT '9' /* convert 7 -> 8 bit if appropriate */ #define M_CHECKINCLUDE ':' /* check for :include: files */ #define M_CHECKPROG '|' /* check for |program addresses */ #define M_CHECKFILE '/' /* check for /file addresses */ #define M_CHECKUDB '@' /* user can be user database key */ #define M_CHECKHDIR '~' /* SGI: check for valid home directory */ #define M_HOLD '%' /* Hold delivery until ETRN/-qI/-qR/-qS */ #define M_PLUS '+' /* Reserved: Used in mc for adding new flags */ #define M_MINUS '-' /* Reserved: Used in mc for removing flags */ /* functions */ extern void initerrmailers __P((void)); extern void makemailer __P((char *)); extern void makequeue __P((char *, bool)); extern void runqueueevent __P((int)); #if _FFR_QUEUE_RUN_PARANOIA extern bool checkqueuerunner __P((void)); #endif /* _FFR_QUEUE_RUN_PARANOIA */ EXTERN MAILER *FileMailer; /* ptr to *file* mailer */ EXTERN MAILER *InclMailer; /* ptr to *include* mailer */ EXTERN MAILER *LocalMailer; /* ptr to local mailer */ EXTERN MAILER *ProgMailer; /* ptr to program mailer */ EXTERN MAILER *Mailer[MAXMAILERS + 1]; /* ** Queue group definition structure. ** Every queue group known to the system is declared in this structure. ** It defines the basic pathname of the queue group, some flags ** associated with it, and the argument vector to pass to it. */ struct qpaths_s { char *qp_name; /* name of queue dir, relative path */ short qp_subdirs; /* use subdirs? */ short qp_fsysidx; /* file system index of this directory */ # if SM_CONF_SHM int qp_idx; /* index into array for queue information */ # endif /* SM_CONF_SHM */ }; typedef struct qpaths_s QPATHS; struct queuegrp { char *qg_name; /* symbolic name of this queue group */ /* ** For now this is the same across all queue groups. ** Otherwise we have to play around with chdir(). */ char *qg_qdir; /* common component of queue directory */ short qg_index; /* queue number internally, index in Queue[] */ int qg_maxqrun; /* max # of jobs in 1 queuerun */ int qg_numqueues; /* number of queues in this queue */ /* ** qg_queueintvl == 0 denotes that no individual value is used. ** Whatever accesses this must deal with "<= 0" as ** "not set, use appropriate default". */ time_t qg_queueintvl; /* interval for queue runs */ QPATHS *qg_qpaths; /* list of queue directories */ BITMAP256 qg_flags; /* status flags, see below */ short qg_nice; /* niceness for queue run */ int qg_wgrp; /* Assigned to this work group */ int qg_maxlist; /* max items in work queue for this group */ int qg_curnum; /* current number of queue for queue runs */ int qg_maxrcpt; /* max recipients per envelope, 0==no limit */ time_t qg_nextrun; /* time for next queue runs */ #if _FFR_QUEUE_GROUP_SORTORDER short qg_sortorder; /* how do we sort this queuerun */ #endif /* _FFR_QUEUE_GROUP_SORTORDER */ #if 0 long qg_wkrcptfact; /* multiplier for # recipients -> priority */ long qg_qfactor; /* slope of queue function */ bool qg_doqueuerun; /* XXX flag is it time to do a queuerun */ #endif /* 0 */ }; /* bits for qg_flags (XXX: unused as of now) */ #define QD_DEFINED ((char) 1) /* queue group has been defined */ #define QD_FORK 'f' /* fork queue runs */ extern void filesys_update __P((void)); #if _FFR_ANY_FREE_FS extern bool filesys_free __P((long)); #endif /* _FFR_ANY_FREE_FS */ #if SASL /* ** SASL */ /* lines in authinfo file or index into SASL_AI_T */ # define SASL_WRONG (-1) # define SASL_USER 0 /* authorization id (user) */ # define SASL_AUTHID 1 /* authentication id */ # define SASL_PASSWORD 2 /* password fuer authid */ # define SASL_DEFREALM 3 /* realm to use */ # define SASL_MECHLIST 4 /* list of mechanisms to try */ # define SASL_ID_REALM 5 /* authid@defrealm */ /* ** Current mechanism; this is just used to convey information between ** invocation of SASL callback functions. ** It must be last in the list, because it's not allocated by us ** and hence we don't free() it. */ # define SASL_MECH 6 # define SASL_ENTRIES 7 /* number of entries in array */ # define SASL_USER_BIT (1 << SASL_USER) # define SASL_AUTHID_BIT (1 << SASL_AUTHID) # define SASL_PASSWORD_BIT (1 << SASL_PASSWORD) # define SASL_DEFREALM_BIT (1 << SASL_DEFREALM) # define SASL_MECHLIST_BIT (1 << SASL_MECHLIST) /* authenticated? */ # define SASL_NOT_AUTH 0 /* not authenticated */ # define SASL_PROC_AUTH 1 /* in process of authenticating */ # define SASL_IS_AUTH 2 /* authenticated */ /* SASL options */ # define SASL_AUTH_AUTH 0x1000 /* use auth= only if authenticated */ # if SASL >= 20101 # define SASL_SEC_MASK SASL_SEC_MAXIMUM /* mask for SASL_SEC_* values: sasl.h */ # else /* SASL >= 20101 */ # define SASL_SEC_MASK 0x0fff /* mask for SASL_SEC_* values: sasl.h */ # if (SASL_SEC_NOPLAINTEXT & SASL_SEC_MASK) == 0 || \ (SASL_SEC_NOACTIVE & SASL_SEC_MASK) == 0 || \ (SASL_SEC_NODICTIONARY & SASL_SEC_MASK) == 0 || \ (SASL_SEC_FORWARD_SECRECY & SASL_SEC_MASK) == 0 || \ (SASL_SEC_NOANONYMOUS & SASL_SEC_MASK) == 0 || \ (SASL_SEC_PASS_CREDENTIALS & SASL_SEC_MASK) == 0 ERROR: change SASL_SEC_MASK_ notify sendmail.org! # endif /* SASL_SEC_NOPLAINTEXT & SASL_SEC_MASK) == 0 ... */ # endif /* SASL >= 20101 */ # define MAXOUTLEN 8192 /* length of output buffer, should be 2^n */ /* functions */ extern char *intersect __P((char *, char *, SM_RPOOL_T *)); extern char *iteminlist __P((char *, char *, char *)); # if SASL >= 20000 extern int proxy_policy __P((sasl_conn_t *, void *, const char *, unsigned, const char *, unsigned, const char *, unsigned, struct propctx *)); extern int safesaslfile __P((void *, const char *, sasl_verify_type_t)); # else /* SASL >= 20000 */ extern int proxy_policy __P((void *, const char *, const char *, const char **, const char **)); # if SASL > 10515 extern int safesaslfile __P((void *, char *, int)); # else /* SASL > 10515 */ extern int safesaslfile __P((void *, char *)); # endif /* SASL > 10515 */ # endif /* SASL >= 20000 */ extern void stop_sasl_client __P((void)); /* structure to store authinfo */ typedef char *SASL_AI_T[SASL_ENTRIES]; EXTERN char *AuthMechanisms; /* AUTH mechanisms */ EXTERN char *AuthRealm; /* AUTH realm */ EXTERN char *SASLInfo; /* file with AUTH info */ EXTERN int SASLOpts; /* options for SASL */ EXTERN int MaxSLBits; /* max. encryption bits for SASL */ #endif /* SASL */ /* ** Structure to store macros. */ typedef struct { SM_RPOOL_T *mac_rpool; /* resource pool */ BITMAP256 mac_allocated; /* storage has been alloc()? */ char *mac_table[MAXMACROID + 1]; /* macros */ } MACROS_T; EXTERN MACROS_T GlobalMacros; /* ** Information about currently open connections to mailers, or to ** hosts that we have looked up recently. */ #define MCI struct mailer_con_info MCI { unsigned long mci_flags; /* flag bits, see below */ short mci_errno; /* error number on last connection */ short mci_herrno; /* h_errno from last DNS lookup */ short mci_exitstat; /* exit status from last connection */ short mci_state; /* SMTP state */ int mci_deliveries; /* delivery attempts for connection */ long mci_maxsize; /* max size this server will accept */ SM_FILE_T *mci_in; /* input side of connection */ SM_FILE_T *mci_out; /* output side of connection */ pid_t mci_pid; /* process id of subordinate proc */ char *mci_phase; /* SMTP phase string */ struct mailer *mci_mailer; /* ptr to the mailer for this conn */ char *mci_host; /* host name */ char *mci_status; /* DSN status to be copied to addrs */ char *mci_rstatus; /* SMTP status to be copied to addrs */ time_t mci_lastuse; /* last usage time */ SM_FILE_T *mci_statfile; /* long term status file */ char *mci_heloname; /* name to use as HELO arg */ long mci_min_by; /* minimum DELIVERBY */ bool mci_retryrcpt; /* tempfail for at least one rcpt */ char *mci_tolist; /* list of valid recipients */ SM_RPOOL_T *mci_rpool; /* resource pool */ #if PIPELINING int mci_okrcpts; /* number of valid recipients */ ADDRESS *mci_nextaddr; /* next address for pipelined status */ #endif /* PIPELINING */ #if SASL SASL_AI_T mci_sai; /* authentication info */ bool mci_sasl_auth; /* authenticated? */ int mci_sasl_string_len; char *mci_sasl_string; /* sasl reply string */ char *mci_saslcap; /* SASL list of mechanisms */ sasl_conn_t *mci_conn; /* SASL connection */ #endif /* SASL */ #if STARTTLS SSL *mci_ssl; /* SSL connection */ #endif /* STARTTLS */ MACROS_T mci_macro; /* macro definitions */ }; /* flag bits */ #define MCIF_VALID 0x00000001 /* this entry is valid */ /* 0x00000002 unused, was MCIF_TEMP */ #define MCIF_CACHED 0x00000004 /* currently in open cache */ #define MCIF_ESMTP 0x00000008 /* this host speaks ESMTP */ #define MCIF_EXPN 0x00000010 /* EXPN command supported */ #define MCIF_SIZE 0x00000020 /* SIZE option supported */ #define MCIF_8BITMIME 0x00000040 /* BODY=8BITMIME supported */ #define MCIF_7BIT 0x00000080 /* strip this message to 7 bits */ /* 0x00000100 unused, was MCIF_MULTSTAT: MAIL11V3: handles MULT status */ #define MCIF_INHEADER 0x00000200 /* currently outputing header */ #define MCIF_CVT8TO7 0x00000400 /* convert from 8 to 7 bits */ #define MCIF_DSN 0x00000800 /* DSN extension supported */ #define MCIF_8BITOK 0x00001000 /* OK to send 8 bit characters */ #define MCIF_CVT7TO8 0x00002000 /* convert from 7 to 8 bits */ #define MCIF_INMIME 0x00004000 /* currently reading MIME header */ #define MCIF_AUTH 0x00008000 /* AUTH= supported */ #define MCIF_AUTHACT 0x00010000 /* SASL (AUTH) active */ #define MCIF_ENHSTAT 0x00020000 /* ENHANCEDSTATUSCODES supported */ #define MCIF_PIPELINED 0x00040000 /* PIPELINING supported */ #define MCIF_VERB 0x00080000 /* VERB supported */ #if STARTTLS #define MCIF_TLS 0x00100000 /* STARTTLS supported */ #define MCIF_TLSACT 0x00200000 /* STARTTLS active */ #else /* STARTTLS */ #define MCIF_TLS 0 #define MCIF_TLSACT 0 #endif /* STARTTLS */ #define MCIF_DLVR_BY 0x00400000 /* DELIVERBY */ #if _FFR_IGNORE_EXT_ON_HELO # define MCIF_HELO 0x00800000 /* we used HELO: ignore extensions */ #endif /* _FFR_IGNORE_EXT_ON_HELO */ #define MCIF_INLONGLINE 0x01000000 /* in the middle of a long line */ #define MCIF_AUTH2 0x02000000 /* got 2 AUTH lines */ #define MCIF_ONLY_EHLO 0x10000000 /* use only EHLO in smtpinit */ #define MCIF_EXTENS (MCIF_EXPN | MCIF_SIZE | MCIF_8BITMIME | MCIF_DSN | MCIF_8BITOK | MCIF_AUTH | MCIF_ENHSTAT | MCIF_TLS | MCIF_AUTH2) /* states */ #define MCIS_CLOSED 0 /* no traffic on this connection */ #define MCIS_OPENING 1 /* sending initial protocol */ #define MCIS_OPEN 2 /* open, initial protocol sent */ #define MCIS_MAIL 3 /* MAIL command sent */ #define MCIS_RCPT 4 /* RCPT commands being sent */ #define MCIS_DATA 5 /* DATA command sent */ #define MCIS_QUITING 6 /* running quit protocol */ #define MCIS_SSD 7 /* service shutting down */ #define MCIS_ERROR 8 /* I/O error on connection */ /* functions */ extern void mci_cache __P((MCI *)); extern void mci_close __P((MCI *, char *where)); extern void mci_dump __P((SM_FILE_T *, MCI *, bool)); extern void mci_dump_all __P((SM_FILE_T *, bool)); extern void mci_flush __P((bool, MCI *)); extern void mci_clr_extensions __P((MCI *)); extern MCI *mci_get __P((char *, MAILER *)); extern int mci_lock_host __P((MCI *)); extern bool mci_match __P((char *, MAILER *)); extern int mci_print_persistent __P((char *, char *)); extern int mci_purge_persistent __P((char *, char *)); extern MCI **mci_scan __P((MCI *)); extern void mci_setstat __P((MCI *, int, char *, char *)); extern void mci_store_persistent __P((MCI *)); extern int mci_traverse_persistent __P((int (*)(char *, char *), char *)); extern void mci_unlock_host __P((MCI *)); EXTERN int MaxMciCache; /* maximum entries in MCI cache */ EXTERN time_t MciCacheTimeout; /* maximum idle time on connections */ EXTERN time_t MciInfoTimeout; /* how long 'til we retry down hosts */ /* ** Header structure. ** This structure is used internally to store header items. */ struct header { char *h_field; /* the name of the field */ char *h_value; /* the value of that field */ struct header *h_link; /* the next header */ unsigned char h_macro; /* include header if macro defined */ unsigned long h_flags; /* status bits, see below */ BITMAP256 h_mflags; /* m_flags bits needed */ }; typedef struct header HDR; /* ** Header information structure. ** Defined in conf.c, this struct declares the header fields ** that have some magic meaning. */ struct hdrinfo { char *hi_field; /* the name of the field */ unsigned long hi_flags; /* status bits, see below */ char *hi_ruleset; /* validity check ruleset */ }; extern struct hdrinfo HdrInfo[]; /* bits for h_flags and hi_flags */ #define H_EOH 0x00000001 /* field terminates header */ #define H_RCPT 0x00000002 /* contains recipient addresses */ #define H_DEFAULT 0x00000004 /* if another value is found, drop this */ #define H_RESENT 0x00000008 /* this address is a "Resent-..." address */ #define H_CHECK 0x00000010 /* check h_mflags against m_flags */ #define H_ACHECK 0x00000020 /* ditto, but always (not just default) */ #define H_FORCE 0x00000040 /* force this field, even if default */ #define H_TRACE 0x00000080 /* this field contains trace information */ #define H_FROM 0x00000100 /* this is a from-type field */ #define H_VALID 0x00000200 /* this field has a validated value */ #define H_RECEIPTTO 0x00000400 /* field has return receipt info */ #define H_ERRORSTO 0x00000800 /* field has error address info */ #define H_CTE 0x00001000 /* field is a content-transfer-encoding */ #define H_CTYPE 0x00002000 /* this is a content-type field */ #define H_BCC 0x00004000 /* Bcc: header: strip value or delete */ #define H_ENCODABLE 0x00008000 /* field can be RFC 1522 encoded */ #define H_STRIPCOMM 0x00010000 /* header check: strip comments */ #define H_BINDLATE 0x00020000 /* only expand macros at deliver */ #define H_USER 0x00040000 /* header came from the user/SMTP */ /* bits for chompheader() */ #define CHHDR_DEF 0x0001 /* default header */ #define CHHDR_CHECK 0x0002 /* call ruleset for header */ #define CHHDR_USER 0x0004 /* header from user */ #define CHHDR_QUEUE 0x0008 /* header from queue file */ /* functions */ extern void addheader __P((char *, char *, int, ENVELOPE *, bool)); extern unsigned long chompheader __P((char *, int, HDR **, ENVELOPE *)); extern bool commaize __P((HDR *, char *, bool, MCI *, ENVELOPE *, int)); extern HDR *copyheader __P((HDR *, SM_RPOOL_T *)); extern void eatheader __P((ENVELOPE *, bool, bool)); extern char *hvalue __P((char *, HDR *)); extern void insheader __P((int, char *, char *, int, ENVELOPE *, bool)); extern bool isheader __P((char *)); extern bool putfromline __P((MCI *, ENVELOPE *)); extern void setupheaders __P((void)); /* ** Performance monitoring */ #define TIMERS struct sm_timers TIMERS { TIMER ti_overall; /* the whole process */ }; #define PUSHTIMER(l, t) { if (tTd(98, l)) pushtimer(&t); } #define POPTIMER(l, t) { if (tTd(98, l)) poptimer(&t); } /* ** Envelope structure. ** This structure defines the message itself. There is usually ** only one of these -- for the message that we originally read ** and which is our primary interest -- but other envelopes can ** be generated during processing. For example, error messages ** will have their own envelope. */ struct envelope { HDR *e_header; /* head of header list */ long e_msgpriority; /* adjusted priority of this message */ time_t e_ctime; /* time message appeared in the queue */ char *e_to; /* (list of) target person(s) */ ADDRESS e_from; /* the person it is from */ char *e_sender; /* e_from.q_paddr w comments stripped */ char **e_fromdomain; /* the domain part of the sender */ ADDRESS *e_sendqueue; /* list of message recipients */ ADDRESS *e_errorqueue; /* the queue for error responses */ /* ** Overflow detection is based on < 0, so don't change this ** to unsigned. We don't use unsigned and == ULONG_MAX because ** some libc's don't have strtoul(), see mail_esmtp_args(). */ long e_msgsize; /* size of the message in bytes */ char *e_msgid; /* message id (for logging) */ unsigned long e_flags; /* flags, see below */ int e_nrcpts; /* number of recipients */ short e_class; /* msg class (priority, junk, etc.) */ short e_hopcount; /* number of times processed */ short e_nsent; /* number of sends since checkpoint */ short e_sendmode; /* message send mode */ short e_errormode; /* error return mode */ short e_timeoutclass; /* message timeout class */ bool (*e_puthdr)__P((MCI *, HDR *, ENVELOPE *, int)); /* function to put header of message */ bool (*e_putbody)__P((MCI *, ENVELOPE *, char *)); /* function to put body of message */ ENVELOPE *e_parent; /* the message this one encloses */ ENVELOPE *e_sibling; /* the next envelope of interest */ char *e_bodytype; /* type of message body */ SM_FILE_T *e_dfp; /* data file */ char *e_id; /* code for this entry in queue */ #if _FFR_SESSID char *e_sessid; /* session ID for this envelope */ #endif /* _FFR_SESSID */ int e_qgrp; /* queue group (index into queues) */ int e_qdir; /* index into queue directories */ int e_dfqgrp; /* data file queue group index */ int e_dfqdir; /* data file queue directory index */ int e_xfqgrp; /* queue group (index into queues) */ int e_xfqdir; /* index into queue directories (xf) */ SM_FILE_T *e_xfp; /* transcript file */ SM_FILE_T *e_lockfp; /* the lock file for this message */ char *e_message; /* error message; readonly; NULL, * or allocated from e_rpool */ char *e_statmsg; /* stat msg (changes per delivery). * readonly. NULL or allocated from * e_rpool. */ char *e_quarmsg; /* why envelope is quarantined */ char e_qfletter; /* queue file letter on disk */ char *e_msgboundary; /* MIME-style message part boundary */ char *e_origrcpt; /* original recipient (one only) */ char *e_envid; /* envelope id from MAIL FROM: line */ char *e_status; /* DSN status for this message */ time_t e_dtime; /* time of last delivery attempt */ int e_ntries; /* number of delivery attempts */ dev_t e_dfdev; /* data file device (crash recovery) */ ino_t e_dfino; /* data file inode (crash recovery) */ MACROS_T e_macro; /* macro definitions */ MCI *e_mci; /* connection info */ char *e_auth_param; /* readonly; NULL or static storage or * allocated from e_rpool */ TIMERS e_timers; /* per job timers */ long e_deliver_by; /* deliver by */ int e_dlvr_flag; /* deliver by flag */ SM_RPOOL_T *e_rpool; /* resource pool for this envelope */ unsigned int e_features; /* server features */ #if _FFR_MILTER_ENHSC #define ENHSC_LEN 11 char e_enhsc[ENHSC_LEN]; /* enhanced status code */ #endif /* _FFR_MILTER_ENHSC */ }; #define PRT_NONNEGL(v) ((v) < 0 ? LONG_MAX : (v)) /* values for e_flags */ #define EF_OLDSTYLE 0x00000001L /* use spaces (not commas) in hdrs */ #define EF_INQUEUE 0x00000002L /* this message is fully queued */ #define EF_NO_BODY_RETN 0x00000004L /* omit message body on error */ #define EF_CLRQUEUE 0x00000008L /* disk copy is no longer needed */ #define EF_SENDRECEIPT 0x00000010L /* send a return receipt */ #define EF_FATALERRS 0x00000020L /* fatal errors occurred */ #define EF_DELETE_BCC 0x00000040L /* delete Bcc: headers entirely */ #define EF_RESPONSE 0x00000080L /* this is an error or return receipt */ #define EF_RESENT 0x00000100L /* this message is being forwarded */ #define EF_VRFYONLY 0x00000200L /* verify only (don't expand aliases) */ #define EF_WARNING 0x00000400L /* warning message has been sent */ #define EF_QUEUERUN 0x00000800L /* this envelope is from queue */ #define EF_GLOBALERRS 0x00001000L /* treat errors as global */ #define EF_PM_NOTIFY 0x00002000L /* send return mail to postmaster */ #define EF_METOO 0x00004000L /* send to me too */ #define EF_LOGSENDER 0x00008000L /* need to log the sender */ #define EF_NORECEIPT 0x00010000L /* suppress all return-receipts */ #define EF_HAS8BIT 0x00020000L /* at least one 8-bit char in body */ #define EF_NL_NOT_EOL 0x00040000L /* don't accept raw NL as EOLine */ #define EF_CRLF_NOT_EOL 0x00080000L /* don't accept CR-LF as EOLine */ #define EF_RET_PARAM 0x00100000L /* RCPT command had RET argument */ #define EF_HAS_DF 0x00200000L /* set when data file is instantiated */ #define EF_IS_MIME 0x00400000L /* really is a MIME message */ #define EF_DONT_MIME 0x00800000L /* never MIME this message */ #define EF_DISCARD 0x01000000L /* discard the message */ #define EF_TOOBIG 0x02000000L /* message is too big */ #define EF_SPLIT 0x04000000L /* envelope has been split */ #define EF_UNSAFE 0x08000000L /* unsafe: read from untrusted source */ #define EF_TOODEEP 0x10000000L /* message is nested too deep */ #define DLVR_NOTIFY 0x01 #define DLVR_RETURN 0x02 #define DLVR_TRACE 0x10 #define IS_DLVR_NOTIFY(e) (((e)->e_dlvr_flag & DLVR_NOTIFY) != 0) #define IS_DLVR_RETURN(e) (((e)->e_dlvr_flag & DLVR_RETURN) != 0) #define IS_DLVR_TRACE(e) (((e)->e_dlvr_flag & DLVR_TRACE) != 0) #define IS_DLVR_BY(e) ((e)->e_dlvr_flag != 0) #define BODYTYPE_NONE (0) #define BODYTYPE_7BIT (1) #define BODYTYPE_8BITMIME (2) #define BODYTYPE_ILLEGAL (-1) #define BODYTYPE_VALID(b) ((b) == BODYTYPE_7BIT || (b) == BODYTYPE_8BITMIME) extern ENVELOPE BlankEnvelope; /* functions */ extern void clearenvelope __P((ENVELOPE *, bool, SM_RPOOL_T *)); extern int dropenvelope __P((ENVELOPE *, bool, bool)); extern ENVELOPE *newenvelope __P((ENVELOPE *, ENVELOPE *, SM_RPOOL_T *)); extern void clrsessenvelope __P((ENVELOPE *)); extern void printenvflags __P((ENVELOPE *)); extern bool putbody __P((MCI *, ENVELOPE *, char *)); extern bool putheader __P((MCI *, HDR *, ENVELOPE *, int)); /* ** Message priority classes. ** ** The message class is read directly from the Priority: header ** field in the message. ** ** CurEnv->e_msgpriority is the number of bytes in the message plus ** the creation time (so that jobs ``tend'' to be ordered correctly), ** adjusted by the message class, the number of recipients, and the ** amount of time the message has been sitting around. This number ** is used to order the queue. Higher values mean LOWER priority. ** ** Each priority class point is worth WkClassFact priority points; ** each recipient is worth WkRecipFact priority points. Each time ** we reprocess a message the priority is adjusted by WkTimeFact. ** WkTimeFact should normally decrease the priority so that jobs ** that have historically failed will be run later; thanks go to ** Jay Lepreau at Utah for pointing out the error in my thinking. ** ** The "class" is this number, unadjusted by the age or size of ** this message. Classes with negative representations will have ** error messages thrown away if they are not local. */ struct priority { char *pri_name; /* external name of priority */ int pri_val; /* internal value for same */ }; EXTERN int NumPriorities; /* pointer into Priorities */ EXTERN struct priority Priorities[MAXPRIORITIES]; /* ** Rewrite rules. */ struct rewrite { char **r_lhs; /* pattern match */ char **r_rhs; /* substitution value */ struct rewrite *r_next;/* next in chain */ int r_line; /* rule line in sendmail.cf */ }; /* ** Special characters in rewriting rules. ** These are used internally only. ** The COND* rules are actually used in macros rather than in ** rewriting rules, but are given here because they ** cannot conflict. */ /* "out of band" indicator */ /* sm/sendmail.h #define METAQUOTE ((unsigned char)0377) quotes the next octet */ /* left hand side items */ #define MATCHZANY ((unsigned char)0220) /* match zero or more tokens */ #define MATCHANY ((unsigned char)0221) /* match one or more tokens */ #define MATCHONE ((unsigned char)0222) /* match exactly one token */ #define MATCHCLASS ((unsigned char)0223) /* match one token in a class */ #define MATCHNCLASS ((unsigned char)0224) /* match tokens not in class */ /* right hand side items */ #define MATCHREPL ((unsigned char)0225) /* RHS replacement for above */ #define CANONNET ((unsigned char)0226) /* canonical net, next token */ #define CANONHOST ((unsigned char)0227) /* canonical host, next token */ #define CANONUSER ((unsigned char)0230) /* canonical user, next N tokens */ #define CALLSUBR ((unsigned char)0231) /* call another rewriting set */ /* conditionals in macros (anywhere) */ #define CONDIF ((unsigned char)0232) /* conditional if-then */ #define CONDELSE ((unsigned char)0233) /* conditional else */ #define CONDFI ((unsigned char)0234) /* conditional fi */ /* bracket characters for RHS host name lookup */ #define HOSTBEGIN ((unsigned char)0235) /* hostname lookup begin */ #define HOSTEND ((unsigned char)0236) /* hostname lookup end */ /* bracket characters for RHS generalized lookup */ #define LOOKUPBEGIN ((unsigned char)0205) /* generalized lookup begin */ #define LOOKUPEND ((unsigned char)0206) /* generalized lookup end */ /* macro substitution characters (anywhere) */ #define MACROEXPAND ((unsigned char)0201) /* macro expansion */ #define MACRODEXPAND ((unsigned char)0202) /* deferred macro expansion */ /* to make the code clearer */ #define MATCHZERO CANONHOST #define MAXMATCH 9 /* max params per rewrite */ #define MAX_MAP_ARGS 10 /* max arguments for map */ /* external <==> internal mapping table */ struct metamac { char metaname; /* external code (after $) */ unsigned char metaval; /* internal code (as above) */ }; /* values for macros with external names only */ #define MID_OPMODE 0202 /* operation mode */ /* functions */ #if SM_HEAP_CHECK extern void macdefine_tagged __P(( MACROS_T *_mac, ARGCLASS_T _vclass, int _id, char *_value, char *_file, int _line, int _group)); # define macdefine(mac,c,id,v) \ macdefine_tagged(mac,c,id,v,__FILE__,__LINE__,sm_heap_group()) #else /* SM_HEAP_CHECK */ extern void macdefine __P(( MACROS_T *_mac, ARGCLASS_T _vclass, int _id, char *_value)); # define macdefine_tagged(mac,c,id,v,file,line,grp) macdefine(mac,c,id,v) #endif /* SM_HEAP_CHECK */ extern void macset __P((MACROS_T *, int, char *)); #define macget(mac, i) (mac)->mac_table[i] extern void expand __P((char *, char *, size_t, ENVELOPE *)); extern int macid_parse __P((char *, char **)); #define macid(name) macid_parse(name, NULL) extern char *macname __P((int)); extern char *macvalue __P((int, ENVELOPE *)); extern int rscheck __P((char *, char *, char *, ENVELOPE *, int, int, char *, char *, ADDRESS *)); extern int rscap __P((char *, char *, char *, ENVELOPE *, char ***, char *, int)); extern void setclass __P((int, char *)); extern int strtorwset __P((char *, char **, int)); extern char *translate_dollars __P((char *, char *, int *)); extern bool wordinclass __P((char *, int)); /* ** Name canonification short circuit. ** ** If the name server for a host is down, the process of trying to ** canonify the name can hang. This is similar to (but alas, not ** identical to) looking up the name for delivery. This stab type ** caches the result of the name server lookup so we don't hang ** multiple times. */ #define NAMECANON struct _namecanon NAMECANON { short nc_errno; /* cached errno */ short nc_herrno; /* cached h_errno */ short nc_stat; /* cached exit status code */ short nc_flags; /* flag bits */ char *nc_cname; /* the canonical name */ time_t nc_exp; /* entry expires at */ }; /* values for nc_flags */ #define NCF_VALID 0x0001 /* entry valid */ /* hostsignature structure */ struct hostsig_t { char *hs_sig; /* hostsignature */ time_t hs_exp; /* entry expires at */ }; typedef struct hostsig_t HOSTSIG_T; /* ** The standard udp packet size PACKETSZ (512) is not sufficient for some ** nameserver answers containing very many resource records. The resolver ** may switch to tcp and retry if it detects udp packet overflow. ** Also note that the resolver routines res_query and res_search return ** the size of the *un*truncated answer in case the supplied answer buffer ** it not big enough to accommodate the entire answer. */ # ifndef MAXPACKET # define MAXPACKET 8192 /* max packet size used internally by BIND */ # endif /* ! MAXPACKET */ /* ** The resolver functions res_{send,query,querydomain} expect the ** answer buffer to be aligned, but some versions of gcc4 reverse ** 25 years of history and no longer align char buffers on the ** stack, resulting in crashes on strict-alignment platforms. Use ** this union when putting the buffer on the stack to force the ** alignment, then cast to (HEADER *) or (unsigned char *) as needed. */ typedef union { HEADER qb1; unsigned char qb2[MAXPACKET]; } querybuf; /* functions */ extern bool getcanonname __P((char *, int, bool, int *)); extern int getmxrr __P((char *, char **, unsigned short *, bool, int *, bool, int *)); extern char *hostsignature __P((MAILER *, char *)); extern int getfallbackmxrr __P((char *)); /* ** Mapping functions ** ** These allow arbitrary mappings in the config file. The idea ** (albeit not the implementation) comes from IDA sendmail. */ #define MAPCLASS struct _mapclass #define MAP struct _map #define MAXMAPACTIONS 5 /* size of map_actions array */ /* ** An actual map. */ MAP { MAPCLASS *map_class; /* the class of this map */ MAPCLASS *map_orgclass; /* the original class of this map */ char *map_mname; /* name of this map */ long map_mflags; /* flags, see below */ char *map_file; /* the (nominal) filename */ ARBPTR_T map_db1; /* the open database ptr */ ARBPTR_T map_db2; /* an "extra" database pointer */ char *map_keycolnm; /* key column name */ char *map_valcolnm; /* value column name */ unsigned char map_keycolno; /* key column number */ unsigned char map_valcolno; /* value column number */ char map_coldelim; /* column delimiter */ char map_spacesub; /* spacesub */ char *map_app; /* to append to successful matches */ char *map_tapp; /* to append to "tempfail" matches */ char *map_domain; /* the (nominal) NIS domain */ char *map_rebuild; /* program to run to do auto-rebuild */ time_t map_mtime; /* last database modification time */ time_t map_timeout; /* timeout for map accesses */ int map_retry; /* # of retries for map accesses */ pid_t map_pid; /* PID of process which opened map */ int map_lockfd; /* auxiliary lock file descriptor */ short map_specificity; /* specificity of aliases */ MAP *map_stack[MAXMAPSTACK]; /* list for stacked maps */ short map_return[MAXMAPACTIONS]; /* return bitmaps for stacked maps */ }; /* bit values for map_mflags */ #define MF_VALID 0x00000001 /* this entry is valid */ #define MF_INCLNULL 0x00000002 /* include null byte in key */ #define MF_OPTIONAL 0x00000004 /* don't complain if map not found */ #define MF_NOFOLDCASE 0x00000008 /* don't fold case in keys */ #define MF_MATCHONLY 0x00000010 /* don't use the map value */ #define MF_OPEN 0x00000020 /* this entry is open */ #define MF_WRITABLE 0x00000040 /* open for writing */ #define MF_ALIAS 0x00000080 /* this is an alias file */ #define MF_TRY0NULL 0x00000100 /* try with no null byte */ #define MF_TRY1NULL 0x00000200 /* try with the null byte */ #define MF_LOCKED 0x00000400 /* this map is currently locked */ #define MF_ALIASWAIT 0x00000800 /* alias map in aliaswait state */ #define MF_IMPL_HASH 0x00001000 /* implicit: underlying hash database */ #define MF_IMPL_NDBM 0x00002000 /* implicit: underlying NDBM database */ /* 0x00004000 */ #define MF_APPEND 0x00008000 /* append new entry on rebuild */ #define MF_KEEPQUOTES 0x00010000 /* don't dequote key before lookup */ #define MF_NODEFER 0x00020000 /* don't defer if map lookup fails */ #define MF_REGEX_NOT 0x00040000 /* regular expression negation */ #define MF_DEFER 0x00080000 /* don't lookup map in defer mode */ #define MF_SINGLEMATCH 0x00100000 /* successful only if match one key */ #define MF_SINGLEDN 0x00200000 /* only one match, but multi values */ #define MF_FILECLASS 0x00400000 /* this is a file class map */ #define MF_OPENBOGUS 0x00800000 /* open failed, don't call map_close */ #define MF_CLOSING 0x01000000 /* map is being closed */ #define DYNOPENMAP(map) \ do \ { \ if (!bitset(MF_OPEN, (map)->map_mflags)) \ { \ if (!openmap(map)) \ return NULL; \ } \ } while (0) /* indices for map_actions */ #define MA_NOTFOUND 0 /* member map returned "not found" */ #define MA_UNAVAIL 1 /* member map is not available */ #define MA_TRYAGAIN 2 /* member map returns temp failure */ /* macros to handle MapTempFail */ #define BIT_IS_MTP 0x01 /* temp.failure occurred */ #define BIT_ASK_MTP 0x02 /* do we care about MapTempFail? */ #define RESET_MAPTEMPFAIL MapTempFail = 0 #define INIT_MAPTEMPFAIL MapTempFail = BIT_ASK_MTP #define SET_MAPTEMPFAIL MapTempFail |= BIT_IS_MTP #define IS_MAPTEMPFAIL bitset(BIT_IS_MTP, MapTempFail) #define ASK_MAPTEMPFAIL bitset(BIT_ASK_MTP, MapTempFail) /* ** The class of a map -- essentially the functions to call */ MAPCLASS { char *map_cname; /* name of this map class */ char *map_ext; /* extension for database file */ short map_cflags; /* flag bits, see below */ bool (*map_parse)__P((MAP *, char *)); /* argument parsing function */ char *(*map_lookup)__P((MAP *, char *, char **, int *)); /* lookup function */ void (*map_store)__P((MAP *, char *, char *)); /* store function */ bool (*map_open)__P((MAP *, int)); /* open function */ void (*map_close)__P((MAP *)); /* close function */ }; /* bit values for map_cflags */ #define MCF_ALIASOK 0x0001 /* can be used for aliases */ #define MCF_ALIASONLY 0x0002 /* usable only for aliases */ #define MCF_REBUILDABLE 0x0004 /* can rebuild alias files */ #define MCF_OPTFILE 0x0008 /* file name is optional */ #define MCF_NOTPERSIST 0x0010 /* don't keep map open all the time */ /* functions */ extern void closemaps __P((bool)); extern bool impl_map_open __P((MAP *, int)); extern void initmaps __P((void)); extern MAP *makemapentry __P((char *)); extern void maplocaluser __P((ADDRESS *, ADDRESS **, int, ENVELOPE *)); extern char *map_rewrite __P((MAP *, const char *, size_t, char **)); #if NETINFO extern char *ni_propval __P((char *, char *, char *, char *, int)); #endif /* NETINFO */ extern bool openmap __P((MAP *)); extern int udbexpand __P((ADDRESS *, ADDRESS **, int, ENVELOPE *)); #if USERDB extern void _udbx_close __P((void)); extern char *udbsender __P((char *, SM_RPOOL_T *)); #endif /* USERDB */ /* ** LDAP related items */ #if LDAPMAP /* struct defining LDAP Auth Methods */ struct lamvalues { char *lam_name; /* name of LDAP auth method */ int lam_code; /* numeric code */ }; /* struct defining LDAP Alias Dereferencing */ struct ladvalues { char *lad_name; /* name of LDAP alias dereferencing method */ int lad_code; /* numeric code */ }; /* struct defining LDAP Search Scope */ struct lssvalues { char *lss_name; /* name of LDAP search scope */ int lss_code; /* numeric code */ }; /* functions */ extern bool ldapmap_parseargs __P((MAP *, char *)); extern void ldapmap_set_defaults __P((char *)); #endif /* LDAPMAP */ /* ** PH related items */ #if PH_MAP # include struct ph_map_struct { char *ph_servers; /* list of ph servers */ char *ph_field_list; /* list of fields to search for match */ PH *ph; /* PH server handle */ int ph_fastclose; /* send "quit" command on close */ time_t ph_timeout; /* timeout interval */ }; typedef struct ph_map_struct PH_MAP_STRUCT; #endif /* PH_MAP */ /* ** Regular UNIX sockaddrs are too small to handle ISO addresses, so ** we are forced to declare a supertype here. */ #if NETINET || NETINET6 || NETUNIX || NETISO || NETNS || NETX25 union bigsockaddr { struct sockaddr sa; /* general version */ # if NETUNIX struct sockaddr_un sunix; /* UNIX family */ # endif /* NETUNIX */ # if NETINET struct sockaddr_in sin; /* INET family */ # endif /* NETINET */ # if NETINET6 struct sockaddr_in6 sin6; /* INET/IPv6 */ # endif /* NETINET6 */ # if NETISO struct sockaddr_iso siso; /* ISO family */ # endif /* NETISO */ # if NETNS struct sockaddr_ns sns; /* XNS family */ # endif /* NETNS */ # if NETX25 struct sockaddr_x25 sx25; /* X.25 family */ # endif /* NETX25 */ }; # define SOCKADDR union bigsockaddr /* functions */ extern char *anynet_ntoa __P((SOCKADDR *)); # if NETINET6 extern char *anynet_ntop __P((struct in6_addr *, char *, size_t)); extern int anynet_pton __P((int, const char *, void *)); # endif /* NETINET6 */ extern char *hostnamebyanyaddr __P((SOCKADDR *)); extern char *validate_connection __P((SOCKADDR *, char *, ENVELOPE *)); # if SASL >= 20000 extern bool iptostring __P((SOCKADDR *, SOCKADDR_LEN_T, char *, unsigned)); # endif /* SASL >= 20000 */ #endif /* NETINET || NETINET6 || NETUNIX || NETISO || NETNS || NETX25 */ /* ** Process List (proclist) */ #define NO_PID ((pid_t) 0) #ifndef PROC_LIST_SEG # define PROC_LIST_SEG 32 /* number of pids to alloc at a time */ #endif /* ! PROC_LIST_SEG */ /* process types */ #define PROC_NONE 0 #define PROC_DAEMON 1 #define PROC_DAEMON_CHILD 2 #define PROC_QUEUE 3 #define PROC_QUEUE_CHILD 3 #define PROC_CONTROL 4 #define PROC_CONTROL_CHILD 5 /* functions */ extern void proc_list_add __P((pid_t, char *, int, int, int, SOCKADDR *)); extern void proc_list_clear __P((void)); extern void proc_list_display __P((SM_FILE_T *, char *)); extern void proc_list_drop __P((pid_t, int, int *)); extern void proc_list_probe __P((void)); extern void proc_list_set __P((pid_t, char *)); extern void proc_list_signal __P((int, int)); /* ** Symbol table definitions */ struct symtab { char *s_name; /* name to be entered */ short s_symtype; /* general type (see below) */ struct symtab *s_next; /* pointer to next in chain */ union { BITMAP256 sv_class; /* bit-map of word classes */ MAILER *sv_mailer; /* pointer to mailer */ char *sv_alias; /* alias */ MAPCLASS sv_mapclass; /* mapping function class */ MAP sv_map; /* mapping function */ HOSTSIG_T sv_hostsig; /* host signature */ MCI sv_mci; /* mailer connection info */ NAMECANON sv_namecanon; /* canonical name cache */ int sv_macro; /* macro name => id mapping */ int sv_ruleset; /* ruleset index */ struct hdrinfo sv_header; /* header metainfo */ char *sv_service[MAXMAPSTACK]; /* service switch */ #if LDAPMAP MAP *sv_lmap; /* Maps for LDAP connection */ #endif /* LDAPMAP */ #if SOCKETMAP MAP *sv_socketmap; /* Maps for SOCKET connection */ #endif /* SOCKETMAP */ #if MILTER struct milter *sv_milter; /* milter filter name */ #endif /* MILTER */ QUEUEGRP *sv_queue; /* pointer to queue */ } s_value; }; typedef struct symtab STAB; /* symbol types */ #define ST_UNDEF 0 /* undefined type */ #define ST_CLASS 1 /* class map */ /* #define ST_unused 2 UNUSED */ #define ST_MAILER 3 /* a mailer header */ #define ST_ALIAS 4 /* an alias */ #define ST_MAPCLASS 5 /* mapping function class */ #define ST_MAP 6 /* mapping function */ #define ST_HOSTSIG 7 /* host signature */ #define ST_NAMECANON 8 /* cached canonical name */ #define ST_MACRO 9 /* macro name to id mapping */ #define ST_RULESET 10 /* ruleset index */ #define ST_SERVICE 11 /* service switch entry */ #define ST_HEADER 12 /* special header flags */ #if LDAPMAP # define ST_LMAP 13 /* List head of maps for LDAP connection */ #endif /* LDAPMAP */ #if MILTER # define ST_MILTER 14 /* milter filter */ #endif /* MILTER */ #define ST_QUEUE 15 /* a queue entry */ #if SOCKETMAP # define ST_SOCKETMAP 16 /* List head of maps for SOCKET connection */ #endif /* SOCKETMAP */ /* This entry must be last */ #define ST_MCI 17 /* mailer connection info (offset) */ #define s_class s_value.sv_class #define s_mailer s_value.sv_mailer #define s_alias s_value.sv_alias #define s_mci s_value.sv_mci #define s_mapclass s_value.sv_mapclass #define s_hostsig s_value.sv_hostsig #define s_map s_value.sv_map #define s_namecanon s_value.sv_namecanon #define s_macro s_value.sv_macro #define s_ruleset s_value.sv_ruleset #define s_service s_value.sv_service #define s_header s_value.sv_header #if LDAPMAP # define s_lmap s_value.sv_lmap #endif /* LDAPMAP */ #if SOCKETMAP # define s_socketmap s_value.sv_socketmap #endif /* SOCKETMAP */ #if MILTER # define s_milter s_value.sv_milter #endif /* MILTER */ #define s_quegrp s_value.sv_queue /* opcodes to stab */ #define ST_FIND 0 /* find entry */ #define ST_ENTER 1 /* enter if not there */ /* functions */ extern STAB *stab __P((char *, int, int)); extern void stabapply __P((void (*)(STAB *, int), int)); /* ** Operation, send, error, and MIME modes ** ** The operation mode describes the basic operation of sendmail. ** This can be set from the command line, and is "send mail" by ** default. ** ** The send mode tells how to send mail. It can be set in the ** configuration file. Its setting determines how quickly the ** mail will be delivered versus the load on your system. If the ** -v (verbose) flag is given, it will be forced to SM_DELIVER ** mode. ** ** The error mode tells how to return errors. */ #define MD_DELIVER 'm' /* be a mail sender */ #define MD_SMTP 's' /* run SMTP on standard input */ #define MD_ARPAFTP 'a' /* obsolete ARPANET mode (Grey Book) */ #define MD_DAEMON 'd' /* run as a daemon */ #define MD_FGDAEMON 'D' /* run daemon in foreground */ #define MD_LOCAL 'l' /* like daemon, but localhost only */ #define MD_VERIFY 'v' /* verify: don't collect or deliver */ #define MD_TEST 't' /* test mode: resolve addrs only */ #define MD_INITALIAS 'i' /* initialize alias database */ #define MD_PRINT 'p' /* print the queue */ #define MD_PRINTNQE 'P' /* print number of entries in queue */ #define MD_FREEZE 'z' /* freeze the configuration file */ #define MD_HOSTSTAT 'h' /* print persistent host stat info */ #define MD_PURGESTAT 'H' /* purge persistent host stat info */ #define MD_QUEUERUN 'q' /* queue run */ #define MD_CHECKCONFIG 'C' /* check configuration file */ #if _FFR_LOCAL_DAEMON EXTERN bool LocalDaemon; # if NETINET6 EXTERN bool V6LoopbackAddrFound; /* found an IPv6 loopback address */ # define SETV6LOOPBACKADDRFOUND(sa) \ do \ { \ if (isloopback(sa)) \ V6LoopbackAddrFound = true; \ } while (0) # endif /* NETINET6 */ #else /* _FFR_LOCAL_DAEMON */ # define LocalDaemon false # define V6LoopbackAddrFound false # define SETV6LOOPBACKADDRFOUND(sa) #endif /* _FFR_LOCAL_DAEMON */ /* Note: see also include/sendmail/pathnames.h: GET_CLIENT_CF */ /* values for e_sendmode -- send modes */ #define SM_DELIVER 'i' /* interactive delivery */ #define SM_FORK 'b' /* deliver in background */ #if _FFR_DM_ONE #define SM_DM_ONE 'o' /* deliver first TA in background, then queue */ #endif /* _FFR_DM_ONE */ #define SM_QUEUE 'q' /* queue, don't deliver */ #define SM_DEFER 'd' /* defer map lookups as well as queue */ #define SM_VERIFY 'v' /* verify only (used internally) */ #define DM_NOTSET (-1) /* DeliveryMode (per daemon) option not set */ # define SM_IS_INTERACTIVE(m) ((m) == SM_DELIVER) #define WILL_BE_QUEUED(m) ((m) == SM_QUEUE || (m) == SM_DEFER) /* used only as a parameter to sendall */ #define SM_DEFAULT '\0' /* unspecified, use SendMode */ /* functions */ extern void set_delivery_mode __P((int, ENVELOPE *)); /* values for e_errormode -- error handling modes */ #define EM_PRINT 'p' /* print errors */ #define EM_MAIL 'm' /* mail back errors */ #define EM_WRITE 'w' /* write back errors */ #define EM_BERKNET 'e' /* special berknet processing */ #define EM_QUIET 'q' /* don't print messages (stat only) */ /* bit values for MimeMode */ #define MM_CVTMIME 0x0001 /* convert 8 to 7 bit MIME */ #define MM_PASS8BIT 0x0002 /* just send 8 bit data blind */ #define MM_MIME8BIT 0x0004 /* convert 8-bit data to MIME */ /* how to handle messages without any recipient addresses */ #define NRA_NO_ACTION 0 /* just leave it as is */ #define NRA_ADD_TO 1 /* add To: header */ #define NRA_ADD_APPARENTLY_TO 2 /* add Apparently-To: header */ #define NRA_ADD_BCC 3 /* add empty Bcc: header */ #define NRA_ADD_TO_UNDISCLOSED 4 /* add To: undisclosed:; header */ /* flags to putxline */ #define PXLF_NOTHINGSPECIAL 0 /* no special mapping */ #define PXLF_MAPFROM 0x0001 /* map From_ to >From_ */ #define PXLF_STRIP8BIT 0x0002 /* strip 8th bit */ #define PXLF_HEADER 0x0004 /* map newlines in headers */ #define PXLF_NOADDEOL 0x0008 /* if EOL not present, don't add one */ #define PXLF_STRIPMQUOTE 0x0010 /* strip METAQUOTEs */ /* ** Privacy flags ** These are bit values for the PrivacyFlags word. */ #define PRIV_PUBLIC 0 /* what have I got to hide? */ #define PRIV_NEEDMAILHELO 0x00000001 /* insist on HELO for MAIL */ #define PRIV_NEEDEXPNHELO 0x00000002 /* insist on HELO for EXPN */ #define PRIV_NEEDVRFYHELO 0x00000004 /* insist on HELO for VRFY */ #define PRIV_NOEXPN 0x00000008 /* disallow EXPN command */ #define PRIV_NOVRFY 0x00000010 /* disallow VRFY command */ #define PRIV_AUTHWARNINGS 0x00000020 /* flag possible auth probs */ #define PRIV_NOVERB 0x00000040 /* disallow VERB command */ #define PRIV_RESTRICTMAILQ 0x00010000 /* restrict mailq command */ #define PRIV_RESTRICTQRUN 0x00020000 /* restrict queue run */ #define PRIV_RESTRICTEXPAND 0x00040000 /* restrict alias/forward expansion */ #define PRIV_NOETRN 0x00080000 /* disallow ETRN command */ #define PRIV_NOBODYRETN 0x00100000 /* do not return bodies on bounces */ #define PRIV_NORECEIPTS 0x00200000 /* disallow return receipts */ #define PRIV_NOACTUALRECIPIENT 0x00400000 /* no X-Actual-Recipient in DSNs */ /* don't give no info, anyway, anyhow (in the main SMTP transaction) */ #define PRIV_GOAWAY 0x0000ffff /* struct defining such things */ struct prival { char *pv_name; /* name of privacy flag */ unsigned long pv_flag; /* numeric level */ }; EXTERN unsigned long PrivacyFlags; /* privacy flags */ /* ** Flags passed to remotename, parseaddr, allocaddr, and buildaddr. */ #define RF_SENDERADDR 0x001 /* this is a sender address */ #define RF_HEADERADDR 0x002 /* this is a header address */ #define RF_CANONICAL 0x004 /* strip comment information */ #define RF_ADDDOMAIN 0x008 /* OK to do domain extension */ #define RF_COPYPARSE 0x010 /* copy parsed user & host */ #define RF_COPYPADDR 0x020 /* copy print address */ #define RF_COPYALL (RF_COPYPARSE|RF_COPYPADDR) #define RF_COPYNONE 0 #define RF_RM_ADDR 0x040 /* address to be removed */ /* ** Flags passed to rscheck */ #define RSF_RMCOMM 0x0001 /* strip comments */ #define RSF_UNSTRUCTURED 0x0002 /* unstructured, ignore syntax errors */ #define RSF_COUNT 0x0004 /* count rejections (statistics)? */ /* ** Flags passed to mime8to7 and putheader. */ #define M87F_OUTER 0 /* outer context */ #define M87F_NO8BIT 0x0001 /* can't have 8-bit in this section */ #define M87F_DIGEST 0x0002 /* processing multipart/digest */ #define M87F_NO8TO7 0x0004 /* don't do 8->7 bit conversions */ /* functions */ extern bool mime7to8 __P((MCI *, HDR *, ENVELOPE *)); extern int mime8to7 __P((MCI *, HDR *, ENVELOPE *, char **, int, int)); /* ** Flags passed to returntosender. */ #define RTSF_NO_BODY 0 /* send headers only */ #define RTSF_SEND_BODY 0x0001 /* include body of message in return */ #define RTSF_PM_BOUNCE 0x0002 /* this is a postmaster bounce */ /* functions */ extern int returntosender __P((char *, ADDRESS *, int, ENVELOPE *)); /* ** Mail Filters (milter) */ /* ** 32-bit type used by milter ** (needed by libmilter even if MILTER isn't defined) */ typedef SM_INT32 mi_int32; #if MILTER # define SMFTO_WRITE 0 /* Timeout for sending information */ # define SMFTO_READ 1 /* Timeout waiting for a response */ # define SMFTO_EOM 2 /* Timeout for ACK/NAK to EOM */ # define SMFTO_CONNECT 3 /* Timeout for connect() */ # define SMFTO_NUM_TO 4 /* Total number of timeouts */ struct milter { char *mf_name; /* filter name */ BITMAP256 mf_flags; /* MTA flags */ mi_int32 mf_fvers; /* filter version */ mi_int32 mf_fflags; /* filter flags */ mi_int32 mf_pflags; /* protocol flags */ char *mf_conn; /* connection info */ int mf_sock; /* connected socket */ char mf_state; /* state of filter */ char mf_lflags; /* "local" flags */ int mf_idx; /* milter number (index) */ time_t mf_timeout[SMFTO_NUM_TO]; /* timeouts */ #if _FFR_MILTER_CHECK /* for testing only */ mi_int32 mf_mta_prot_version; mi_int32 mf_mta_prot_flags; mi_int32 mf_mta_actions; #endif /* _FFR_MILTER_CHECK */ }; #define MI_LFL_NONE 0x00000000 #define MI_LFLAGS_SYM(st) (1 << (st)) /* has its own symlist for stage st */ struct milters { mi_int32 mis_flags; /* filter flags */ }; typedef struct milters milters_T; #define MIS_FL_NONE 0x00000000 /* no requirements... */ #define MIS_FL_DEL_RCPT 0x00000001 /* can delete rcpt */ #define MIS_FL_REJ_RCPT 0x00000002 /* can reject rcpt */ /* MTA flags */ # define SMF_REJECT 'R' /* Reject connection on filter fail */ # define SMF_TEMPFAIL 'T' /* tempfail connection on failure */ # define SMF_TEMPDROP '4' /* 421 connection on failure */ EXTERN struct milter *InputFilters[MAXFILTERS]; EXTERN char *InputFilterList; EXTERN int MilterLogLevel; /* functions */ extern void setup_daemon_milters __P((void)); #endif /* MILTER */ /* ** Vendor codes ** ** Vendors can customize sendmail to add special behaviour, ** generally for back compatibility. Ideally, this should ** be set up in the .cf file using the "V" command. However, ** it's quite reasonable for some vendors to want the default ** be their old version; this can be set using ** -DVENDOR_DEFAULT=VENDOR_xxx ** in the Makefile. ** ** Vendors should apply to sendmail@sendmail.org for ** unique vendor codes. */ #define VENDOR_BERKELEY 1 /* Berkeley-native configuration file */ #define VENDOR_SUN 2 /* Sun-native configuration file */ #define VENDOR_HP 3 /* Hewlett-Packard specific config syntax */ #define VENDOR_IBM 4 /* IBM specific config syntax */ #define VENDOR_SENDMAIL 5 /* Sendmail, Inc. specific config syntax */ #define VENDOR_DEC 6 /* Compaq, DEC, Digital */ /* prototypes for vendor-specific hook routines */ extern void vendor_daemon_setup __P((ENVELOPE *)); extern void vendor_set_uid __P((UID_T)); /* ** Terminal escape codes. ** ** To make debugging output clearer. */ struct termescape { char *te_rv_on; /* turn reverse-video on */ char *te_under_on; /* turn underlining on */ char *te_normal; /* revert to normal output */ }; /* ** Additional definitions */ /* ** d_flags, see daemon.c ** general rule: lower case: required, upper case: No */ #define D_AUTHREQ 'a' /* authentication required */ #define D_BINDIF 'b' /* use if_addr for outgoing connection */ #define D_CANONREQ 'c' /* canonification required (cf) */ #define D_IFNHELO 'h' /* use if name for HELO */ #define D_FQMAIL 'f' /* fq sender address required (cf) */ #define D_FQRCPT 'r' /* fq recipient address required (cf) */ #define D_SMTPS 's' /* SMTP over SSL (smtps) */ #define D_UNQUALOK 'u' /* unqualified address is ok (cf) */ #define D_NOAUTH 'A' /* no AUTH */ #define D_NOCANON 'C' /* no canonification (cf) */ #define D_NOETRN 'E' /* no ETRN (MSA) */ #define D_NOTLS 'S' /* don't use STARTTLS */ #define D_ETRNONLY ((char)0x01) /* allow only ETRN (disk low) */ #define D_OPTIONAL 'O' /* optional socket */ #define D_DISABLE ((char)0x02) /* optional socket disabled */ #define D_ISSET ((char)0x03) /* this client struct is set */ #if STARTTLS /* ** TLS */ /* what to do in the TLS initialization */ #define TLS_I_NONE 0x00000000 /* no requirements... */ #define TLS_I_CERT_EX 0x00000001 /* cert must exist */ #define TLS_I_CERT_UNR 0x00000002 /* cert must be g/o unreadable */ #define TLS_I_KEY_EX 0x00000004 /* key must exist */ #define TLS_I_KEY_UNR 0x00000008 /* key must be g/o unreadable */ #define TLS_I_CERTP_EX 0x00000010 /* CA cert path must exist */ #define TLS_I_CERTP_UNR 0x00000020 /* CA cert path must be g/o unreadable */ #define TLS_I_CERTF_EX 0x00000040 /* CA cert file must exist */ #define TLS_I_CERTF_UNR 0x00000080 /* CA cert file must be g/o unreadable */ #define TLS_I_RSA_TMP 0x00000100 /* RSA TMP must be generated */ #define TLS_I_USE_KEY 0x00000200 /* private key must usable */ #define TLS_I_USE_CERT 0x00000400 /* certificate must be usable */ #define TLS_I_VRFY_PATH 0x00000800 /* load verify path must succeed */ #define TLS_I_VRFY_LOC 0x00001000 /* load verify default must succeed */ #define TLS_I_CACHE 0x00002000 /* require cache */ #define TLS_I_TRY_DH 0x00004000 /* try DH certificate */ #define TLS_I_REQ_DH 0x00008000 /* require DH certificate */ #define TLS_I_DHPAR_EX 0x00010000 /* require DH parameters */ #define TLS_I_DHPAR_UNR 0x00020000 /* DH param. must be g/o unreadable */ #define TLS_I_DH512 0x00040000 /* generate 512bit DH param */ #define TLS_I_DH1024 0x00080000 /* generate 1024bit DH param */ #define TLS_I_DH2048 0x00100000 /* generate 2048bit DH param */ #define TLS_I_NO_VRFY 0x00200000 /* do not require authentication */ #define TLS_I_KEY_OUNR 0x00400000 /* Key must be other unreadable */ #define TLS_I_CRLF_EX 0x00800000 /* CRL file must exist */ #define TLS_I_CRLF_UNR 0x01000000 /* CRL file must be g/o unreadable */ /* require server cert */ #define TLS_I_SRV_CERT (TLS_I_CERT_EX | TLS_I_KEY_EX | \ TLS_I_KEY_UNR | TLS_I_KEY_OUNR | \ TLS_I_CERTP_EX | TLS_I_CERTF_EX | \ TLS_I_USE_KEY | TLS_I_USE_CERT | TLS_I_CACHE) /* server requirements */ #define TLS_I_SRV (TLS_I_SRV_CERT | TLS_I_RSA_TMP | TLS_I_VRFY_PATH | \ TLS_I_VRFY_LOC | TLS_I_TRY_DH | TLS_I_DH512 | \ TLS_I_CACHE) /* client requirements */ #define TLS_I_CLT (TLS_I_KEY_UNR | TLS_I_KEY_OUNR) #define TLS_AUTH_OK 0 #define TLS_AUTH_NO 1 #define TLS_AUTH_FAIL (-1) /* functions */ -extern bool init_tls_library __P((void)); +extern bool init_tls_library __P((bool _fipsmode)); extern bool inittls __P((SSL_CTX **, unsigned long, long, bool, char *, char *, char *, char *, char *)); extern bool initclttls __P((bool)); extern void setclttls __P((bool)); extern bool initsrvtls __P((bool)); extern int tls_get_info __P((SSL *, bool, char *, MACROS_T *, bool)); extern int endtls __P((SSL *, char *)); -extern void tlslogerr __P((const char *)); +extern void tlslogerr __P((int, const char *)); EXTERN char *CACertPath; /* path to CA certificates (dir. with hashes) */ EXTERN char *CACertFile; /* file with CA certificate */ EXTERN char *CltCertFile; /* file with client certificate */ EXTERN char *CltKeyFile; /* file with client private key */ # if _FFR_TLS_1 EXTERN char *CipherList; /* list of ciphers */ EXTERN char *DHParams5; /* file with DH parameters (512) */ # endif /* _FFR_TLS_1 */ EXTERN char *DHParams; /* file with DH parameters */ EXTERN char *RandFile; /* source of random data */ EXTERN char *SrvCertFile; /* file with server certificate */ EXTERN char *SrvKeyFile; /* file with server private key */ EXTERN char *CRLFile; /* file CRLs */ #if _FFR_CRLPATH EXTERN char *CRLPath; /* path to CRLs (dir. with hashes) */ #endif /* _FFR_CRLPATH */ EXTERN unsigned long TLS_Srv_Opts; /* TLS server options */ EXTERN long Srv_SSL_Options, Clt_SSL_Options; /* SSL options */ #endif /* STARTTLS */ /* ** Queue related items */ /* queue file names */ #define ANYQFL_LETTER '?' #define QUARQF_LETTER 'h' #define DATAFL_LETTER 'd' #define XSCRPT_LETTER 'x' #define NORMQF_LETTER 'q' #define NEWQFL_LETTER 't' # define TEMPQF_LETTER 'T' # define LOSEQF_LETTER 'Q' /* queue sort order */ #define QSO_BYPRIORITY 0 /* sort by message priority */ #define QSO_BYHOST 1 /* sort by first host name */ #define QSO_BYTIME 2 /* sort by submission time */ #define QSO_BYFILENAME 3 /* sort by file name only */ #define QSO_RANDOM 4 /* sort in random order */ #define QSO_BYMODTIME 5 /* sort by modification time */ #define QSO_NONE 6 /* do not sort */ #if _FFR_RHS # define QSO_BYSHUFFLE 7 /* sort by shuffled host name */ #endif /* _FFR_RHS */ #define NOQGRP (-1) /* no queue group (yet) */ #define ENVQGRP (-2) /* use queue group of envelope */ #define NOAQGRP (-3) /* no queue group in addr (yet) */ #define ISVALIDQGRP(x) ((x) >= 0) /* valid queue group? */ #define NOQDIR (-1) /* no queue directory (yet) */ #define ENVQDIR (-2) /* use queue directory of envelope */ #define NOAQDIR (-3) /* no queue directory in addr (yet) */ #define ISVALIDQDIR(x) ((x) >= 0) /* valid queue directory? */ #define RS_QUEUEGROUP "queuegroup" /* ruleset for queue group selection */ #define NOW ((time_t) (-1)) /* queue return: now */ /* SuperSafe values */ #define SAFE_NO 0 /* no fsync(): don't use... */ #define SAFE_INTERACTIVE 1 /* limit fsync() in -odi */ #define SAFE_REALLY 2 /* always fsync() */ #define SAFE_REALLY_POSTMILTER 3 /* fsync() if milter says OK */ /* QueueMode bits */ #define QM_NORMAL ' ' #define QM_QUARANTINE 'Q' #define QM_LOST 'L' /* Queue Run Limitations */ struct queue_char { char *queue_match; /* string to match */ bool queue_negate; /* or not match, if set */ struct queue_char *queue_next; }; /* run_work_group() flags */ #define RWG_NONE 0x0000 #define RWG_FORK 0x0001 #define RWG_VERBOSE 0x0002 #define RWG_PERSISTENT 0x0004 #define RWG_FORCE 0x0008 #define RWG_RUNALL 0x0010 typedef struct queue_char QUEUE_CHAR; EXTERN int volatile CurRunners; /* current number of runner children */ EXTERN int MaxQueueRun; /* maximum number of jobs in one queue run */ EXTERN int MaxQueueChildren; /* max # of forked queue children */ EXTERN int MaxRunnersPerQueue; /* max # proc's active in queue group */ EXTERN int NiceQueueRun; /* nice queue runs to this value */ EXTERN int NumQueue; /* number of queue groups */ EXTERN int QueueFileMode; /* mode on files in mail queue */ EXTERN int QueueMode; /* which queue items to act upon */ EXTERN int QueueSortOrder; /* queue sorting order algorithm */ EXTERN time_t MinQueueAge; /* min delivery interval */ #if _FFR_EXPDELAY EXTERN time_t MaxQueueAge; /* max delivery interval */ #endif /* _FFR_EXPDELAY */ EXTERN time_t QueueIntvl; /* intervals between running the queue */ EXTERN char *QueueDir; /* location of queue directory */ EXTERN QUEUE_CHAR *QueueLimitId; /* limit queue run to id */ EXTERN QUEUE_CHAR *QueueLimitQuarantine; /* limit queue run to quarantine reason */ EXTERN QUEUE_CHAR *QueueLimitRecipient; /* limit queue run to rcpt */ EXTERN QUEUE_CHAR *QueueLimitSender; /* limit queue run to sender */ EXTERN QUEUEGRP *Queue[MAXQUEUEGROUPS + 1]; /* queue groups */ /* functions */ extern void assign_queueid __P((ENVELOPE *)); extern ADDRESS *copyqueue __P((ADDRESS *, SM_RPOOL_T *)); extern void cleanup_queues __P((void)); extern bool doqueuerun __P((void)); extern void initsys __P((ENVELOPE *)); extern void loseqfile __P((ENVELOPE *, char *)); extern int name2qid __P((char *)); extern char *qid_printname __P((ENVELOPE *)); extern char *qid_printqueue __P((int, int)); extern void quarantine_queue __P((char *, int)); extern char *queuename __P((ENVELOPE *, int)); extern void queueup __P((ENVELOPE *, bool, bool)); extern bool runqueue __P((bool, bool, bool, bool)); extern bool run_work_group __P((int, int)); extern void set_def_queueval __P((QUEUEGRP *, bool)); extern void setup_queues __P((bool)); extern bool setnewqueue __P((ENVELOPE *)); extern bool shouldqueue __P((long, time_t)); extern void sync_queue_time __P((void)); extern void init_qid_alg __P((void)); extern int print_single_queue __P((int, int)); #if REQUIRES_DIR_FSYNC # define SYNC_DIR(path, panic) sync_dir(path, panic) extern void sync_dir __P((char *, bool)); #else /* REQUIRES_DIR_FSYNC */ # define SYNC_DIR(path, panic) ((void) 0) #endif /* REQUIRES_DIR_FSYNC */ /* ** Timeouts ** ** Indicated values are the MINIMUM per RFC 1123 section 5.3.2. */ EXTERN struct { /* RFC 1123-specified timeouts [minimum value] */ time_t to_initial; /* initial greeting timeout [5m] */ time_t to_mail; /* MAIL command [5m] */ time_t to_rcpt; /* RCPT command [5m] */ time_t to_datainit; /* DATA initiation [2m] */ time_t to_datablock; /* DATA block [3m] */ time_t to_datafinal; /* DATA completion [10m] */ time_t to_nextcommand; /* next command [5m] */ /* following timeouts are not mentioned in RFC 1123 */ time_t to_iconnect; /* initial connection timeout (first try) */ time_t to_connect; /* initial connection timeout (later tries) */ time_t to_aconnect; /* all connections timeout (MX and A records) */ time_t to_rset; /* RSET command */ time_t to_helo; /* HELO command */ time_t to_quit; /* QUIT command */ time_t to_miscshort; /* misc short commands (NOOP, VERB, etc) */ time_t to_ident; /* IDENT protocol requests */ time_t to_fileopen; /* opening :include: and .forward files */ time_t to_control; /* process a control socket command */ time_t to_lhlo; /* LMTP: LHLO command */ #if SASL time_t to_auth; /* AUTH dialogue [10m] */ #endif /* SASL */ #if STARTTLS time_t to_starttls; /* STARTTLS dialogue [10m] */ #endif /* STARTTLS */ /* following are per message */ time_t to_q_return[MAXTOCLASS]; /* queue return timeouts */ time_t to_q_warning[MAXTOCLASS]; /* queue warning timeouts */ time_t res_retrans[MAXRESTOTYPES]; /* resolver retransmit */ int res_retry[MAXRESTOTYPES]; /* resolver retry */ } TimeOuts; /* timeout classes for return and warning timeouts */ #define TOC_NORMAL 0 /* normal delivery */ #define TOC_URGENT 1 /* urgent delivery */ #define TOC_NONURGENT 2 /* non-urgent delivery */ #define TOC_DSN 3 /* DSN delivery */ /* resolver timeout specifiers */ #define RES_TO_FIRST 0 /* first attempt */ #define RES_TO_NORMAL 1 /* subsequent attempts */ #define RES_TO_DEFAULT 2 /* default value */ /* functions */ extern void inittimeouts __P((char *, bool)); /* ** Interface probing */ #define DPI_PROBENONE 0 /* Don't probe any interfaces */ #define DPI_PROBEALL 1 /* Probe all interfaces */ #define DPI_SKIPLOOPBACK 2 /* Don't probe loopback interfaces */ /* ** Trace information */ /* macros for debugging flags */ #if NOT_SENDMAIL # define tTd(flag, level) (tTdvect[flag] >= (unsigned char)level) #else # define tTd(flag, level) (tTdvect[flag] >= (unsigned char)level && !IntSig) #endif #define tTdlevel(flag) (tTdvect[flag]) /* variables */ extern unsigned char tTdvect[100]; /* trace vector */ /* ** Miscellaneous information. */ /* ** The "no queue id" queue id for sm_syslog */ #define NOQID "" #define CURHOSTNAME (CurHostName == NULL ? "local" : CurHostName) /* ** Some in-line functions */ /* set exit status */ #define setstat(s) \ do \ { \ if (ExitStat == EX_OK || ExitStat == EX_TEMPFAIL) \ ExitStat = s; \ } while (0) #define STRUCTCOPY(s, d) d = s /* free a pointer if it isn't NULL and set it to NULL */ #define SM_FREE_CLR(p) \ do \ { \ if ((p) != NULL) \ { \ sm_free(p); \ (p) = NULL; \ } \ } while (0) /* ** Update a permanent string variable with a new value. ** The old value is freed, the new value is strdup'ed. ** ** We use sm_pstrdup_x to duplicate the string because it raises ** an exception on error, and because it allocates "permanent storage" ** which is not expected to be freed before process exit. ** The latter is important for memory leak analysis. ** ** If an exception occurs while strdup'ing the new value, ** then the variable remains set to the old value. ** That's why the strdup must occur before we free the old value. ** ** The macro uses a do loop so that this idiom will work: ** if (...) ** PSTRSET(var, val1); ** else ** PSTRSET(var, val2); */ #define PSTRSET(var, val) \ do \ { \ char *_newval = sm_pstrdup_x(val); \ if (var != NULL) \ sm_free(var); \ var = _newval; \ } while (0) #define _CHECK_RESTART \ do \ { \ if (ShutdownRequest != NULL) \ shutdown_daemon(); \ else if (RestartRequest != NULL) \ restart_daemon(); \ else if (RestartWorkGroup) \ restart_marked_work_groups(); \ } while (0) # define CHECK_RESTART _CHECK_RESTART #define CHK_CUR_RUNNERS(fct, idx, count) \ do \ { \ if (CurRunners < 0) \ { \ if (LogLevel > 3) \ sm_syslog(LOG_ERR, NOQID, \ "%s: CurRunners=%d, i=%d, count=%d, status=should not happen", \ fct, CurRunners, idx, count); \ CurRunners = 0; \ } \ } while (0) /* reply types (text in SmtpMsgBuffer) */ #define XS_DEFAULT 0 #define XS_STARTTLS 1 #define XS_AUTH 2 #define XS_GREET 3 #define XS_EHLO 4 #define XS_MAIL 5 #define XS_RCPT 6 #define XS_DATA 7 #define XS_EOM 8 #define XS_DATA2 9 #define XS_RCPT2 10 #define XS_QUIT 15 /* ** Global variables. */ #if _FFR_ADDR_TYPE_MODES EXTERN bool AddrTypeModes; /* addr_type: extra "mode" information */ #endif /* _FFR_ADDR_TYPE_MODES */ EXTERN bool AllowBogusHELO; /* allow syntax errors on HELO command */ EXTERN bool CheckAliases; /* parse addresses during newaliases */ #if _FFR_QUEUE_RUN_PARANOIA EXTERN int CheckQueueRunners; /* check whether queue runners are OK */ #endif /* _FFR_QUEUE_RUN_PARANOIA */ EXTERN bool ColonOkInAddr; /* single colon legal in address */ #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) EXTERN bool ConfigFileRead; /* configuration file has been read */ #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */ EXTERN bool DisConnected; /* running with OutChannel redirect to transcript file */ EXTERN bool DontExpandCnames; /* do not $[...$] expand CNAMEs */ EXTERN bool DontInitGroups; /* avoid initgroups() because of NIS cost */ EXTERN bool DontLockReadFiles; /* don't read lock support files */ EXTERN bool DontPruneRoutes; /* don't prune source routes */ EXTERN bool ForkQueueRuns; /* fork for each job when running the queue */ EXTERN bool FromFlag; /* if set, "From" person is explicit */ +EXTERN bool FipsMode; EXTERN bool GrabTo; /* if set, get recipients from msg */ EXTERN bool EightBitAddrOK; /* we'll let 8-bit addresses through */ EXTERN bool HasEightBits; /* has at least one eight bit input byte */ EXTERN bool HasWildcardMX; /* don't use MX records when canonifying */ EXTERN bool HoldErrs; /* only output errors to transcript */ EXTERN bool IgnoreHostStatus; /* ignore long term host status files */ EXTERN bool IgnrDot; /* don't let dot end messages */ EXTERN bool LogUsrErrs; /* syslog user errors (e.g., SMTP RCPT cmd) */ EXTERN bool MatchGecos; /* look for user names in gecos field */ EXTERN bool MeToo; /* send to the sender also */ EXTERN bool NoAlias; /* suppress aliasing */ EXTERN bool NoConnect; /* don't connect to non-local mailers */ EXTERN bool OnlyOneError; /* .... or only want to give one SMTP reply */ EXTERN bool QuickAbort; /* .... but only if we want a quick abort */ +#if _FFR_REJECT_NUL_BYTE +EXTERN bool RejectNUL; /* reject NUL input byte? */ +#endif /* _FFR_REJECT_NUL_BYTE */ #if REQUIRES_DIR_FSYNC EXTERN bool RequiresDirfsync; /* requires fsync() for directory */ #endif /* REQUIRES_DIR_FSYNC */ EXTERN bool volatile RestartWorkGroup; /* daemon needs to restart some work groups */ EXTERN bool RrtImpliesDsn; /* turn Return-Receipt-To: into DSN */ EXTERN bool SaveFrom; /* save leading "From" lines */ EXTERN bool SendMIMEErrors; /* send error messages in MIME format */ EXTERN bool SevenBitInput; /* force 7-bit data on input */ EXTERN bool SingleLineFromHeader; /* force From: header to be one line */ EXTERN bool SingleThreadDelivery; /* single thread hosts on delivery */ EXTERN bool SoftBounce; /* replace 5xy by 4xy (for testing) */ EXTERN bool volatile StopRequest; /* stop sending output */ EXTERN bool SuprErrs; /* set if we are suppressing errors */ EXTERN bool TryNullMXList; /* if we are the best MX, try host directly */ EXTERN bool UseMSP; /* mail submission: group writable queue ok? */ EXTERN bool WorkAroundBrokenAAAA; /* some nameservers return SERVFAIL on AAAA queries */ EXTERN bool UseErrorsTo; /* use Errors-To: header (back compat) */ EXTERN bool UseNameServer; /* using DNS -- interpret h_errno & MX RRs */ EXTERN char InetMode; /* default network for daemon mode */ EXTERN char OpMode; /* operation mode, see below */ EXTERN char SpaceSub; /* substitution for */ #if _FFR_BADRCPT_SHUTDOWN EXTERN int BadRcptShutdown; /* Shutdown connection for rejected RCPTs */ EXTERN int BadRcptShutdownGood; /* above even when there are good RCPTs */ #endif /* _FFR_BADRCPT_SHUTDOWN */ EXTERN int BadRcptThrottle; /* Throttle rejected RCPTs per SMTP message */ #if _FFR_RCPTTHROTDELAY EXTERN unsigned int BadRcptThrottleDelay; /* delay for BadRcptThrottle */ #else # define BadRcptThrottleDelay 1 #endif /* _FFR_RCPTTHROTDELAY */ EXTERN int CheckpointInterval; /* queue file checkpoint interval */ EXTERN int ConfigLevel; /* config file level */ EXTERN int ConnRateThrottle; /* throttle for SMTP connection rate */ EXTERN int volatile CurChildren; /* current number of daemonic children */ EXTERN int CurrentLA; /* current load average */ EXTERN int DefaultNotify; /* default DSN notification flags */ EXTERN int DelayLA; /* load average to delay connections */ EXTERN int DontProbeInterfaces; /* don't probe interfaces for names */ EXTERN int Errors; /* set if errors (local to single pass) */ EXTERN int ExitStat; /* exit status code */ EXTERN int FastSplit; /* fast initial splitting of envelopes */ EXTERN int FileMode; /* mode on files */ EXTERN int LineNumber; /* line number in current input */ EXTERN int LogLevel; /* level of logging to perform */ EXTERN int MaxAliasRecursion; /* maximum depth of alias recursion */ EXTERN int MaxChildren; /* maximum number of daemonic children */ EXTERN int MaxForwardEntries; /* maximum number of forward entries */ EXTERN int MaxHeadersLength; /* max length of headers */ EXTERN int MaxHopCount; /* max # of hops until bounce */ EXTERN int MaxMacroRecursion; /* maximum depth of macro recursion */ EXTERN int MaxMimeFieldLength; /* maximum MIME field length */ EXTERN int MaxMimeHeaderLength; /* maximum MIME header length */ EXTERN int MaxNOOPCommands; /* max "noise" commands before slowdown */ EXTERN int MaxRcptPerMsg; /* max recipients per SMTP message */ EXTERN int MaxRuleRecursion; /* maximum depth of ruleset recursion */ #if _FFR_MSG_ACCEPT EXTERN char *MessageAccept; /* "Message accepted for delivery" reply text */ #endif /* _FFR_MSG_ACCEPT */ EXTERN int MimeMode; /* MIME processing mode */ EXTERN int NoRecipientAction; #if SM_CONF_SHM EXTERN int Numfilesys; /* number of queue file systems */ EXTERN int *PNumFileSys; # define NumFileSys (*PNumFileSys) # else /* SM_CONF_SHM */ EXTERN int NumFileSys; /* number of queue file systems */ # endif /* SM_CONF_SHM */ EXTERN int QueueLA; /* load average starting forced queueing */ EXTERN int RefuseLA; /* load average refusing connections */ EXTERN time_t RejectLogInterval; /* time btwn log msgs while refusing */ #if _FFR_MEMSTAT EXTERN long QueueLowMem; /* low memory starting forced queueing */ EXTERN long RefuseLowMem; /* low memory refusing connections */ EXTERN char *MemoryResource;/* memory resource to look up */ #endif /* _FFR_MEMSTAT */ EXTERN int SuperSafe; /* be extra careful, even if expensive */ EXTERN int VendorCode; /* vendor-specific operation enhancements */ EXTERN int Verbose; /* set if blow-by-blow desired */ EXTERN gid_t DefGid; /* default gid to run as */ EXTERN gid_t RealGid; /* real gid of caller */ EXTERN gid_t RunAsGid; /* GID to become for bulk of run */ EXTERN gid_t EffGid; /* effective gid */ #if SM_CONF_SHM EXTERN key_t ShmKey; /* shared memory key */ EXTERN char *ShmKeyFile; /* shared memory key file */ #endif /* SM_CONF_SHM */ EXTERN pid_t CurrentPid; /* current process id */ EXTERN pid_t DaemonPid; /* process id of daemon */ EXTERN pid_t PidFilePid; /* daemon/queue runner who wrote pid file */ EXTERN uid_t DefUid; /* default uid to run as */ EXTERN uid_t RealUid; /* real uid of caller */ EXTERN uid_t RunAsUid; /* UID to become for bulk of run */ EXTERN uid_t TrustedUid; /* uid of trusted user for files and startup */ EXTERN size_t DataFileBufferSize; /* size of buf for in-core data file */ EXTERN time_t DeliverByMin; /* deliver by minimum time */ EXTERN time_t DialDelay; /* delay between dial-on-demand tries */ EXTERN time_t SafeAlias; /* interval to wait until @:@ in alias file */ EXTERN time_t ServiceCacheMaxAge; /* refresh interval for cache */ EXTERN size_t XscriptFileBufferSize; /* size of buf for in-core transcript file */ EXTERN MODE_T OldUmask; /* umask when sendmail starts up */ EXTERN long MaxMessageSize; /* advertised max size we will accept */ EXTERN long MinBlocksFree; /* min # of blocks free on queue fs */ EXTERN long QueueFactor; /* slope of queue function */ EXTERN long WkClassFact; /* multiplier for message class -> priority */ EXTERN long WkRecipFact; /* multiplier for # of recipients -> priority */ EXTERN long WkTimeFact; /* priority offset each time this job is run */ EXTERN char *ControlSocketName; /* control socket filename [control.c] */ EXTERN char *CurHostName; /* current host we are dealing with */ EXTERN char *DeadLetterDrop; /* path to dead letter office */ EXTERN char *DefUser; /* default user to run as (from DefUid) */ EXTERN char *DefaultCharSet; /* default character set for MIME */ EXTERN char *DoubleBounceAddr; /* where to send double bounces */ EXTERN char *ErrMsgFile; /* file to prepend to all error messages */ EXTERN char *FallbackMX; /* fall back MX host */ EXTERN char *FallbackSmartHost; /* fall back smart host */ EXTERN char *FileName; /* name to print on error messages */ EXTERN char *ForwardPath; /* path to search for .forward files */ EXTERN char *HeloName; /* hostname to announce in HELO */ EXTERN char *HelpFile; /* location of SMTP help file */ EXTERN char *HostStatDir; /* location of host status information */ EXTERN char *HostsFile; /* path to /etc/hosts file */ extern char *Mbdb; /* mailbox database type */ EXTERN char *MustQuoteChars; /* quote these characters in phrases */ EXTERN char *MyHostName; /* name of this host for SMTP messages */ EXTERN char *OperatorChars; /* operators (old $o macro) */ EXTERN char *PidFile; /* location of proc id file [conf.c] */ EXTERN char *PostMasterCopy; /* address to get errs cc's */ EXTERN char *ProcTitlePrefix; /* process title prefix */ EXTERN char *RealHostName; /* name of host we are talking to */ EXTERN char *RealUserName; /* real user name of caller */ EXTERN char *volatile RestartRequest;/* a sendmail restart has been requested */ EXTERN char *RunAsUserName; /* user to become for bulk of run */ EXTERN char *SafeFileEnv; /* chroot location for file delivery */ EXTERN char *ServiceSwitchFile; /* backup service switch */ EXTERN char *volatile ShutdownRequest;/* a sendmail shutdown has been requested */ EXTERN bool volatile IntSig; EXTERN char *SmtpGreeting; /* SMTP greeting message (old $e macro) */ EXTERN char *SmtpPhase; /* current phase in SMTP processing */ EXTERN char SmtpError[MAXLINE]; /* save failure error messages */ EXTERN char *StatFile; /* location of statistics summary */ EXTERN char *TimeZoneSpec; /* override time zone specification */ EXTERN char *UdbSpec; /* user database source spec */ EXTERN char *UnixFromLine; /* UNIX From_ line (old $l macro) */ EXTERN char **ExternalEnviron; /* saved user (input) environment */ EXTERN char **SaveArgv; /* argument vector for re-execing */ EXTERN BITMAP256 DontBlameSendmail; /* DontBlameSendmail bits */ EXTERN SM_FILE_T *InChannel; /* input connection */ EXTERN SM_FILE_T *OutChannel; /* output connection */ EXTERN SM_FILE_T *TrafficLogFile; /* file in which to log all traffic */ #if HESIOD EXTERN void *HesiodContext; #endif /* HESIOD */ EXTERN ENVELOPE *CurEnv; /* envelope currently being processed */ EXTERN char *RuleSetNames[MAXRWSETS]; /* ruleset number to name */ EXTERN char *UserEnviron[MAXUSERENVIRON + 1]; EXTERN struct rewrite *RewriteRules[MAXRWSETS]; EXTERN struct termescape TermEscape; /* terminal escape codes */ EXTERN SOCKADDR ConnectOnlyTo; /* override connection address (for testing) */ EXTERN SOCKADDR RealHostAddr; /* address of host we are talking to */ extern const SM_EXC_TYPE_T EtypeQuickAbort; /* type of a QuickAbort exception */ EXTERN int ConnectionRateWindowSize; #if STARTTLS && USE_OPENSSL_ENGINE EXTERN bool SSLEngineInitialized; #endif /* STARTTLS && USE_OPENSSL_ENGINE */ /* ** Declarations of useful functions */ /* Transcript file */ extern void closexscript __P((ENVELOPE *)); extern void openxscript __P((ENVELOPE *)); /* error related */ extern void buffer_errors __P((void)); extern void flush_errors __P((bool)); extern void PRINTFLIKE(1, 2) message __P((const char *, ...)); extern void PRINTFLIKE(1, 2) nmessage __P((const char *, ...)); extern void PRINTFLIKE(1, 2) syserr __P((const char *, ...)); extern void PRINTFLIKE(2, 3) usrerrenh __P((char *, const char *, ...)); extern void PRINTFLIKE(1, 2) usrerr __P((const char *, ...)); extern int isenhsc __P((const char *, int)); extern int extenhsc __P((const char *, int, char *)); /* alias file */ extern void alias __P((ADDRESS *, ADDRESS **, int, ENVELOPE *)); extern bool aliaswait __P((MAP *, char *, bool)); extern void forward __P((ADDRESS *, ADDRESS **, int, ENVELOPE *)); extern void readaliases __P((MAP *, SM_FILE_T *, bool, bool)); extern bool rebuildaliases __P((MAP *, bool)); extern void setalias __P((char *)); /* logging */ extern void logdelivery __P((MAILER *, MCI *, char *, const char *, ADDRESS *, time_t, ENVELOPE *)); extern void logsender __P((ENVELOPE *, char *)); extern void PRINTFLIKE(3, 4) sm_syslog __P((int, const char *, const char *, ...)); /* SMTP */ extern void giveresponse __P((int, char *, MAILER *, MCI *, ADDRESS *, time_t, ENVELOPE *, ADDRESS *)); extern int reply __P((MAILER *, MCI *, ENVELOPE *, time_t, void (*)__P((char *, bool, MAILER *, MCI *, ENVELOPE *)), char **, int)); extern void smtp __P((char *volatile, BITMAP256, ENVELOPE *volatile)); #if SASL extern int smtpauth __P((MAILER *, MCI *, ENVELOPE *)); #endif /* SASL */ extern int smtpdata __P((MAILER *, MCI *, ENVELOPE *, ADDRESS *, time_t)); extern int smtpgetstat __P((MAILER *, MCI *, ENVELOPE *)); extern int smtpmailfrom __P((MAILER *, MCI *, ENVELOPE *)); extern void smtpmessage __P((char *, MAILER *, MCI *, ...)); extern void smtpinit __P((MAILER *, MCI *, ENVELOPE *, bool)); extern char *smtptodsn __P((int)); extern int smtpprobe __P((MCI *)); extern void smtpquit __P((MAILER *, MCI *, ENVELOPE *)); extern int smtprcpt __P((ADDRESS *, MAILER *, MCI *, ENVELOPE *, ADDRESS *, time_t)); extern void smtprset __P((MAILER *, MCI *, ENVELOPE *)); #define REPLYTYPE(r) ((r) / 100) /* first digit of reply code */ #define REPLYCLASS(r) (((r) / 10) % 10) /* second digit of reply code */ #define REPLYMINOR(r) ((r) % 10) /* last digit of reply code */ #define ISSMTPCODE(c) (isascii(c[0]) && isdigit(c[0]) && \ isascii(c[1]) && isdigit(c[1]) && \ isascii(c[2]) && isdigit(c[2])) #define ISSMTPREPLY(c) (ISSMTPCODE(c) && \ (c[3] == ' ' || c[3] == '-' || c[3] == '\0')) /* delivery */ extern pid_t dowork __P((int, int, char *, bool, bool, ENVELOPE *)); extern pid_t doworklist __P((ENVELOPE *, bool, bool)); extern int endmailer __P((MCI *, ENVELOPE *, char **)); extern int mailfile __P((char *volatile, MAILER *volatile, ADDRESS *, volatile long, ENVELOPE *)); extern void sendall __P((ENVELOPE *, int)); /* stats */ #define STATS_NORMAL 'n' #define STATS_QUARANTINE 'q' #define STATS_REJECT 'r' #define STATS_CONNECT 'c' extern void markstats __P((ENVELOPE *, ADDRESS *, int)); extern void clearstats __P((void)); extern void poststats __P((char *)); /* control socket */ extern void closecontrolsocket __P((bool)); extern void clrcontrol __P((void)); extern void control_command __P((int, ENVELOPE *)); extern int opencontrolsocket __P((void)); #if MILTER /* milter functions */ extern void milter_config __P((char *, struct milter **, int)); extern void milter_setup __P((char *)); extern void milter_set_option __P((char *, char *, bool)); extern bool milter_init __P((ENVELOPE *, char *, milters_T *)); extern void milter_quit __P((ENVELOPE *)); extern void milter_abort __P((ENVELOPE *)); extern char *milter_connect __P((char *, SOCKADDR, ENVELOPE *, char *)); extern char *milter_helo __P((char *, ENVELOPE *, char *)); extern char *milter_envfrom __P((char **, ENVELOPE *, char *)); extern char *milter_data_cmd __P((ENVELOPE *, char *)); extern char *milter_envrcpt __P((char **, ENVELOPE *, char *, bool)); extern char *milter_data __P((ENVELOPE *, char *)); extern char *milter_unknown __P((char *, ENVELOPE *, char *)); #endif /* MILTER */ extern char *addquotes __P((char *, SM_RPOOL_T *)); extern char *arpadate __P((char *)); extern bool atobool __P((char *)); extern int atooct __P((char *)); extern void auth_warning __P((ENVELOPE *, const char *, ...)); extern int blocksignal __P((int)); extern bool bitintersect __P((BITMAP256, BITMAP256)); extern bool bitzerop __P((BITMAP256)); extern int check_bodytype __P((char *)); extern void buildfname __P((char *, char *, char *, int)); extern bool chkclientmodifiers __P((int)); extern bool chkdaemonmodifiers __P((int)); extern int checkcompat __P((ADDRESS *, ENVELOPE *)); #ifdef XDEBUG extern void checkfd012 __P((char *)); extern void checkfdopen __P((int, char *)); #endif /* XDEBUG */ extern void checkfds __P((char *)); extern bool chownsafe __P((int, bool)); extern void cleanstrcpy __P((char *, char *, int)); #if SM_CONF_SHM extern void cleanup_shm __P((bool)); #endif /* SM_CONF_SHM */ extern void close_sendmail_pid __P((void)); extern void clrdaemon __P((void)); extern void collect __P((SM_FILE_T *, bool, HDR **, ENVELOPE *, bool)); extern bool connection_rate_check __P((SOCKADDR *, ENVELOPE *)); extern time_t convtime __P((char *, int)); extern char **copyplist __P((char **, bool, SM_RPOOL_T *)); extern void copy_class __P((int, int)); extern int count_open_connections __P((SOCKADDR *)); extern time_t curtime __P((void)); extern char *defcharset __P((ENVELOPE *)); extern char *denlstring __P((char *, bool, bool)); extern void dferror __P((SM_FILE_T *volatile, char *, ENVELOPE *)); extern void disconnect __P((int, ENVELOPE *)); extern void disk_status __P((SM_FILE_T *, char *)); extern bool dns_getcanonname __P((char *, int, bool, int *, int *)); extern pid_t dofork __P((void)); extern int drop_privileges __P((bool)); extern int dsntoexitstat __P((char *)); extern void dumpfd __P((int, bool, bool)); #if SM_HEAP_CHECK extern void dumpstab __P((void)); #endif /* SM_HEAP_CHECK */ extern void dumpstate __P((char *)); extern bool enoughdiskspace __P((long, ENVELOPE *)); extern char *exitstat __P((char *)); extern void fatal_error __P((SM_EXC_T *)); extern char *fgetfolded __P((char *, int *, SM_FILE_T *)); extern void fill_fd __P((int, char *)); extern char *find_character __P((char *, int)); extern int finduser __P((char *, bool *, SM_MBDB_T *)); extern void finis __P((bool, bool, volatile int)); extern void fixcrlf __P((char *, bool)); extern long freediskspace __P((const char *, long *)); #if NETINET6 && NEEDSGETIPNODE extern void freehostent __P((struct hostent *)); #endif /* NETINET6 && NEEDSGETIPNODE */ extern char *get_column __P((char *, int, int, char *, int)); extern char *getauthinfo __P((int, bool *)); extern int getdtsize __P((void)); extern int getla __P((void)); extern char *getmodifiers __P((char *, BITMAP256)); extern BITMAP256 *getrequests __P((ENVELOPE *)); extern char *getvendor __P((int)); extern void help __P((char *, ENVELOPE *)); extern void init_md __P((int, char **)); extern void initdaemon __P((void)); extern void inithostmaps __P((void)); extern void initmacros __P((ENVELOPE *)); extern void initsetproctitle __P((int, char **, char **)); extern void init_vendor_macros __P((ENVELOPE *)); extern SIGFUNC_DECL intsig __P((int)); +extern bool isatom __P((const char *)); extern bool isloopback __P((SOCKADDR sa)); extern void load_if_names __P((void)); extern bool lockfile __P((int, char *, char *, int)); extern void log_sendmail_pid __P((ENVELOPE *)); extern void logundelrcpts __P((ENVELOPE *, char *, int, bool)); extern char lower __P((int)); extern void makelower __P((char *)); extern int makeconnection_ds __P((char *, MCI *)); extern int makeconnection __P((char *, volatile unsigned int, MCI *, ENVELOPE *, time_t)); extern void makeworkgroups __P((void)); extern void markfailure __P((ENVELOPE *, ADDRESS *, MCI *, int, bool)); extern void mark_work_group_restart __P((int, int)); extern MCI *mci_new __P((SM_RPOOL_T *)); extern char *munchstring __P((char *, char **, int)); extern struct hostent *myhostname __P((char *, int)); extern char *newstr __P((const char *)); #if NISPLUS extern char *nisplus_default_domain __P((void)); /* extern for Sun */ #endif /* NISPLUS */ extern bool path_is_dir __P((char *, bool)); extern int pickqdir __P((QUEUEGRP *qg, long fsize, ENVELOPE *e)); extern char *pintvl __P((time_t, bool)); extern void printav __P((SM_FILE_T *, char **)); extern void printmailer __P((SM_FILE_T *, MAILER *)); extern void printnqe __P((SM_FILE_T *, char *)); extern void printopenfds __P((bool)); extern void printqueue __P((void)); extern void printrules __P((void)); extern pid_t prog_open __P((char **, int *, ENVELOPE *)); extern bool putline __P((char *, MCI *)); extern bool putxline __P((char *, size_t, MCI *, int)); extern void queueup_macros __P((int, SM_FILE_T *, ENVELOPE *)); extern void readcf __P((char *, bool, ENVELOPE *)); extern SIGFUNC_DECL reapchild __P((int)); extern int releasesignal __P((int)); extern void resetlimits __P((void)); extern void restart_daemon __P((void)); extern void restart_marked_work_groups __P((void)); extern bool rfc822_string __P((char *)); extern void rmexpstab __P((void)); extern bool savemail __P((ENVELOPE *, bool)); extern void seed_random __P((void)); extern void sendtoargv __P((char **, ENVELOPE *)); extern void setclientoptions __P((char *)); extern bool setdaemonoptions __P((char *)); extern void setdefaults __P((ENVELOPE *)); extern void setdefuser __P((void)); extern bool setvendor __P((char *)); extern void set_op_mode __P((int)); extern void setoption __P((int, char *, bool, bool, ENVELOPE *)); extern sigfunc_t setsignal __P((int, sigfunc_t)); extern void sm_setuserenv __P((const char *, const char *)); extern void settime __P((ENVELOPE *)); #if STARTTLS extern void set_tls_rd_tmo __P((int)); #else /* STARTTLS */ #define set_tls_rd_tmo(rd_tmo) #endif /* STARTTLS */ extern char *sfgets __P((char *, int, SM_FILE_T *, time_t, char *)); extern char *shortenstring __P((const char *, size_t)); extern char *shorten_hostname __P((char [])); extern bool shorten_rfc822_string __P((char *, size_t)); extern void shutdown_daemon __P((void)); extern void sm_closefrom __P((int lowest, int highest)); extern void sm_close_on_exec __P((int lowest, int highest)); extern struct hostent *sm_gethostbyname __P((char *, int)); extern struct hostent *sm_gethostbyaddr __P((char *, int, int)); extern void sm_getla __P((void)); extern struct passwd *sm_getpwnam __P((char *)); extern struct passwd *sm_getpwuid __P((UID_T)); extern void sm_setproctitle __P((bool, ENVELOPE *, const char *, ...)); extern pid_t sm_wait __P((int *)); extern bool split_by_recipient __P((ENVELOPE *e)); extern void stop_sendmail __P((void)); extern void stripbackslash __P((char *)); extern bool strreplnonprt __P((char *, int)); extern bool strcontainedin __P((bool, char *, char *)); extern int switch_map_find __P((char *, char *[], short [])); #if STARTTLS extern void tls_set_verify __P((SSL_CTX *, SSL *, bool)); #endif /* STARTTLS */ extern bool transienterror __P((int)); extern void truncate_at_delim __P((char *, size_t, int)); extern void tTflag __P((char *)); extern void tTsetup __P((unsigned char *, unsigned int, char *)); extern SIGFUNC_DECL tick __P((int)); extern char *ttypath __P((void)); extern void unlockqueue __P((ENVELOPE *)); #if !HASUNSETENV extern void unsetenv __P((char *)); #endif /* !HASUNSETENV */ /* update file system information: +/- some blocks */ #if SM_CONF_SHM extern void upd_qs __P((ENVELOPE *, int, int, char *)); # define updfs(e, count, space, where) upd_qs(e, count, space, where) #else /* SM_CONF_SHM */ # define updfs(e, count, space, where) # define upd_qs(e, count, space, where) #endif /* SM_CONF_SHM */ extern char *username __P((void)); extern bool usershellok __P((char *, char *)); extern void vendor_post_defaults __P((ENVELOPE *)); extern void vendor_pre_defaults __P((ENVELOPE *)); extern int waitfor __P((pid_t)); extern bool writable __P((char *, ADDRESS *, long)); #if SM_HEAP_CHECK # define xalloc(size) xalloc_tagged(size, __FILE__, __LINE__) extern char *xalloc_tagged __P((int, char*, int)); #else /* SM_HEAP_CHECK */ extern char *xalloc __P((int)); #endif /* SM_HEAP_CHECK */ extern void xputs __P((SM_FILE_T *, const char *)); extern char *xtextify __P((char *, char *)); extern bool xtextok __P((char *)); extern int xunlink __P((char *)); extern char *xuntextify __P((char *)); #undef EXTERN #endif /* ! _SENDMAIL_H */ Index: head/contrib/sendmail/src/sfsasl.c =================================================================== --- head/contrib/sendmail/src/sfsasl.c (revision 249728) +++ head/contrib/sendmail/src/sfsasl.c (revision 249729) @@ -1,974 +1,995 @@ /* * Copyright (c) 1999-2006, 2008 Sendmail, Inc. and its suppliers. * All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: sfsasl.c,v 8.118 2008/07/22 15:12:48 ca Exp $") +SM_RCSID("@(#)$Id: sfsasl.c,v 8.120 2013/03/15 17:49:12 guenther Exp $") #include #include #include #include /* allow to disable error handling code just in case... */ #ifndef DEAL_WITH_ERROR_SSL # define DEAL_WITH_ERROR_SSL 1 #endif /* ! DEAL_WITH_ERROR_SSL */ #if SASL # include "sfsasl.h" /* Structure used by the "sasl" file type */ struct sasl_obj { SM_FILE_T *fp; sasl_conn_t *conn; }; struct sasl_info { SM_FILE_T *fp; sasl_conn_t *conn; }; /* ** SASL_GETINFO - returns requested information about a "sasl" file ** descriptor. ** ** Parameters: ** fp -- the file descriptor ** what -- the type of information requested ** valp -- the thang to return the information in ** ** Returns: ** -1 for unknown requests ** >=0 on success with valp filled in (if possible). */ static int sasl_getinfo __P((SM_FILE_T *, int, void *)); static int sasl_getinfo(fp, what, valp) SM_FILE_T *fp; int what; void *valp; { struct sasl_obj *so = (struct sasl_obj *) fp->f_cookie; switch (what) { case SM_IO_WHAT_FD: if (so->fp == NULL) return -1; return so->fp->f_file; /* for stdio fileno() compatability */ case SM_IO_IS_READABLE: if (so->fp == NULL) return 0; /* get info from underlying file */ return sm_io_getinfo(so->fp, what, valp); default: return -1; } } /* ** SASL_OPEN -- creates the sasl specific information for opening a ** file of the sasl type. ** ** Parameters: ** fp -- the file pointer associated with the new open ** info -- contains the sasl connection information pointer and ** the original SM_FILE_T that holds the open ** flags -- ignored ** rpool -- ignored ** ** Returns: ** 0 on success */ static int sasl_open __P((SM_FILE_T *, const void *, int, const void *)); /* ARGSUSED2 */ static int sasl_open(fp, info, flags, rpool) SM_FILE_T *fp; const void *info; int flags; const void *rpool; { struct sasl_obj *so; struct sasl_info *si = (struct sasl_info *) info; so = (struct sasl_obj *) sm_malloc(sizeof(struct sasl_obj)); if (so == NULL) { errno = ENOMEM; return -1; } so->fp = si->fp; so->conn = si->conn; /* ** The underlying 'fp' is set to SM_IO_NOW so that the entire ** encoded string is written in one chunk. Otherwise there is ** the possibility that it may appear illegal, bogus or ** mangled to the other side of the connection. ** We will read or write through 'fp' since it is the opaque ** connection for the communications. We need to treat it this ** way in case the encoded string is to be sent down a TLS ** connection rather than, say, sm_io's stdio. */ (void) sm_io_setvbuf(so->fp, SM_TIME_DEFAULT, NULL, SM_IO_NOW, 0); fp->f_cookie = so; return 0; } /* ** SASL_CLOSE -- close the sasl specific parts of the sasl file pointer ** ** Parameters: ** fp -- the file pointer to close ** ** Returns: ** 0 on success */ static int sasl_close __P((SM_FILE_T *)); static int sasl_close(fp) SM_FILE_T *fp; { struct sasl_obj *so; so = (struct sasl_obj *) fp->f_cookie; if (so == NULL) return 0; if (so->fp != NULL) { sm_io_close(so->fp, SM_TIME_DEFAULT); so->fp = NULL; } sm_free(so); so = NULL; return 0; } /* how to deallocate a buffer allocated by SASL */ extern void sm_sasl_free __P((void *)); # define SASL_DEALLOC(b) sm_sasl_free(b) /* ** SASL_READ -- read encrypted information and decrypt it for the caller ** ** Parameters: ** fp -- the file pointer ** buf -- the location to place the decrypted information ** size -- the number of bytes to read after decryption ** ** Results: ** -1 on error ** otherwise the number of bytes read */ static ssize_t sasl_read __P((SM_FILE_T *, char *, size_t)); static ssize_t sasl_read(fp, buf, size) SM_FILE_T *fp; char *buf; size_t size; { int result; ssize_t len; # if SASL >= 20000 static const char *outbuf = NULL; # else /* SASL >= 20000 */ static char *outbuf = NULL; # endif /* SASL >= 20000 */ static unsigned int outlen = 0; static unsigned int offset = 0; struct sasl_obj *so = (struct sasl_obj *) fp->f_cookie; /* ** sasl_decode() may require more data than a single read() returns. ** Hence we have to put a loop around the decoding. ** This also requires that we may have to split up the returned ** data since it might be larger than the allowed size. ** Therefore we use a static pointer and return portions of it ** if necessary. ** XXX Note: This function is not thread-safe nor can it be used ** on more than one file. A correct implementation would store ** this data in fp->f_cookie. */ # if SASL >= 20000 while (outlen == 0) # else /* SASL >= 20000 */ while (outbuf == NULL && outlen == 0) # endif /* SASL >= 20000 */ { len = sm_io_read(so->fp, SM_TIME_DEFAULT, buf, size); if (len <= 0) return len; result = sasl_decode(so->conn, buf, (unsigned int) len, &outbuf, &outlen); if (result != SASL_OK) { if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "AUTH: sasl_decode error=%d", result); outbuf = NULL; offset = 0; outlen = 0; return -1; } } if (outbuf == NULL) { /* be paranoid: outbuf == NULL but outlen != 0 */ syserr("@sasl_read failure: outbuf == NULL but outlen != 0"); /* NOTREACHED */ } if (outlen - offset > size) { /* return another part of the buffer */ (void) memcpy(buf, outbuf + offset, size); offset += size; len = size; } else { /* return the rest of the buffer */ len = outlen - offset; (void) memcpy(buf, outbuf + offset, (size_t) len); # if SASL < 20000 SASL_DEALLOC(outbuf); # endif /* SASL < 20000 */ outbuf = NULL; offset = 0; outlen = 0; } return len; } /* ** SASL_WRITE -- write information out after encrypting it ** ** Parameters: ** fp -- the file pointer ** buf -- holds the data to be encrypted and written ** size -- the number of bytes to have encrypted and written ** ** Returns: ** -1 on error ** otherwise number of bytes written */ static ssize_t sasl_write __P((SM_FILE_T *, const char *, size_t)); static ssize_t sasl_write(fp, buf, size) SM_FILE_T *fp; const char *buf; size_t size; { int result; # if SASL >= 20000 const char *outbuf; # else /* SASL >= 20000 */ char *outbuf; # endif /* SASL >= 20000 */ unsigned int outlen, *maxencode; size_t ret = 0, total = 0; struct sasl_obj *so = (struct sasl_obj *) fp->f_cookie; /* ** Fetch the maximum input buffer size for sasl_encode(). ** This can be less than the size set in attemptauth() ** due to a negotiation with the other side, e.g., ** Cyrus IMAP lmtp program sets maxbuf=4096, ** digestmd5 substracts 25 and hence we'll get 4071 ** instead of 8192 (MAXOUTLEN). ** Hack (for now): simply reduce the size, callers are (must be) ** able to deal with that and invoke sasl_write() again with ** the rest of the data. ** Note: it would be better to store this value in the context ** after the negotiation. */ result = sasl_getprop(so->conn, SASL_MAXOUTBUF, (const void **) &maxencode); if (result == SASL_OK && size > *maxencode && *maxencode > 0) size = *maxencode; result = sasl_encode(so->conn, buf, (unsigned int) size, &outbuf, &outlen); if (result != SASL_OK) { if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "AUTH: sasl_encode error=%d", result); return -1; } if (outbuf != NULL) { while (outlen > 0) { errno = 0; /* XXX result == 0? */ ret = sm_io_write(so->fp, SM_TIME_DEFAULT, &outbuf[total], outlen); if (ret <= 0) return ret; outlen -= ret; total += ret; } # if SASL < 20000 SASL_DEALLOC(outbuf); # endif /* SASL < 20000 */ } return size; } /* ** SFDCSASL -- create sasl file type and open in and out file pointers ** for sendmail to read from and write to. ** ** Parameters: ** fin -- the sm_io file encrypted data to be read from ** fout -- the sm_io file encrypted data to be written to ** conn -- the sasl connection pointer ** tmo -- timeout ** ** Returns: ** -1 on error ** 0 on success ** ** Side effects: ** The arguments "fin" and "fout" are replaced with the new ** SM_FILE_T pointers. */ int sfdcsasl(fin, fout, conn, tmo) SM_FILE_T **fin; SM_FILE_T **fout; sasl_conn_t *conn; int tmo; { SM_FILE_T *newin, *newout; SM_FILE_T SM_IO_SET_TYPE(sasl_vector, "sasl", sasl_open, sasl_close, sasl_read, sasl_write, NULL, sasl_getinfo, NULL, SM_TIME_DEFAULT); struct sasl_info info; if (conn == NULL) { /* no need to do anything */ return 0; } SM_IO_INIT_TYPE(sasl_vector, "sasl", sasl_open, sasl_close, sasl_read, sasl_write, NULL, sasl_getinfo, NULL, SM_TIME_DEFAULT); info.fp = *fin; info.conn = conn; newin = sm_io_open(&sasl_vector, SM_TIME_DEFAULT, &info, SM_IO_RDONLY_B, NULL); if (newin == NULL) return -1; info.fp = *fout; info.conn = conn; newout = sm_io_open(&sasl_vector, SM_TIME_DEFAULT, &info, SM_IO_WRONLY_B, NULL); if (newout == NULL) { (void) sm_io_close(newin, SM_TIME_DEFAULT); return -1; } sm_io_automode(newin, newout); sm_io_setinfo(*fin, SM_IO_WHAT_TIMEOUT, &tmo); sm_io_setinfo(*fout, SM_IO_WHAT_TIMEOUT, &tmo); *fin = newin; *fout = newout; return 0; } #endif /* SASL */ #if STARTTLS # include "sfsasl.h" # include /* Structure used by the "tls" file type */ struct tls_obj { SM_FILE_T *fp; SSL *con; }; struct tls_info { SM_FILE_T *fp; SSL *con; }; /* ** TLS_GETINFO - returns requested information about a "tls" file ** descriptor. ** ** Parameters: ** fp -- the file descriptor ** what -- the type of information requested ** valp -- the thang to return the information in (unused) ** ** Returns: ** -1 for unknown requests ** >=0 on success with valp filled in (if possible). */ static int tls_getinfo __P((SM_FILE_T *, int, void *)); /* ARGSUSED2 */ static int tls_getinfo(fp, what, valp) SM_FILE_T *fp; int what; void *valp; { struct tls_obj *so = (struct tls_obj *) fp->f_cookie; switch (what) { case SM_IO_WHAT_FD: if (so->fp == NULL) return -1; return so->fp->f_file; /* for stdio fileno() compatability */ case SM_IO_IS_READABLE: return SSL_pending(so->con) > 0; default: return -1; } } /* ** TLS_OPEN -- creates the tls specific information for opening a ** file of the tls type. ** ** Parameters: ** fp -- the file pointer associated with the new open ** info -- the sm_io file pointer holding the open and the ** TLS encryption connection to be read from or written to ** flags -- ignored ** rpool -- ignored ** ** Returns: ** 0 on success */ static int tls_open __P((SM_FILE_T *, const void *, int, const void *)); /* ARGSUSED2 */ static int tls_open(fp, info, flags, rpool) SM_FILE_T *fp; const void *info; int flags; const void *rpool; { struct tls_obj *so; struct tls_info *ti = (struct tls_info *) info; so = (struct tls_obj *) sm_malloc(sizeof(struct tls_obj)); if (so == NULL) { errno = ENOMEM; return -1; } so->fp = ti->fp; so->con = ti->con; /* ** We try to get the "raw" file descriptor that TLS uses to ** do the actual read/write with. This is to allow us control ** over the file descriptor being a blocking or non-blocking type. ** Under the covers TLS handles the change and this allows us ** to do timeouts with sm_io. */ fp->f_file = sm_io_getinfo(so->fp, SM_IO_WHAT_FD, NULL); (void) sm_io_setvbuf(so->fp, SM_TIME_DEFAULT, NULL, SM_IO_NOW, 0); fp->f_cookie = so; return 0; } /* ** TLS_CLOSE -- close the tls specific parts of the tls file pointer ** ** Parameters: ** fp -- the file pointer to close ** ** Returns: ** 0 on success */ static int tls_close __P((SM_FILE_T *)); static int tls_close(fp) SM_FILE_T *fp; { struct tls_obj *so; so = (struct tls_obj *) fp->f_cookie; if (so == NULL) return 0; if (so->fp != NULL) { sm_io_close(so->fp, SM_TIME_DEFAULT); so->fp = NULL; } sm_free(so); so = NULL; return 0; } /* maximum number of retries for TLS related I/O due to handshakes */ # define MAX_TLS_IOS 4 /* ** TLS_RETRY -- check whether a failed SSL operation can be retried ** ** Parameters: ** ssl -- TLS structure ** rfd -- read fd ** wfd -- write fd ** tlsstart -- start time of TLS operation ** timeout -- timeout for TLS operation ** err -- SSL error ** where -- description of operation ** ** Results: ** >0 on success ** 0 on timeout ** <0 on error */ int tls_retry(ssl, rfd, wfd, tlsstart, timeout, err, where) SSL *ssl; int rfd; int wfd; time_t tlsstart; int timeout; int err; const char *where; { int ret; time_t left; time_t now = curtime(); struct timeval tv; ret = -1; /* ** For SSL_ERROR_WANT_{READ,WRITE}: ** There is not a complete SSL record available yet ** or there is only a partial SSL record removed from ** the network (socket) buffer into the SSL buffer. ** The SSL_connect will only succeed when a full ** SSL record is available (assuming a "real" error ** doesn't happen). To handle when a "real" error ** does happen the select is set for exceptions too. ** The connection may be re-negotiated during this time ** so both read and write "want errors" need to be handled. ** A select() exception loops back so that a proper SSL ** error message can be gotten. */ left = timeout - (now - tlsstart); if (left <= 0) return 0; /* timeout */ tv.tv_sec = left; tv.tv_usec = 0; if (LogLevel > 14) { sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, info: fds=%d/%d, err=%d", where, rfd, wfd, err); } if (FD_SETSIZE > 0 && ((err == SSL_ERROR_WANT_READ && rfd >= FD_SETSIZE) || (err == SSL_ERROR_WANT_WRITE && wfd >= FD_SETSIZE))) { if (LogLevel > 5) { sm_syslog(LOG_ERR, NOQID, "STARTTLS=%s, error: fd %d/%d too large", where, rfd, wfd); if (LogLevel > 8) - tlslogerr(where); + tlslogerr(LOG_WARNING, where); } errno = EINVAL; } else if (err == SSL_ERROR_WANT_READ) { fd_set ssl_maskr, ssl_maskx; + int save_errno = errno; FD_ZERO(&ssl_maskr); FD_SET(rfd, &ssl_maskr); FD_ZERO(&ssl_maskx); FD_SET(rfd, &ssl_maskx); do { ret = select(rfd + 1, &ssl_maskr, NULL, &ssl_maskx, &tv); } while (ret < 0 && errno == EINTR); if (ret < 0 && errno > 0) ret = -errno; + errno = save_errno; } else if (err == SSL_ERROR_WANT_WRITE) { fd_set ssl_maskw, ssl_maskx; + int save_errno = errno; FD_ZERO(&ssl_maskw); FD_SET(wfd, &ssl_maskw); FD_ZERO(&ssl_maskx); FD_SET(rfd, &ssl_maskx); do { ret = select(wfd + 1, NULL, &ssl_maskw, &ssl_maskx, &tv); } while (ret < 0 && errno == EINTR); if (ret < 0 && errno > 0) ret = -errno; + errno = save_errno; } return ret; } /* errno to force refill() etc to stop (see IS_IO_ERROR()) */ #ifdef ETIMEDOUT # define SM_ERR_TIMEOUT ETIMEDOUT #else /* ETIMEDOUT */ # define SM_ERR_TIMEOUT EIO #endif /* ETIMEDOUT */ /* ** SET_TLS_RD_TMO -- read secured information for the caller ** ** Parameters: ** rd_tmo -- read timeout ** ** Results: ** none ** This is a hack: there is no way to pass it in */ static int tls_rd_tmo = -1; void set_tls_rd_tmo(rd_tmo) int rd_tmo; { tls_rd_tmo = rd_tmo; } /* ** TLS_READ -- read secured information for the caller ** ** Parameters: ** fp -- the file pointer ** buf -- the location to place the data ** size -- the number of bytes to read from connection ** ** Results: ** -1 on error ** otherwise the number of bytes read */ static ssize_t tls_read __P((SM_FILE_T *, char *, size_t)); static ssize_t tls_read(fp, buf, size) SM_FILE_T *fp; char *buf; size_t size; { int r, rfd, wfd, try, ssl_err; struct tls_obj *so = (struct tls_obj *) fp->f_cookie; time_t tlsstart; char *err; try = 99; err = NULL; tlsstart = curtime(); retry: r = SSL_read(so->con, (char *) buf, size); if (r > 0) return r; err = NULL; switch (ssl_err = SSL_get_error(so->con, r)) { case SSL_ERROR_NONE: case SSL_ERROR_ZERO_RETURN: break; case SSL_ERROR_WANT_WRITE: err = "read W BLOCK"; /* FALLTHROUGH */ case SSL_ERROR_WANT_READ: if (err == NULL) err = "read R BLOCK"; rfd = SSL_get_rfd(so->con); wfd = SSL_get_wfd(so->con); try = tls_retry(so->con, rfd, wfd, tlsstart, (tls_rd_tmo < 0) ? TimeOuts.to_datablock : tls_rd_tmo, ssl_err, "read"); if (try > 0) goto retry; errno = SM_ERR_TIMEOUT; break; case SSL_ERROR_WANT_X509_LOOKUP: err = "write X BLOCK"; break; case SSL_ERROR_SYSCALL: if (r == 0 && errno == 0) /* out of protocol EOF found */ break; err = "syscall error"; /* get_last_socket_error()); */ break; case SSL_ERROR_SSL: #if DEAL_WITH_ERROR_SSL if (r == 0 && errno == 0) /* out of protocol EOF found */ break; #endif /* DEAL_WITH_ERROR_SSL */ err = "generic SSL error"; + if (LogLevel > 9) - tlslogerr("read"); + { + int pri; + if (errno == EAGAIN && try > 0) + pri = LOG_DEBUG; + else + pri = LOG_WARNING; + tlslogerr(pri, "read"); + } + #if DEAL_WITH_ERROR_SSL /* avoid repeated calls? */ if (r == 0) r = -1; #endif /* DEAL_WITH_ERROR_SSL */ break; } if (err != NULL) { int save_errno; save_errno = (errno == 0) ? EIO : errno; if (try == 0 && save_errno == SM_ERR_TIMEOUT) { if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: read error=timeout"); } else if (LogLevel > 8) - sm_syslog(LOG_WARNING, NOQID, + { + int pri; + + if (save_errno == EAGAIN && try > 0) + pri = LOG_DEBUG; + else + pri = LOG_WARNING; + sm_syslog(pri, NOQID, "STARTTLS: read error=%s (%d), errno=%d, get_error=%s, retry=%d, ssl_err=%d", err, r, errno, ERR_error_string(ERR_get_error(), NULL), try, ssl_err); + } else if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: read error=%s (%d), retry=%d, ssl_err=%d", err, r, errno, try, ssl_err); errno = save_errno; } return r; } /* ** TLS_WRITE -- write information out through secure connection ** ** Parameters: ** fp -- the file pointer ** buf -- holds the data to be securely written ** size -- the number of bytes to write ** ** Returns: ** -1 on error ** otherwise number of bytes written */ static ssize_t tls_write __P((SM_FILE_T *, const char *, size_t)); static ssize_t tls_write(fp, buf, size) SM_FILE_T *fp; const char *buf; size_t size; { int r, rfd, wfd, try, ssl_err; struct tls_obj *so = (struct tls_obj *) fp->f_cookie; time_t tlsstart; char *err; try = 99; err = NULL; tlsstart = curtime(); retry: r = SSL_write(so->con, (char *) buf, size); if (r > 0) return r; err = NULL; switch (ssl_err = SSL_get_error(so->con, r)) { case SSL_ERROR_NONE: case SSL_ERROR_ZERO_RETURN: break; case SSL_ERROR_WANT_WRITE: err = "read W BLOCK"; /* FALLTHROUGH */ case SSL_ERROR_WANT_READ: if (err == NULL) err = "read R BLOCK"; rfd = SSL_get_rfd(so->con); wfd = SSL_get_wfd(so->con); try = tls_retry(so->con, rfd, wfd, tlsstart, DATA_PROGRESS_TIMEOUT, ssl_err, "write"); if (try > 0) goto retry; errno = SM_ERR_TIMEOUT; break; case SSL_ERROR_WANT_X509_LOOKUP: err = "write X BLOCK"; break; case SSL_ERROR_SYSCALL: if (r == 0 && errno == 0) /* out of protocol EOF found */ break; err = "syscall error"; /* get_last_socket_error()); */ break; case SSL_ERROR_SSL: err = "generic SSL error"; /* ERR_GET_REASON(ERR_peek_error())); */ if (LogLevel > 9) - tlslogerr("write"); + tlslogerr(LOG_WARNING, "write"); #if DEAL_WITH_ERROR_SSL /* avoid repeated calls? */ if (r == 0) r = -1; #endif /* DEAL_WITH_ERROR_SSL */ break; } if (err != NULL) { int save_errno; save_errno = (errno == 0) ? EIO : errno; if (try == 0 && save_errno == SM_ERR_TIMEOUT) { if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: write error=timeout"); } else if (LogLevel > 8) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: write error=%s (%d), errno=%d, get_error=%s, retry=%d, ssl_err=%d", err, r, errno, ERR_error_string(ERR_get_error(), NULL), try, ssl_err); else if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: write error=%s (%d), errno=%d, retry=%d, ssl_err=%d", err, r, errno, try, ssl_err); errno = save_errno; } return r; } /* ** SFDCTLS -- create tls file type and open in and out file pointers ** for sendmail to read from and write to. ** ** Parameters: ** fin -- data input source being replaced ** fout -- data output source being replaced ** con -- the tls connection pointer ** ** Returns: ** -1 on error ** 0 on success ** ** Side effects: ** The arguments "fin" and "fout" are replaced with the new ** SM_FILE_T pointers. ** The original "fin" and "fout" are preserved in the tls file ** type but are not actually used because of the design of TLS. */ int sfdctls(fin, fout, con) SM_FILE_T **fin; SM_FILE_T **fout; SSL *con; { SM_FILE_T *tlsin, *tlsout; SM_FILE_T SM_IO_SET_TYPE(tls_vector, "tls", tls_open, tls_close, tls_read, tls_write, NULL, tls_getinfo, NULL, SM_TIME_FOREVER); struct tls_info info; SM_ASSERT(con != NULL); SM_IO_INIT_TYPE(tls_vector, "tls", tls_open, tls_close, tls_read, tls_write, NULL, tls_getinfo, NULL, SM_TIME_FOREVER); info.fp = *fin; info.con = con; tlsin = sm_io_open(&tls_vector, SM_TIME_DEFAULT, &info, SM_IO_RDONLY_B, NULL); if (tlsin == NULL) return -1; info.fp = *fout; tlsout = sm_io_open(&tls_vector, SM_TIME_DEFAULT, &info, SM_IO_WRONLY_B, NULL); if (tlsout == NULL) { (void) sm_io_close(tlsin, SM_TIME_DEFAULT); return -1; } sm_io_automode(tlsin, tlsout); *fin = tlsin; *fout = tlsout; return 0; } #endif /* STARTTLS */ Index: head/contrib/sendmail/src/srvrsmtp.c =================================================================== --- head/contrib/sendmail/src/srvrsmtp.c (revision 249728) +++ head/contrib/sendmail/src/srvrsmtp.c (revision 249729) @@ -1,5071 +1,5082 @@ /* - * Copyright (c) 1998-2010, 2012 Sendmail, Inc. and its suppliers. + * Copyright (c) 1998-2010, 2012, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include #if MILTER # include # include #endif /* MILTER */ -SM_RCSID("@(#)$Id: srvrsmtp.c,v 8.1011 2012/12/19 02:49:21 ca Exp $") +SM_RCSID("@(#)$Id: srvrsmtp.c,v 8.1015 2013/03/12 15:24:54 ca Exp $") #include #include #if SASL || STARTTLS # include "sfsasl.h" #endif /* SASL || STARTTLS */ #if SASL # define ENC64LEN(l) (((l) + 2) * 4 / 3 + 1) static int saslmechs __P((sasl_conn_t *, char **)); #endif /* SASL */ #if STARTTLS # include # include static SSL_CTX *srv_ctx = NULL; /* TLS server context */ static SSL *srv_ssl = NULL; /* per connection context */ static bool tls_ok_srv = false; # define TLS_VERIFY_CLIENT() tls_set_verify(srv_ctx, srv_ssl, \ bitset(SRV_VRFY_CLT, features)) #endif /* STARTTLS */ #if _FFR_DM_ONE static bool NotFirstDelivery = false; #endif /* _FFR_DM_ONE */ /* server features */ #define SRV_NONE 0x0000 /* none... */ #define SRV_OFFER_TLS 0x0001 /* offer STARTTLS */ #define SRV_VRFY_CLT 0x0002 /* request a cert */ #define SRV_OFFER_AUTH 0x0004 /* offer AUTH */ #define SRV_OFFER_ETRN 0x0008 /* offer ETRN */ #define SRV_OFFER_VRFY 0x0010 /* offer VRFY (not yet used) */ #define SRV_OFFER_EXPN 0x0020 /* offer EXPN */ #define SRV_OFFER_VERB 0x0040 /* offer VERB */ #define SRV_OFFER_DSN 0x0080 /* offer DSN */ #if PIPELINING # define SRV_OFFER_PIPE 0x0100 /* offer PIPELINING */ # if _FFR_NO_PIPE # define SRV_NO_PIPE 0x0200 /* disable PIPELINING, sleep if used */ # endif /* _FFR_NO_PIPE */ #endif /* PIPELINING */ #define SRV_REQ_AUTH 0x0400 /* require AUTH */ #define SRV_REQ_SEC 0x0800 /* require security - equiv to AuthOptions=p */ #define SRV_TMP_FAIL 0x1000 /* ruleset caused a temporary failure */ static unsigned int srvfeatures __P((ENVELOPE *, char *, unsigned int)); #define STOP_ATTACK ((time_t) -1) static time_t checksmtpattack __P((volatile unsigned int *, unsigned int, bool, char *, ENVELOPE *)); static void printvrfyaddr __P((ADDRESS *, bool, bool)); static char *skipword __P((char *volatile, char *)); static void setup_smtpd_io __P((void)); #if SASL # if SASL >= 20000 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname, char *_remoteip, char *_localip, char *_auth_id, sasl_ssf_t *_ext_ssf)); # define RESET_SASLCONN \ do \ { \ result = reset_saslconn(&conn, AuthRealm, remoteip, \ localip, auth_id, &ext_ssf); \ if (result != SASL_OK) \ sasl_ok = false; \ } while (0) # else /* SASL >= 20000 */ static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname, struct sockaddr_in *_saddr_r, struct sockaddr_in *_saddr_l, sasl_external_properties_t *_ext_ssf)); # define RESET_SASLCONN \ do \ { \ result = reset_saslconn(&conn, AuthRealm, &saddr_r, \ &saddr_l, &ext_ssf); \ if (result != SASL_OK) \ sasl_ok = false; \ } while (0) # endif /* SASL >= 20000 */ #endif /* SASL */ extern ENVELOPE BlankEnvelope; #define NBADRCPTS \ do \ { \ char buf[16]; \ (void) sm_snprintf(buf, sizeof(buf), "%d", \ BadRcptThrottle > 0 && n_badrcpts > BadRcptThrottle \ ? n_badrcpts - 1 : n_badrcpts); \ macdefine(&e->e_macro, A_TEMP, macid("{nbadrcpts}"), buf); \ } while (0) #define SKIP_SPACE(s) while (isascii(*s) && isspace(*s)) \ (s)++ /* ** PARSE_ESMTP_ARGS -- parse EMSTP arguments (for MAIL, RCPT) ** ** Parameters: ** e -- the envelope ** addr_st -- address (RCPT only) ** p -- read buffer ** delimptr -- current position in read buffer ** which -- MAIL/RCPT ** args -- arguments (output) ** esmtp_args -- function to process a single ESMTP argument ** ** Returns: ** none */ void parse_esmtp_args(e, addr_st, p, delimptr, which, args, esmtp_args) ENVELOPE *e; ADDRESS *addr_st; char *p; char *delimptr; char *which; char *args[]; esmtp_args_F esmtp_args; { int argno; argno = 0; if (args != NULL) args[argno++] = p; p = delimptr; while (p != NULL && *p != '\0') { char *kp; char *vp = NULL; char *equal = NULL; /* locate the beginning of the keyword */ SKIP_SPACE(p); if (*p == '\0') break; kp = p; /* skip to the value portion */ while ((isascii(*p) && isalnum(*p)) || *p == '-') p++; if (*p == '=') { equal = p; *p++ = '\0'; vp = p; /* skip to the end of the value */ while (*p != '\0' && *p != ' ' && !(isascii(*p) && iscntrl(*p)) && *p != '=') p++; } if (*p != '\0') *p++ = '\0'; if (tTd(19, 1)) sm_dprintf("%s: got arg %s=\"%s\"\n", which, kp, vp == NULL ? "" : vp); esmtp_args(addr_st, kp, vp, e); if (equal != NULL) *equal = '='; if (args != NULL) args[argno] = kp; argno++; if (argno >= MAXSMTPARGS - 1) usrerr("501 5.5.4 Too many parameters"); if (Errors > 0) break; } if (args != NULL) args[argno] = NULL; } /* ** SMTP -- run the SMTP protocol. ** ** Parameters: ** nullserver -- if non-NULL, rejection message for ** (almost) all SMTP commands. ** d_flags -- daemon flags ** e -- the envelope. ** ** Returns: ** never. ** ** Side Effects: ** Reads commands from the input channel and processes them. */ /* ** Notice: The smtp server doesn't have a session context like the client ** side has (mci). Therefore some data (session oriented) is allocated ** or assigned to the "wrong" structure (esp. STARTTLS, AUTH). ** This should be fixed in a successor version. */ struct cmd { char *cmd_name; /* command name */ int cmd_code; /* internal code, see below */ }; /* values for cmd_code */ #define CMDERROR 0 /* bad command */ #define CMDMAIL 1 /* mail -- designate sender */ #define CMDRCPT 2 /* rcpt -- designate recipient */ #define CMDDATA 3 /* data -- send message text */ #define CMDRSET 4 /* rset -- reset state */ #define CMDVRFY 5 /* vrfy -- verify address */ #define CMDEXPN 6 /* expn -- expand address */ #define CMDNOOP 7 /* noop -- do nothing */ #define CMDQUIT 8 /* quit -- close connection and die */ #define CMDHELO 9 /* helo -- be polite */ #define CMDHELP 10 /* help -- give usage info */ #define CMDEHLO 11 /* ehlo -- extended helo (RFC 1425) */ #define CMDETRN 12 /* etrn -- flush queue */ #if SASL # define CMDAUTH 13 /* auth -- SASL authenticate */ #endif /* SASL */ #if STARTTLS # define CMDSTLS 14 /* STARTTLS -- start TLS session */ #endif /* STARTTLS */ /* non-standard commands */ #define CMDVERB 17 /* verb -- go into verbose mode */ /* unimplemented commands from RFC 821 */ #define CMDUNIMPL 19 /* unimplemented rfc821 commands */ /* use this to catch and log "door handle" attempts on your system */ #define CMDLOGBOGUS 23 /* bogus command that should be logged */ /* debugging-only commands, only enabled if SMTPDEBUG is defined */ #define CMDDBGQSHOW 24 /* showq -- show send queue */ #define CMDDBGDEBUG 25 /* debug -- set debug mode */ /* ** Note: If you change this list, remember to update 'helpfile' */ static struct cmd CmdTab[] = { { "mail", CMDMAIL }, { "rcpt", CMDRCPT }, { "data", CMDDATA }, { "rset", CMDRSET }, { "vrfy", CMDVRFY }, { "expn", CMDEXPN }, { "help", CMDHELP }, { "noop", CMDNOOP }, { "quit", CMDQUIT }, { "helo", CMDHELO }, { "ehlo", CMDEHLO }, { "etrn", CMDETRN }, { "verb", CMDVERB }, { "send", CMDUNIMPL }, { "saml", CMDUNIMPL }, { "soml", CMDUNIMPL }, { "turn", CMDUNIMPL }, #if SASL { "auth", CMDAUTH, }, #endif /* SASL */ #if STARTTLS { "starttls", CMDSTLS, }, #endif /* STARTTLS */ /* remaining commands are here only to trap and log attempts to use them */ { "showq", CMDDBGQSHOW }, { "debug", CMDDBGDEBUG }, { "wiz", CMDLOGBOGUS }, { NULL, CMDERROR } }; static char *CurSmtpClient; /* who's at the other end of channel */ #ifndef MAXBADCOMMANDS # define MAXBADCOMMANDS 25 /* maximum number of bad commands */ #endif /* ! MAXBADCOMMANDS */ #ifndef MAXHELOCOMMANDS # define MAXHELOCOMMANDS 3 /* max HELO/EHLO commands before slowdown */ #endif /* ! MAXHELOCOMMANDS */ #ifndef MAXVRFYCOMMANDS # define MAXVRFYCOMMANDS 6 /* max VRFY/EXPN commands before slowdown */ #endif /* ! MAXVRFYCOMMANDS */ #ifndef MAXETRNCOMMANDS # define MAXETRNCOMMANDS 8 /* max ETRN commands before slowdown */ #endif /* ! MAXETRNCOMMANDS */ #ifndef MAXTIMEOUT # define MAXTIMEOUT (4 * 60) /* max timeout for bad commands */ #endif /* ! MAXTIMEOUT */ /* ** Maximum shift value to compute timeout for bad commands. ** This introduces an upper limit of 2^MAXSHIFT for the timeout. */ #ifndef MAXSHIFT # define MAXSHIFT 8 #endif /* ! MAXSHIFT */ #if MAXSHIFT > 31 ERROR _MAXSHIFT > 31 is invalid #endif /* MAXSHIFT */ #if MAXBADCOMMANDS > 0 # define STOP_IF_ATTACK(r) do \ { \ if ((r) == STOP_ATTACK) \ goto stopattack; \ } while (0) #else /* MAXBADCOMMANDS > 0 */ # define STOP_IF_ATTACK(r) r #endif /* MAXBADCOMMANDS > 0 */ #if SM_HEAP_CHECK static SM_DEBUG_T DebugLeakSmtp = SM_DEBUG_INITIALIZER("leak_smtp", "@(#)$Debug: leak_smtp - trace memory leaks during SMTP processing $"); #endif /* SM_HEAP_CHECK */ typedef struct { bool sm_gotmail; /* mail command received */ unsigned int sm_nrcpts; /* number of successful RCPT commands */ bool sm_discard; #if MILTER bool sm_milterize; bool sm_milterlist; /* any filters in the list? */ milters_T sm_milters; /* e_nrcpts from envelope before recipient() call */ unsigned int sm_e_nrcpts_orig; #endif /* MILTER */ char *sm_quarmsg; /* carry quarantining across messages */ } SMTP_T; static bool smtp_data __P((SMTP_T *, ENVELOPE *)); #define MSG_TEMPFAIL "451 4.3.2 Please try again later" #if MILTER # define MILTER_ABORT(e) milter_abort((e)) # define MILTER_REPLY(str) \ { \ int savelogusrerrs = LogUsrErrs; \ \ milter_cmd_fail = true; \ switch (state) \ { \ case SMFIR_SHUTDOWN: \ if (MilterLogLevel > 3) \ { \ sm_syslog(LOG_INFO, e->e_id, \ "Milter: %s=%s, reject=421, errormode=4", \ str, addr); \ LogUsrErrs = false; \ } \ { \ bool tsave = QuickAbort; \ \ QuickAbort = false; \ usrerr("421 4.3.0 closing connection"); \ QuickAbort = tsave; \ e->e_sendqueue = NULL; \ goto doquit; \ } \ break; \ case SMFIR_REPLYCODE: \ if (MilterLogLevel > 3) \ { \ sm_syslog(LOG_INFO, e->e_id, \ "Milter: %s=%s, reject=%s", \ str, addr, response); \ LogUsrErrs = false; \ } \ if (strncmp(response, "421 ", 4) == 0 \ || strncmp(response, "421-", 4) == 0) \ { \ bool tsave = QuickAbort; \ \ QuickAbort = false; \ usrerr(response); \ QuickAbort = tsave; \ e->e_sendqueue = NULL; \ goto doquit; \ } \ else \ usrerr(response); \ break; \ \ case SMFIR_REJECT: \ if (MilterLogLevel > 3) \ { \ sm_syslog(LOG_INFO, e->e_id, \ "Milter: %s=%s, reject=550 5.7.1 Command rejected", \ str, addr); \ LogUsrErrs = false; \ } \ usrerr("550 5.7.1 Command rejected"); \ break; \ \ case SMFIR_DISCARD: \ if (MilterLogLevel > 3) \ sm_syslog(LOG_INFO, e->e_id, \ "Milter: %s=%s, discard", \ str, addr); \ e->e_flags |= EF_DISCARD; \ milter_cmd_fail = false; \ break; \ \ case SMFIR_TEMPFAIL: \ if (MilterLogLevel > 3) \ { \ sm_syslog(LOG_INFO, e->e_id, \ "Milter: %s=%s, reject=%s", \ str, addr, MSG_TEMPFAIL); \ LogUsrErrs = false; \ } \ usrerr(MSG_TEMPFAIL); \ break; \ default: \ milter_cmd_fail = false; \ break; \ } \ LogUsrErrs = savelogusrerrs; \ if (response != NULL) \ sm_free(response); /* XXX */ \ } #else /* MILTER */ # define MILTER_ABORT(e) #endif /* MILTER */ /* clear all SMTP state (for HELO/EHLO/RSET) */ #define CLEAR_STATE(cmd) \ do \ { \ /* abort milter filters */ \ MILTER_ABORT(e); \ \ if (smtp.sm_nrcpts > 0) \ { \ logundelrcpts(e, cmd, 10, false); \ smtp.sm_nrcpts = 0; \ macdefine(&e->e_macro, A_PERM, \ macid("{nrcpts}"), "0"); \ } \ \ e->e_sendqueue = NULL; \ e->e_flags |= EF_CLRQUEUE; \ \ if (tTd(92, 2)) \ sm_dprintf("CLEAR_STATE: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",\ e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel);\ if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags)) \ logsender(e, NULL); \ e->e_flags &= ~EF_LOGSENDER; \ \ /* clean up a bit */ \ smtp.sm_gotmail = false; \ SuprErrs = true; \ (void) dropenvelope(e, true, false); \ sm_rpool_free(e->e_rpool); \ e = newenvelope(e, CurEnv, sm_rpool_new_x(NULL)); \ CurEnv = e; \ e->e_features = features; \ \ /* put back discard bit */ \ if (smtp.sm_discard) \ e->e_flags |= EF_DISCARD; \ \ /* restore connection quarantining */ \ if (smtp.sm_quarmsg == NULL) \ { \ e->e_quarmsg = NULL; \ macdefine(&e->e_macro, A_PERM, \ macid("{quarantine}"), ""); \ } \ else \ { \ e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \ smtp.sm_quarmsg); \ macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \ e->e_quarmsg); \ } \ } while (0) /* sleep to flatten out connection load */ #define MIN_DELAY_LOG 15 /* wait before logging this again */ /* is it worth setting the process title for 1s? */ #define DELAY_CONN(cmd) \ if (DelayLA > 0 && (CurrentLA = getla()) >= DelayLA) \ { \ time_t dnow; \ \ sm_setproctitle(true, e, \ "%s: %s: delaying %s: load average: %d", \ qid_printname(e), CurSmtpClient, \ cmd, DelayLA); \ if (LogLevel > 8 && (dnow = curtime()) > log_delay) \ { \ sm_syslog(LOG_INFO, e->e_id, \ "delaying=%s, load average=%d >= %d", \ cmd, CurrentLA, DelayLA); \ log_delay = dnow + MIN_DELAY_LOG; \ } \ (void) sleep(1); \ sm_setproctitle(true, e, "%s %s: %.80s", \ qid_printname(e), CurSmtpClient, inp); \ } static bool SevenBitInput_Saved; /* saved version of SevenBitInput */ void smtp(nullserver, d_flags, e) char *volatile nullserver; BITMAP256 d_flags; register ENVELOPE *volatile e; { register char *volatile p; register struct cmd *volatile c = NULL; char *cmd; auto ADDRESS *vrfyqueue; ADDRESS *a; volatile bool gothello; /* helo command received */ bool vrfy; /* set if this is a vrfy command */ char *volatile protocol; /* sending protocol */ char *volatile sendinghost; /* sending hostname */ char *volatile peerhostname; /* name of SMTP peer or "localhost" */ auto char *delimptr; char *id; volatile unsigned int n_badcmds = 0; /* count of bad commands */ volatile unsigned int n_badrcpts = 0; /* number of rejected RCPT */ volatile unsigned int n_verifies = 0; /* count of VRFY/EXPN */ volatile unsigned int n_etrn = 0; /* count of ETRN */ volatile unsigned int n_noop = 0; /* count of NOOP/VERB/etc */ volatile unsigned int n_helo = 0; /* count of HELO/EHLO */ bool ok; volatile bool first; volatile bool tempfail = false; volatile time_t wt; /* timeout after too many commands */ volatile time_t previous; /* time after checksmtpattack() */ volatile bool lognullconnection = true; register char *q; SMTP_T smtp; char *addr; char *greetcode = "220"; char *hostname; /* my hostname ($j) */ QUEUE_CHAR *new; char *args[MAXSMTPARGS]; char inp[MAXINPLINE]; #if MAXINPLINE < MAXLINE ERROR _MAXINPLINE must NOT be less than _MAXLINE: MAXINPLINE < MAXLINE #endif /* MAXINPLINE < MAXLINE */ char cmdbuf[MAXLINE]; #if SASL sasl_conn_t *conn; volatile bool sasl_ok; volatile unsigned int n_auth = 0; /* count of AUTH commands */ bool ismore; int result; volatile int authenticating; char *user; char *in, *out2; # if SASL >= 20000 char *auth_id = NULL; const char *out; sasl_ssf_t ext_ssf; char localip[60], remoteip[60]; # else /* SASL >= 20000 */ char *out; const char *errstr; sasl_external_properties_t ext_ssf; struct sockaddr_in saddr_l; struct sockaddr_in saddr_r; # endif /* SASL >= 20000 */ sasl_security_properties_t ssp; sasl_ssf_t *ssf; unsigned int inlen, out2len; unsigned int outlen; char *volatile auth_type; char *mechlist; volatile unsigned int n_mechs; unsigned int len; #else /* SASL */ #endif /* SASL */ int r; #if STARTTLS int rfd, wfd; volatile bool tls_active = false; volatile bool smtps = bitnset(D_SMTPS, d_flags); bool saveQuickAbort; bool saveSuprErrs; time_t tlsstart; #endif /* STARTTLS */ volatile unsigned int features; #if PIPELINING # if _FFR_NO_PIPE int np_log = 0; # endif /* _FFR_NO_PIPE */ #endif /* PIPELINING */ volatile time_t log_delay = (time_t) 0; #if MILTER volatile bool milter_cmd_done, milter_cmd_safe; volatile bool milter_rcpt_added, milter_cmd_fail; ADDRESS addr_st; # define p_addr_st &addr_st #else /* MILTER */ # define p_addr_st NULL #endif /* MILTER */ size_t inplen; #if _FFR_BADRCPT_SHUTDOWN int n_badrcpts_adj; #endif /* _FFR_BADRCPT_SHUTDOWN */ SevenBitInput_Saved = SevenBitInput; smtp.sm_nrcpts = 0; #if MILTER smtp.sm_milterize = (nullserver == NULL); smtp.sm_milterlist = false; addr = NULL; #endif /* MILTER */ /* setup I/O fd correctly for the SMTP server */ setup_smtpd_io(); #if SM_HEAP_CHECK if (sm_debug_active(&DebugLeakSmtp, 1)) { sm_heap_newgroup(); sm_dprintf("smtp() heap group #%d\n", sm_heap_group()); } #endif /* SM_HEAP_CHECK */ /* XXX the rpool should be set when e is initialized in main() */ e->e_rpool = sm_rpool_new_x(NULL); e->e_macro.mac_rpool = e->e_rpool; settime(e); sm_getla(); peerhostname = RealHostName; if (peerhostname == NULL) peerhostname = "localhost"; CurHostName = peerhostname; CurSmtpClient = macvalue('_', e); if (CurSmtpClient == NULL) CurSmtpClient = CurHostName; /* check_relay may have set discard bit, save for later */ smtp.sm_discard = bitset(EF_DISCARD, e->e_flags); #if PIPELINING /* auto-flush output when reading input */ (void) sm_io_autoflush(InChannel, OutChannel); #endif /* PIPELINING */ sm_setproctitle(true, e, "server %s startup", CurSmtpClient); /* Set default features for server. */ features = ((bitset(PRIV_NOETRN, PrivacyFlags) || bitnset(D_NOETRN, d_flags)) ? SRV_NONE : SRV_OFFER_ETRN) | (bitnset(D_AUTHREQ, d_flags) ? SRV_REQ_AUTH : SRV_NONE) | (bitset(PRIV_NOEXPN, PrivacyFlags) ? SRV_NONE : (SRV_OFFER_EXPN | (bitset(PRIV_NOVERB, PrivacyFlags) ? SRV_NONE : SRV_OFFER_VERB))) | ((bitset(PRIV_NORECEIPTS, PrivacyFlags) || !SendMIMEErrors) ? SRV_NONE : SRV_OFFER_DSN) #if SASL | (bitnset(D_NOAUTH, d_flags) ? SRV_NONE : SRV_OFFER_AUTH) | (bitset(SASL_SEC_NOPLAINTEXT, SASLOpts) ? SRV_REQ_SEC : SRV_NONE) #endif /* SASL */ #if PIPELINING | SRV_OFFER_PIPE #endif /* PIPELINING */ #if STARTTLS | (bitnset(D_NOTLS, d_flags) ? SRV_NONE : SRV_OFFER_TLS) | (bitset(TLS_I_NO_VRFY, TLS_Srv_Opts) ? SRV_NONE : SRV_VRFY_CLT) #endif /* STARTTLS */ ; if (nullserver == NULL) { features = srvfeatures(e, CurSmtpClient, features); if (bitset(SRV_TMP_FAIL, features)) { if (LogLevel > 4) sm_syslog(LOG_ERR, NOQID, "ERROR: srv_features=tempfail, relay=%.100s, access temporarily disabled", CurSmtpClient); nullserver = "450 4.3.0 Please try again later."; } else { #if PIPELINING # if _FFR_NO_PIPE if (bitset(SRV_NO_PIPE, features)) { /* for consistency */ features &= ~SRV_OFFER_PIPE; } # endif /* _FFR_NO_PIPE */ #endif /* PIPELINING */ #if SASL if (bitset(SRV_REQ_SEC, features)) SASLOpts |= SASL_SEC_NOPLAINTEXT; else SASLOpts &= ~SASL_SEC_NOPLAINTEXT; #endif /* SASL */ } } else if (strncmp(nullserver, "421 ", 4) == 0) { message(nullserver); goto doquit; } e->e_features = features; hostname = macvalue('j', e); #if SASL if (AuthRealm == NULL) AuthRealm = hostname; sasl_ok = bitset(SRV_OFFER_AUTH, features); n_mechs = 0; authenticating = SASL_NOT_AUTH; /* SASL server new connection */ if (sasl_ok) { # if SASL >= 20000 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, NULL, NULL, 0, &conn); # elif SASL > 10505 /* use empty realm: only works in SASL > 1.5.5 */ result = sasl_server_new("smtp", AuthRealm, "", NULL, 0, &conn); # else /* SASL >= 20000 */ /* use no realm -> realm is set to hostname by SASL lib */ result = sasl_server_new("smtp", AuthRealm, NULL, NULL, 0, &conn); # endif /* SASL >= 20000 */ sasl_ok = result == SASL_OK; if (!sasl_ok) { if (LogLevel > 9) sm_syslog(LOG_WARNING, NOQID, "AUTH error: sasl_server_new failed=%d", result); } } if (sasl_ok) { /* ** SASL set properties for sasl ** set local/remote IP ** XXX Cyrus SASL v1 only supports IPv4 ** ** XXX where exactly are these used/required? ** Kerberos_v4 */ # if SASL >= 20000 localip[0] = remoteip[0] = '\0'; # if NETINET || NETINET6 in = macvalue(macid("{daemon_family}"), e); if (in != NULL && ( # if NETINET6 strcmp(in, "inet6") == 0 || # endif /* NETINET6 */ strcmp(in, "inet") == 0)) { SOCKADDR_LEN_T addrsize; SOCKADDR saddr_l; SOCKADDR saddr_r; addrsize = sizeof(saddr_r); if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL), (struct sockaddr *) &saddr_r, &addrsize) == 0) { if (iptostring(&saddr_r, addrsize, remoteip, sizeof(remoteip))) { sasl_setprop(conn, SASL_IPREMOTEPORT, remoteip); } addrsize = sizeof(saddr_l); if (getsockname(sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL), (struct sockaddr *) &saddr_l, &addrsize) == 0) { if (iptostring(&saddr_l, addrsize, localip, sizeof(localip))) { sasl_setprop(conn, SASL_IPLOCALPORT, localip); } } } } # endif /* NETINET || NETINET6 */ # else /* SASL >= 20000 */ # if NETINET in = macvalue(macid("{daemon_family}"), e); if (in != NULL && strcmp(in, "inet") == 0) { SOCKADDR_LEN_T addrsize; addrsize = sizeof(struct sockaddr_in); if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL), (struct sockaddr *)&saddr_r, &addrsize) == 0) { sasl_setprop(conn, SASL_IP_REMOTE, &saddr_r); addrsize = sizeof(struct sockaddr_in); if (getsockname(sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL), (struct sockaddr *)&saddr_l, &addrsize) == 0) sasl_setprop(conn, SASL_IP_LOCAL, &saddr_l); } } # endif /* NETINET */ # endif /* SASL >= 20000 */ auth_type = NULL; mechlist = NULL; user = NULL; # if 0 macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{auth_author}"), NULL); # endif /* 0 */ /* set properties */ (void) memset(&ssp, '\0', sizeof(ssp)); /* XXX should these be options settable via .cf ? */ /* ssp.min_ssf = 0; is default due to memset() */ ssp.max_ssf = MaxSLBits; ssp.maxbufsize = MAXOUTLEN; ssp.security_flags = SASLOpts & SASL_SEC_MASK; sasl_ok = sasl_setprop(conn, SASL_SEC_PROPS, &ssp) == SASL_OK; if (sasl_ok) { /* ** external security strength factor; ** currently we have none so zero */ # if SASL >= 20000 ext_ssf = 0; auth_id = NULL; sasl_ok = ((sasl_setprop(conn, SASL_SSF_EXTERNAL, &ext_ssf) == SASL_OK) && (sasl_setprop(conn, SASL_AUTH_EXTERNAL, auth_id) == SASL_OK)); # else /* SASL >= 20000 */ ext_ssf.ssf = 0; ext_ssf.auth_id = NULL; sasl_ok = sasl_setprop(conn, SASL_SSF_EXTERNAL, &ext_ssf) == SASL_OK; # endif /* SASL >= 20000 */ } if (sasl_ok) n_mechs = saslmechs(conn, &mechlist); } #endif /* SASL */ #if STARTTLS set_tls_rd_tmo(TimeOuts.to_nextcommand); #endif /* STARTTLS */ #if MILTER if (smtp.sm_milterize) { char state; /* initialize mail filter connection */ smtp.sm_milterlist = milter_init(e, &state, &smtp.sm_milters); switch (state) { case SMFIR_REJECT: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: initialization failed, rejecting commands"); greetcode = "554"; nullserver = "Command rejected"; smtp.sm_milterize = false; break; case SMFIR_TEMPFAIL: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: initialization failed, temp failing commands"); tempfail = true; smtp.sm_milterize = false; break; case SMFIR_SHUTDOWN: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: initialization failed, closing connection"); tempfail = true; smtp.sm_milterize = false; message("421 4.7.0 %s closing connection", MyHostName); /* arrange to ignore send list */ e->e_sendqueue = NULL; lognullconnection = false; goto doquit; } } if (smtp.sm_milterlist && smtp.sm_milterize && !bitset(EF_DISCARD, e->e_flags)) { char state; char *response; q = macvalue(macid("{client_name}"), e); SM_ASSERT(q != NULL || OpMode == MD_SMTP); if (q == NULL) q = "localhost"; response = milter_connect(q, RealHostAddr, e, &state); switch (state) { case SMFIR_REPLYCODE: /* REPLYCODE shouldn't happen */ case SMFIR_REJECT: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: connect: host=%s, addr=%s, rejecting commands", peerhostname, anynet_ntoa(&RealHostAddr)); greetcode = "554"; nullserver = "Command rejected"; smtp.sm_milterize = false; break; case SMFIR_TEMPFAIL: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: connect: host=%s, addr=%s, temp failing commands", peerhostname, anynet_ntoa(&RealHostAddr)); tempfail = true; smtp.sm_milterize = false; break; case SMFIR_SHUTDOWN: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: connect: host=%s, addr=%s, shutdown", peerhostname, anynet_ntoa(&RealHostAddr)); tempfail = true; smtp.sm_milterize = false; message("421 4.7.0 %s closing connection", MyHostName); /* arrange to ignore send list */ e->e_sendqueue = NULL; goto doquit; } if (response != NULL) sm_free(response); /* XXX */ } #endif /* MILTER */ /* ** Broken proxies and SMTP slammers ** push data without waiting, catch them */ if ( #if STARTTLS !smtps && #endif /* STARTTLS */ *greetcode == '2' && nullserver == NULL) { time_t msecs = 0; char **pvp; char pvpbuf[PSBUFSIZE]; /* Ask the rulesets how long to pause */ pvp = NULL; r = rscap("greet_pause", peerhostname, anynet_ntoa(&RealHostAddr), e, &pvp, pvpbuf, sizeof(pvpbuf)); if (r == EX_OK && pvp != NULL && pvp[0] != NULL && (pvp[0][0] & 0377) == CANONNET && pvp[1] != NULL) { msecs = strtol(pvp[1], NULL, 10); } if (msecs > 0) { int fd; fd_set readfds; struct timeval timeout; struct timeval bp, ep, tp; /* {begin,end,total}pause */ int eoftest; /* pause for a moment */ timeout.tv_sec = msecs / 1000; timeout.tv_usec = (msecs % 1000) * 1000; /* Obey RFC 2821: 4.3.5.2: 220 timeout of 5 minutes */ if (timeout.tv_sec >= 300) { timeout.tv_sec = 300; timeout.tv_usec = 0; } /* check if data is on the socket during the pause */ fd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL); FD_ZERO(&readfds); SM_FD_SET(fd, &readfds); gettimeofday(&bp, NULL); if (select(fd + 1, FDSET_CAST &readfds, NULL, NULL, &timeout) > 0 && FD_ISSET(fd, &readfds) && (eoftest = sm_io_getc(InChannel, SM_TIME_DEFAULT)) != SM_IO_EOF) { sm_io_ungetc(InChannel, SM_TIME_DEFAULT, eoftest); gettimeofday(&ep, NULL); timersub(&ep, &bp, &tp); greetcode = "554"; nullserver = "Command rejected"; sm_syslog(LOG_INFO, e->e_id, "rejecting commands from %s [%s] due to pre-greeting traffic after %d seconds", peerhostname, anynet_ntoa(&RealHostAddr), (int) tp.tv_sec + (tp.tv_usec >= 500000 ? 1 : 0) ); } } } #if STARTTLS /* If this an smtps connection, start TLS now */ if (smtps) { Errors = 0; goto starttls; } greeting: #endif /* STARTTLS */ /* output the first line, inserting "ESMTP" as second word */ if (*greetcode == '5') (void) sm_snprintf(inp, sizeof(inp), "%s not accepting messages", hostname); else expand(SmtpGreeting, inp, sizeof(inp), e); p = strchr(inp, '\n'); if (p != NULL) *p++ = '\0'; id = strchr(inp, ' '); if (id == NULL) id = &inp[strlen(inp)]; if (p == NULL) (void) sm_snprintf(cmdbuf, sizeof(cmdbuf), "%s %%.*s ESMTP%%s", greetcode); else (void) sm_snprintf(cmdbuf, sizeof(cmdbuf), "%s-%%.*s ESMTP%%s", greetcode); message(cmdbuf, (int) (id - inp), inp, id); /* output remaining lines */ while ((id = p) != NULL && (p = strchr(id, '\n')) != NULL) { *p++ = '\0'; if (isascii(*id) && isspace(*id)) id++; (void) sm_strlcpyn(cmdbuf, sizeof(cmdbuf), 2, greetcode, "-%s"); message(cmdbuf, id); } if (id != NULL) { if (isascii(*id) && isspace(*id)) id++; (void) sm_strlcpyn(cmdbuf, sizeof(cmdbuf), 2, greetcode, " %s"); message(cmdbuf, id); } protocol = NULL; sendinghost = macvalue('s', e); /* If quarantining by a connect/ehlo action, save between messages */ if (e->e_quarmsg == NULL) smtp.sm_quarmsg = NULL; else smtp.sm_quarmsg = newstr(e->e_quarmsg); /* sendinghost's storage must outlive the current envelope */ if (sendinghost != NULL) sendinghost = sm_strdup_x(sendinghost); first = true; gothello = false; smtp.sm_gotmail = false; for (;;) { SM_TRY { QuickAbort = false; HoldErrs = false; SuprErrs = false; LogUsrErrs = false; OnlyOneError = true; e->e_flags &= ~(EF_VRFYONLY|EF_GLOBALERRS); #if MILTER milter_cmd_fail = false; #endif /* MILTER */ /* setup for the read */ e->e_to = NULL; Errors = 0; FileName = NULL; (void) sm_io_flush(smioout, SM_TIME_DEFAULT); /* read the input line */ SmtpPhase = "server cmd read"; sm_setproctitle(true, e, "server %s cmd read", CurSmtpClient); /* handle errors */ if (sm_io_error(OutChannel) || (p = sfgets(inp, sizeof(inp), InChannel, TimeOuts.to_nextcommand, SmtpPhase)) == NULL) { char *d; d = macvalue(macid("{daemon_name}"), e); if (d == NULL) d = "stdin"; /* end of file, just die */ disconnect(1, e); #if MILTER /* close out milter filters */ milter_quit(e); #endif /* MILTER */ message("421 4.4.1 %s Lost input channel from %s", MyHostName, CurSmtpClient); if (LogLevel > (smtp.sm_gotmail ? 1 : 19)) sm_syslog(LOG_NOTICE, e->e_id, "lost input channel from %s to %s after %s", CurSmtpClient, d, (c == NULL || c->cmd_name == NULL) ? "startup" : c->cmd_name); /* ** If have not accepted mail (DATA), do not bounce ** bad addresses back to sender. */ if (bitset(EF_CLRQUEUE, e->e_flags)) e->e_sendqueue = NULL; goto doquit; } /* also used by "proxy" check below */ inplen = strlen(inp); #if SASL /* ** SMTP AUTH requires accepting any length, ** at least for challenge/response. However, not imposing ** a limit is a bad idea (denial of service). */ if (authenticating != SASL_PROC_AUTH && sm_strncasecmp(inp, "AUTH ", 5) != 0 && inplen > MAXLINE) { message("421 4.7.0 %s Command too long, possible attack %s", MyHostName, CurSmtpClient); sm_syslog(LOG_INFO, e->e_id, "%s: SMTP violation, input too long: %lu", CurSmtpClient, (unsigned long) inplen); goto doquit; } #endif /* SASL */ if (first) { size_t cmdlen; int idx; char *http_cmd; static char *http_cmds[] = { "GET", "POST", "CONNECT", "USER", NULL }; for (idx = 0; (http_cmd = http_cmds[idx]) != NULL; idx++) { cmdlen = strlen(http_cmd); if (cmdlen < inplen && sm_strncasecmp(inp, http_cmd, cmdlen) == 0 && isascii(inp[cmdlen]) && isspace(inp[cmdlen])) { /* Open proxy, drop it */ message("421 4.7.0 %s Rejecting open proxy %s", MyHostName, CurSmtpClient); sm_syslog(LOG_INFO, e->e_id, "%s: probable open proxy: command=%.40s", CurSmtpClient, inp); goto doquit; } } first = false; } /* clean up end of line */ fixcrlf(inp, true); #if PIPELINING # if _FFR_NO_PIPE /* ** if there is more input and pipelining is disabled: ** delay ... (and maybe discard the input?) ** XXX this doesn't really work, at least in tests using ** telnet SM_IO_IS_READABLE only returns 1 if there were ** more than 2 input lines available. */ if (bitset(SRV_NO_PIPE, features) && sm_io_getinfo(InChannel, SM_IO_IS_READABLE, NULL) > 0) { if (++np_log < 3) sm_syslog(LOG_INFO, NOQID, "unauthorized PIPELINING, sleeping, relay=%.100s", CurSmtpClient); sleep(1); } # endif /* _FFR_NO_PIPE */ #endif /* PIPELINING */ #if SASL if (authenticating == SASL_PROC_AUTH) { # if 0 if (*inp == '\0') { authenticating = SASL_NOT_AUTH; message("501 5.5.2 missing input"); RESET_SASLCONN; continue; } # endif /* 0 */ if (*inp == '*' && *(inp + 1) == '\0') { authenticating = SASL_NOT_AUTH; /* RFC 2554 4. */ message("501 5.0.0 AUTH aborted"); RESET_SASLCONN; continue; } /* could this be shorter? XXX */ # if SASL >= 20000 in = xalloc(strlen(inp) + 1); result = sasl_decode64(inp, strlen(inp), in, strlen(inp), &inlen); # else /* SASL >= 20000 */ out = xalloc(strlen(inp)); result = sasl_decode64(inp, strlen(inp), out, &outlen); # endif /* SASL >= 20000 */ if (result != SASL_OK) { authenticating = SASL_NOT_AUTH; /* RFC 2554 4. */ message("501 5.5.4 cannot decode AUTH parameter %s", inp); # if SASL >= 20000 sm_free(in); # endif /* SASL >= 20000 */ RESET_SASLCONN; continue; } # if SASL >= 20000 result = sasl_server_step(conn, in, inlen, &out, &outlen); sm_free(in); # else /* SASL >= 20000 */ result = sasl_server_step(conn, out, outlen, &out, &outlen, &errstr); # endif /* SASL >= 20000 */ /* get an OK if we're done */ if (result == SASL_OK) { authenticated: message("235 2.0.0 OK Authenticated"); authenticating = SASL_IS_AUTH; macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{auth_type}"), auth_type); # if SASL >= 20000 user = macvalue(macid("{auth_authen}"), e); /* get security strength (features) */ result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf); # else /* SASL >= 20000 */ result = sasl_getprop(conn, SASL_USERNAME, (void **)&user); if (result != SASL_OK) { user = ""; macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{auth_authen}"), NULL); } else { macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{auth_authen}"), xtextify(user, "<>\")")); } # if 0 /* get realm? */ sasl_getprop(conn, SASL_REALM, (void **) &data); # endif /* 0 */ /* get security strength (features) */ result = sasl_getprop(conn, SASL_SSF, (void **) &ssf); # endif /* SASL >= 20000 */ if (result != SASL_OK) { macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{auth_ssf}"), "0"); ssf = NULL; } else { char pbuf[8]; (void) sm_snprintf(pbuf, sizeof(pbuf), "%u", *ssf); macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{auth_ssf}"), pbuf); if (tTd(95, 8)) sm_dprintf("AUTH auth_ssf: %u\n", *ssf); } /* ** Only switch to encrypted connection ** if a security layer has been negotiated */ if (ssf != NULL && *ssf > 0) { int tmo; /* ** Convert I/O layer to use SASL. ** If the call fails, the connection ** is aborted. */ tmo = TimeOuts.to_datablock * 1000; if (sfdcsasl(&InChannel, &OutChannel, conn, tmo) == 0) { /* restart dialogue */ n_helo = 0; # if PIPELINING (void) sm_io_autoflush(InChannel, OutChannel); # endif /* PIPELINING */ } else syserr("503 5.3.3 SASL TLS failed"); } /* NULL pointer ok since it's our function */ if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, "AUTH=server, relay=%s, authid=%.128s, mech=%.16s, bits=%d", CurSmtpClient, shortenstring(user, 128), auth_type, *ssf); } else if (result == SASL_CONTINUE) { len = ENC64LEN(outlen); out2 = xalloc(len); result = sasl_encode64(out, outlen, out2, len, &out2len); if (result != SASL_OK) { /* correct code? XXX */ /* 454 Temp. authentication failure */ message("454 4.5.4 Internal error: unable to encode64"); if (LogLevel > 5) sm_syslog(LOG_WARNING, e->e_id, "AUTH encode64 error [%d for \"%s\"], relay=%.100s", result, out, CurSmtpClient); /* start over? */ authenticating = SASL_NOT_AUTH; } else { message("334 %s", out2); if (tTd(95, 2)) sm_dprintf("AUTH continue: msg='%s' len=%u\n", out2, out2len); } # if SASL >= 20000 sm_free(out2); # endif /* SASL >= 20000 */ } else { /* not SASL_OK or SASL_CONT */ message("535 5.7.0 authentication failed"); if (LogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "AUTH failure (%s): %s (%d) %s, relay=%.100s", auth_type, sasl_errstring(result, NULL, NULL), result, # if SASL >= 20000 sasl_errdetail(conn), # else /* SASL >= 20000 */ errstr == NULL ? "" : errstr, # endif /* SASL >= 20000 */ CurSmtpClient); RESET_SASLCONN; authenticating = SASL_NOT_AUTH; } } else { /* don't want to do any of this if authenticating */ #endif /* SASL */ /* echo command to transcript */ if (e->e_xfp != NULL) (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "<<< %s\n", inp); if (LogLevel > 14) sm_syslog(LOG_INFO, e->e_id, "<-- %s", inp); /* break off command */ for (p = inp; isascii(*p) && isspace(*p); p++) continue; cmd = cmdbuf; while (*p != '\0' && !(isascii(*p) && isspace(*p)) && cmd < &cmdbuf[sizeof(cmdbuf) - 2]) *cmd++ = *p++; *cmd = '\0'; /* throw away leading whitespace */ SKIP_SPACE(p); /* decode command */ for (c = CmdTab; c->cmd_name != NULL; c++) { if (sm_strcasecmp(c->cmd_name, cmdbuf) == 0) break; } /* reset errors */ errno = 0; /* check whether a "non-null" command has been used */ switch (c->cmd_code) { #if SASL case CMDAUTH: /* avoid information leak; take first two words? */ q = "AUTH"; break; #endif /* SASL */ case CMDMAIL: case CMDEXPN: case CMDVRFY: case CMDETRN: lognullconnection = false; /* FALLTHROUGH */ default: q = inp; break; } if (e->e_id == NULL) sm_setproctitle(true, e, "%s: %.80s", CurSmtpClient, q); else sm_setproctitle(true, e, "%s %s: %.80s", qid_printname(e), CurSmtpClient, q); /* ** Process command. ** ** If we are running as a null server, return 550 ** to almost everything. */ if (nullserver != NULL || bitnset(D_ETRNONLY, d_flags)) { switch (c->cmd_code) { case CMDQUIT: case CMDHELO: case CMDEHLO: case CMDNOOP: case CMDRSET: case CMDERROR: /* process normally */ break; case CMDETRN: if (bitnset(D_ETRNONLY, d_flags) && nullserver == NULL) break; DELAY_CONN("ETRN"); /* FALLTHROUGH */ default: #if MAXBADCOMMANDS > 0 /* theoretically this could overflow */ if (nullserver != NULL && ++n_badcmds > MAXBADCOMMANDS) { message("421 4.7.0 %s Too many bad commands; closing connection", MyHostName); /* arrange to ignore send list */ e->e_sendqueue = NULL; goto doquit; } #endif /* MAXBADCOMMANDS > 0 */ if (nullserver != NULL) { if (ISSMTPREPLY(nullserver)) usrerr(nullserver); else usrerr("550 5.0.0 %s", nullserver); } else usrerr("452 4.4.5 Insufficient disk space; try again later"); continue; } } switch (c->cmd_code) { #if SASL case CMDAUTH: /* sasl */ DELAY_CONN("AUTH"); if (!sasl_ok || n_mechs <= 0) { message("503 5.3.3 AUTH not available"); break; } if (authenticating == SASL_IS_AUTH) { message("503 5.5.0 Already Authenticated"); break; } if (smtp.sm_gotmail) { message("503 5.5.0 AUTH not permitted during a mail transaction"); break; } if (tempfail) { if (LogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "SMTP AUTH command (%.100s) from %s tempfailed (due to previous checks)", p, CurSmtpClient); usrerr("454 4.3.0 Please try again later"); break; } ismore = false; /* crude way to avoid crack attempts */ STOP_IF_ATTACK(checksmtpattack(&n_auth, n_mechs + 1, true, "AUTH", e)); /* make sure mechanism (p) is a valid string */ for (q = p; *q != '\0' && isascii(*q); q++) { if (isspace(*q)) { *q = '\0'; while (*++q != '\0' && isascii(*q) && isspace(*q)) continue; *(q - 1) = '\0'; ismore = (*q != '\0'); break; } } if (*p == '\0') { message("501 5.5.2 AUTH mechanism must be specified"); break; } /* check whether mechanism is available */ if (iteminlist(p, mechlist, " ") == NULL) { message("504 5.3.3 AUTH mechanism %.32s not available", p); break; } /* ** RFC 2554 4. ** Unlike a zero-length client answer to a ** 334 reply, a zero- length initial response ** is sent as a single equals sign ("="). */ if (ismore && *q == '=' && *(q + 1) == '\0') { /* will be free()d, don't use in=""; */ in = xalloc(1); *in = '\0'; inlen = 0; } else if (ismore) { /* could this be shorter? XXX */ # if SASL >= 20000 in = xalloc(strlen(q) + 1); result = sasl_decode64(q, strlen(q), in, strlen(q), &inlen); # else /* SASL >= 20000 */ in = sm_rpool_malloc(e->e_rpool, strlen(q)); result = sasl_decode64(q, strlen(q), in, &inlen); # endif /* SASL >= 20000 */ if (result != SASL_OK) { message("501 5.5.4 cannot BASE64 decode '%s'", q); if (LogLevel > 5) sm_syslog(LOG_WARNING, e->e_id, "AUTH decode64 error [%d for \"%s\"], relay=%.100s", result, q, CurSmtpClient); /* start over? */ authenticating = SASL_NOT_AUTH; # if SASL >= 20000 sm_free(in); # endif /* SASL >= 20000 */ in = NULL; inlen = 0; break; } } else { in = NULL; inlen = 0; } /* see if that auth type exists */ # if SASL >= 20000 result = sasl_server_start(conn, p, in, inlen, &out, &outlen); if (in != NULL) sm_free(in); # else /* SASL >= 20000 */ result = sasl_server_start(conn, p, in, inlen, &out, &outlen, &errstr); # endif /* SASL >= 20000 */ if (result != SASL_OK && result != SASL_CONTINUE) { message("535 5.7.0 authentication failed"); if (LogLevel > 9) sm_syslog(LOG_ERR, e->e_id, "AUTH failure (%s): %s (%d) %s, relay=%.100s", p, sasl_errstring(result, NULL, NULL), result, # if SASL >= 20000 sasl_errdetail(conn), # else /* SASL >= 20000 */ errstr, # endif /* SASL >= 20000 */ CurSmtpClient); RESET_SASLCONN; break; } auth_type = newstr(p); if (result == SASL_OK) { /* ugly, but same code */ goto authenticated; /* authenticated by the initial response */ } /* len is at least 2 */ len = ENC64LEN(outlen); out2 = xalloc(len); result = sasl_encode64(out, outlen, out2, len, &out2len); if (result != SASL_OK) { message("454 4.5.4 Temporary authentication failure"); if (LogLevel > 5) sm_syslog(LOG_WARNING, e->e_id, "AUTH encode64 error [%d for \"%s\"]", result, out); /* start over? */ authenticating = SASL_NOT_AUTH; RESET_SASLCONN; } else { message("334 %s", out2); authenticating = SASL_PROC_AUTH; } # if SASL >= 20000 sm_free(out2); # endif /* SASL >= 20000 */ break; #endif /* SASL */ #if STARTTLS case CMDSTLS: /* starttls */ DELAY_CONN("STARTTLS"); if (*p != '\0') { message("501 5.5.2 Syntax error (no parameters allowed)"); break; } if (!bitset(SRV_OFFER_TLS, features)) { message("503 5.5.0 TLS not available"); break; } if (!tls_ok_srv) { message("454 4.3.3 TLS not available after start"); break; } if (smtp.sm_gotmail) { message("503 5.5.0 TLS not permitted during a mail transaction"); break; } if (tempfail) { if (LogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "SMTP STARTTLS command (%.100s) from %s tempfailed (due to previous checks)", p, CurSmtpClient); usrerr("454 4.7.0 Please try again later"); break; } starttls: # if USE_OPENSSL_ENGINE if (!SSLEngineInitialized) { if (!SSL_set_engine(NULL)) { sm_syslog(LOG_ERR, NOQID, "STARTTLS=server, SSL_set_engine=failed"); tls_ok_srv = false; message("454 4.3.3 TLS not available right now"); break; } else SSLEngineInitialized = true; } # endif /* USE_OPENSSL_ENGINE */ # if TLS_NO_RSA /* ** XXX do we need a temp key ? */ # else /* TLS_NO_RSA */ # endif /* TLS_NO_RSA */ # if TLS_VRFY_PER_CTX /* ** Note: this sets the verification globally ** (per SSL_CTX) ** it's ok since it applies only to one transaction */ TLS_VERIFY_CLIENT(); # endif /* TLS_VRFY_PER_CTX */ if (srv_ssl != NULL) SSL_clear(srv_ssl); else if ((srv_ssl = SSL_new(srv_ctx)) == NULL) { message("454 4.3.3 TLS not available: error generating SSL handle"); if (LogLevel > 8) - tlslogerr("server"); + tlslogerr(LOG_WARNING, "server"); goto tls_done; } # if !TLS_VRFY_PER_CTX /* ** this could be used if it were possible to set ** verification per SSL (connection) ** not just per SSL_CTX (global) */ TLS_VERIFY_CLIENT(); # endif /* !TLS_VRFY_PER_CTX */ rfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL); wfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL); if (rfd < 0 || wfd < 0 || SSL_set_rfd(srv_ssl, rfd) <= 0 || SSL_set_wfd(srv_ssl, wfd) <= 0) { message("454 4.3.3 TLS not available: error set fd"); SSL_free(srv_ssl); srv_ssl = NULL; goto tls_done; } if (!smtps) message("220 2.0.0 Ready to start TLS"); # if PIPELINING (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT); # endif /* PIPELINING */ SSL_set_accept_state(srv_ssl); # define SSL_ACC(s) SSL_accept(s) tlsstart = curtime(); ssl_retry: if ((r = SSL_ACC(srv_ssl)) <= 0) { int i, ssl_err; ssl_err = SSL_get_error(srv_ssl, r); i = tls_retry(srv_ssl, rfd, wfd, tlsstart, TimeOuts.to_starttls, ssl_err, "server"); if (i > 0) goto ssl_retry; if (LogLevel > 5) { unsigned long l; const char *sr; l = ERR_peek_error(); sr = ERR_reason_error_string(l); sm_syslog(LOG_WARNING, NOQID, "STARTTLS=server, error: accept failed=%d, reason=%s, SSL_error=%d, errno=%d, retry=%d, relay=%.100s", r, sr == NULL ? "unknown" : sr, ssl_err, errno, i, CurSmtpClient); if (LogLevel > 9) - tlslogerr("server"); + tlslogerr(LOG_WARNING, "server"); } tls_ok_srv = false; SSL_free(srv_ssl); srv_ssl = NULL; /* ** according to the next draft of ** RFC 2487 the connection should be dropped */ /* arrange to ignore any current send list */ e->e_sendqueue = NULL; goto doquit; } /* ignore return code for now, it's in {verify} */ (void) tls_get_info(srv_ssl, true, CurSmtpClient, &BlankEnvelope.e_macro, bitset(SRV_VRFY_CLT, features)); /* ** call Stls_client to find out whether ** to accept the connection from the client */ saveQuickAbort = QuickAbort; saveSuprErrs = SuprErrs; SuprErrs = true; QuickAbort = false; if (rscheck("tls_client", macvalue(macid("{verify}"), e), "STARTTLS", e, RSF_RMCOMM|RSF_COUNT, 5, NULL, NOQID, NULL) != EX_OK || Errors > 0) { extern char MsgBuf[]; if (MsgBuf[0] != '\0' && ISSMTPREPLY(MsgBuf)) nullserver = newstr(MsgBuf); else nullserver = "503 5.7.0 Authentication required."; } QuickAbort = saveQuickAbort; SuprErrs = saveSuprErrs; tls_ok_srv = false; /* don't offer STARTTLS again */ n_helo = 0; # if SASL if (sasl_ok) { int cipher_bits; bool verified; char *s, *v, *c; s = macvalue(macid("{cipher_bits}"), e); v = macvalue(macid("{verify}"), e); c = macvalue(macid("{cert_subject}"), e); verified = (v != NULL && strcmp(v, "OK") == 0); if (s != NULL && (cipher_bits = atoi(s)) > 0) { # if SASL >= 20000 ext_ssf = cipher_bits; auth_id = verified ? c : NULL; sasl_ok = ((sasl_setprop(conn, SASL_SSF_EXTERNAL, &ext_ssf) == SASL_OK) && (sasl_setprop(conn, SASL_AUTH_EXTERNAL, auth_id) == SASL_OK)); # else /* SASL >= 20000 */ ext_ssf.ssf = cipher_bits; ext_ssf.auth_id = verified ? c : NULL; sasl_ok = sasl_setprop(conn, SASL_SSF_EXTERNAL, &ext_ssf) == SASL_OK; # endif /* SASL >= 20000 */ mechlist = NULL; if (sasl_ok) n_mechs = saslmechs(conn, &mechlist); } } # endif /* SASL */ /* switch to secure connection */ if (sfdctls(&InChannel, &OutChannel, srv_ssl) == 0) { tls_active = true; # if PIPELINING (void) sm_io_autoflush(InChannel, OutChannel); # endif /* PIPELINING */ } else { /* ** XXX this is an internal error ** how to deal with it? ** we can't generate an error message ** since the other side switched to an ** encrypted layer, but we could not... ** just "hang up"? */ nullserver = "454 4.3.3 TLS not available: can't switch to encrypted layer"; syserr("STARTTLS: can't switch to encrypted layer"); } tls_done: if (smtps) { if (tls_active) goto greeting; else goto doquit; } break; #endif /* STARTTLS */ case CMDHELO: /* hello -- introduce yourself */ case CMDEHLO: /* extended hello */ DELAY_CONN("EHLO"); if (c->cmd_code == CMDEHLO) { protocol = "ESMTP"; SmtpPhase = "server EHLO"; } else { protocol = "SMTP"; SmtpPhase = "server HELO"; } /* avoid denial-of-service */ STOP_IF_ATTACK(checksmtpattack(&n_helo, MAXHELOCOMMANDS, true, "HELO/EHLO", e)); #if 0 /* RFC2821 4.1.4 allows duplicate HELO/EHLO */ /* check for duplicate HELO/EHLO per RFC 1651 4.2 */ if (gothello) { usrerr("503 %s Duplicate HELO/EHLO", MyHostName); break; } #endif /* 0 */ /* check for valid domain name (re 1123 5.2.5) */ if (*p == '\0' && !AllowBogusHELO) { usrerr("501 %s requires domain address", cmdbuf); break; } /* check for long domain name (hides Received: info) */ if (strlen(p) > MAXNAME) { usrerr("501 Invalid domain name"); if (LogLevel > 9) sm_syslog(LOG_INFO, CurEnv->e_id, "invalid domain name (too long) from %s", CurSmtpClient); break; } ok = true; for (q = p; *q != '\0'; q++) { if (!isascii(*q)) break; if (isalnum(*q)) continue; if (isspace(*q)) { *q = '\0'; /* only complain if strict check */ ok = AllowBogusHELO; /* allow trailing whitespace */ while (!ok && *++q != '\0' && isspace(*q)) ; if (*q == '\0') ok = true; break; } if (strchr("[].-_#:", *q) == NULL) break; } if (*q == '\0' && ok) { q = "pleased to meet you"; sendinghost = sm_strdup_x(p); } else if (!AllowBogusHELO) { usrerr("501 Invalid domain name"); if (LogLevel > 9) sm_syslog(LOG_INFO, CurEnv->e_id, "invalid domain name (%s) from %.100s", p, CurSmtpClient); break; } else { q = "accepting invalid domain name"; } if (gothello || smtp.sm_gotmail) CLEAR_STATE(cmdbuf); #if MILTER if (smtp.sm_milterlist && smtp.sm_milterize && !bitset(EF_DISCARD, e->e_flags)) { char state; char *response; response = milter_helo(p, e, &state); switch (state) { case SMFIR_REJECT: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: helo=%s, reject=Command rejected", p); nullserver = "Command rejected"; smtp.sm_milterize = false; break; case SMFIR_TEMPFAIL: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: helo=%s, reject=%s", p, MSG_TEMPFAIL); tempfail = true; smtp.sm_milterize = false; break; case SMFIR_REPLYCODE: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: helo=%s, reject=%s", p, response); if (strncmp(response, "421 ", 4) != 0 && strncmp(response, "421-", 4) != 0) { nullserver = newstr(response); smtp.sm_milterize = false; break; } /* FALLTHROUGH */ case SMFIR_SHUTDOWN: if (MilterLogLevel > 3 && response == NULL) sm_syslog(LOG_INFO, e->e_id, "Milter: helo=%s, reject=421 4.7.0 %s closing connection", p, MyHostName); tempfail = true; smtp.sm_milterize = false; if (response != NULL) usrerr(response); else message("421 4.7.0 %s closing connection", MyHostName); /* arrange to ignore send list */ e->e_sendqueue = NULL; lognullconnection = false; goto doquit; } if (response != NULL) sm_free(response); /* ** If quarantining by a connect/ehlo action, ** save between messages */ if (smtp.sm_quarmsg == NULL && e->e_quarmsg != NULL) smtp.sm_quarmsg = newstr(e->e_quarmsg); } #endif /* MILTER */ gothello = true; /* print HELO response message */ if (c->cmd_code != CMDEHLO) { message("250 %s Hello %s, %s", MyHostName, CurSmtpClient, q); break; } message("250-%s Hello %s, %s", MyHostName, CurSmtpClient, q); /* offer ENHSC even for nullserver */ if (nullserver != NULL) { message("250 ENHANCEDSTATUSCODES"); break; } /* ** print EHLO features list ** ** Note: If you change this list, ** remember to update 'helpfile' */ message("250-ENHANCEDSTATUSCODES"); #if PIPELINING if (bitset(SRV_OFFER_PIPE, features)) message("250-PIPELINING"); #endif /* PIPELINING */ if (bitset(SRV_OFFER_EXPN, features)) { message("250-EXPN"); if (bitset(SRV_OFFER_VERB, features)) message("250-VERB"); } #if MIME8TO7 message("250-8BITMIME"); #endif /* MIME8TO7 */ if (MaxMessageSize > 0) message("250-SIZE %ld", MaxMessageSize); else message("250-SIZE"); #if DSN if (SendMIMEErrors && bitset(SRV_OFFER_DSN, features)) message("250-DSN"); #endif /* DSN */ if (bitset(SRV_OFFER_ETRN, features)) message("250-ETRN"); #if SASL if (sasl_ok && mechlist != NULL && *mechlist != '\0') message("250-AUTH %s", mechlist); #endif /* SASL */ #if STARTTLS if (tls_ok_srv && bitset(SRV_OFFER_TLS, features)) message("250-STARTTLS"); #endif /* STARTTLS */ if (DeliverByMin > 0) message("250-DELIVERBY %ld", (long) DeliverByMin); else if (DeliverByMin == 0) message("250-DELIVERBY"); /* < 0: no deliver-by */ message("250 HELP"); break; case CMDMAIL: /* mail -- designate sender */ SmtpPhase = "server MAIL"; DELAY_CONN("MAIL"); /* check for validity of this command */ if (!gothello && bitset(PRIV_NEEDMAILHELO, PrivacyFlags)) { usrerr("503 5.0.0 Polite people say HELO first"); break; } if (smtp.sm_gotmail) { usrerr("503 5.5.0 Sender already specified"); break; } #if SASL if (bitset(SRV_REQ_AUTH, features) && authenticating != SASL_IS_AUTH) { usrerr("530 5.7.0 Authentication required"); break; } #endif /* SASL */ p = skipword(p, "from"); if (p == NULL) break; if (tempfail) { if (LogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "SMTP MAIL command (%.100s) from %s tempfailed (due to previous checks)", p, CurSmtpClient); usrerr(MSG_TEMPFAIL); break; } /* make sure we know who the sending host is */ if (sendinghost == NULL) sendinghost = peerhostname; #if SM_HEAP_CHECK if (sm_debug_active(&DebugLeakSmtp, 1)) { sm_heap_newgroup(); sm_dprintf("smtp() heap group #%d\n", sm_heap_group()); } #endif /* SM_HEAP_CHECK */ if (Errors > 0) goto undo_no_pm; if (!gothello) { auth_warning(e, "%s didn't use HELO protocol", CurSmtpClient); } #ifdef PICKY_HELO_CHECK if (sm_strcasecmp(sendinghost, peerhostname) != 0 && (sm_strcasecmp(peerhostname, "localhost") != 0 || sm_strcasecmp(sendinghost, MyHostName) != 0)) { auth_warning(e, "Host %s claimed to be %s", CurSmtpClient, sendinghost); } #endif /* PICKY_HELO_CHECK */ if (protocol == NULL) protocol = "SMTP"; macdefine(&e->e_macro, A_PERM, 'r', protocol); macdefine(&e->e_macro, A_PERM, 's', sendinghost); if (Errors > 0) goto undo_no_pm; smtp.sm_nrcpts = 0; n_badrcpts = 0; macdefine(&e->e_macro, A_PERM, macid("{ntries}"), "0"); macdefine(&e->e_macro, A_PERM, macid("{nrcpts}"), "0"); macdefine(&e->e_macro, A_PERM, macid("{nbadrcpts}"), "0"); e->e_flags |= EF_CLRQUEUE; sm_setproctitle(true, e, "%s %s: %.80s", qid_printname(e), CurSmtpClient, inp); /* do the processing */ SM_TRY { extern char *FullName; QuickAbort = true; SM_FREE_CLR(FullName); /* must parse sender first */ delimptr = NULL; setsender(p, e, &delimptr, ' ', false); if (delimptr != NULL && *delimptr != '\0') *delimptr++ = '\0'; if (Errors > 0) sm_exc_raisenew_x(&EtypeQuickAbort, 1); /* Successfully set e_from, allow logging */ e->e_flags |= EF_LOGSENDER; /* put resulting triple from parseaddr() into macros */ if (e->e_from.q_mailer != NULL) macdefine(&e->e_macro, A_PERM, macid("{mail_mailer}"), e->e_from.q_mailer->m_name); else macdefine(&e->e_macro, A_PERM, macid("{mail_mailer}"), NULL); if (e->e_from.q_host != NULL) macdefine(&e->e_macro, A_PERM, macid("{mail_host}"), e->e_from.q_host); else macdefine(&e->e_macro, A_PERM, macid("{mail_host}"), "localhost"); if (e->e_from.q_user != NULL) macdefine(&e->e_macro, A_PERM, macid("{mail_addr}"), e->e_from.q_user); else macdefine(&e->e_macro, A_PERM, macid("{mail_addr}"), NULL); if (Errors > 0) sm_exc_raisenew_x(&EtypeQuickAbort, 1); /* check for possible spoofing */ if (RealUid != 0 && OpMode == MD_SMTP && !wordinclass(RealUserName, 't') && (!bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags) || strcmp(e->e_from.q_user, RealUserName) != 0)) { auth_warning(e, "%s owned process doing -bs", RealUserName); } /* reset to default value */ SevenBitInput = SevenBitInput_Saved; /* now parse ESMTP arguments */ e->e_msgsize = 0; addr = p; parse_esmtp_args(e, NULL, p, delimptr, "MAIL", args, mail_esmtp_args); if (Errors > 0) sm_exc_raisenew_x(&EtypeQuickAbort, 1); #if SASL # if _FFR_AUTH_PASSING /* set the default AUTH= if the sender didn't */ if (e->e_auth_param == NULL) { /* XXX only do this for an MSA? */ e->e_auth_param = macvalue(macid("{auth_authen}"), e); if (e->e_auth_param == NULL) e->e_auth_param = "<>"; /* ** XXX should we invoke Strust_auth now? ** authorizing as the client that just ** authenticated, so we'll trust implicitly */ } # endif /* _FFR_AUTH_PASSING */ #endif /* SASL */ /* do config file checking of the sender */ macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e s"); #if _FFR_MAIL_MACRO /* make the "real" sender address available */ macdefine(&e->e_macro, A_TEMP, macid("{mail_from}"), e->e_from.q_paddr); #endif /* _FFR_MAIL_MACRO */ if (rscheck("check_mail", addr, NULL, e, RSF_RMCOMM|RSF_COUNT, 3, NULL, e->e_id, NULL) != EX_OK || Errors > 0) sm_exc_raisenew_x(&EtypeQuickAbort, 1); macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL); if (MaxMessageSize > 0 && (e->e_msgsize > MaxMessageSize || e->e_msgsize < 0)) { usrerr("552 5.2.3 Message size exceeds fixed maximum message size (%ld)", MaxMessageSize); sm_exc_raisenew_x(&EtypeQuickAbort, 1); } /* ** XXX always check whether there is at least one fs ** with enough space? ** However, this may not help much: the queue group ** selection may later on select a FS that hasn't ** enough space. */ if ((NumFileSys == 1 || NumQueue == 1) && !enoughdiskspace(e->e_msgsize, e) #if _FFR_ANY_FREE_FS && !filesys_free(e->e_msgsize) #endif /* _FFR_ANY_FREE_FS */ ) { /* ** We perform this test again when the ** queue directory is selected, in collect. */ usrerr("452 4.4.5 Insufficient disk space; try again later"); sm_exc_raisenew_x(&EtypeQuickAbort, 1); } if (Errors > 0) sm_exc_raisenew_x(&EtypeQuickAbort, 1); LogUsrErrs = true; #if MILTER if (smtp.sm_milterlist && smtp.sm_milterize && !bitset(EF_DISCARD, e->e_flags)) { char state; char *response; response = milter_envfrom(args, e, &state); MILTER_REPLY("from"); } #endif /* MILTER */ if (Errors > 0) sm_exc_raisenew_x(&EtypeQuickAbort, 1); message("250 2.1.0 Sender ok"); smtp.sm_gotmail = true; } SM_EXCEPT(exc, "[!F]*") { /* ** An error occurred while processing a MAIL command. ** Jump to the common error handling code. */ sm_exc_free(exc); goto undo_no_pm; } SM_END_TRY break; undo_no_pm: e->e_flags &= ~EF_PM_NOTIFY; undo: break; case CMDRCPT: /* rcpt -- designate recipient */ DELAY_CONN("RCPT"); macdefine(&e->e_macro, A_PERM, macid("{rcpt_mailer}"), NULL); macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), NULL); macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), NULL); #if MILTER (void) memset(&addr_st, '\0', sizeof(addr_st)); a = NULL; milter_rcpt_added = false; smtp.sm_e_nrcpts_orig = e->e_nrcpts; #endif #if _FFR_BADRCPT_SHUTDOWN /* ** hack to deal with hack, see below: ** n_badrcpts is increased if limit is reached. */ n_badrcpts_adj = (BadRcptThrottle > 0 && n_badrcpts > BadRcptThrottle && LogLevel > 5) ? n_badrcpts - 1 : n_badrcpts; if (BadRcptShutdown > 0 && n_badrcpts_adj >= BadRcptShutdown && (BadRcptShutdownGood == 0 || smtp.sm_nrcpts == 0 || (n_badrcpts_adj * 100 / (smtp.sm_nrcpts + n_badrcpts) >= BadRcptShutdownGood))) { if (LogLevel > 5) sm_syslog(LOG_INFO, e->e_id, "%s: Possible SMTP RCPT flood, shutting down connection.", CurSmtpClient); message("421 4.7.0 %s Too many bad recipients; closing connection", MyHostName); /* arrange to ignore any current send list */ e->e_sendqueue = NULL; goto doquit; } #endif /* _FFR_BADRCPT_SHUTDOWN */ if (BadRcptThrottle > 0 && n_badrcpts >= BadRcptThrottle) { if (LogLevel > 5 && n_badrcpts == BadRcptThrottle) { sm_syslog(LOG_INFO, e->e_id, "%s: Possible SMTP RCPT flood, throttling.", CurSmtpClient); /* To avoid duplicated message */ n_badrcpts++; } NBADRCPTS; /* ** Don't use exponential backoff for now. ** Some systems will open more connections ** and actually overload the receiver even ** more. */ (void) sleep(BadRcptThrottleDelay); } if (!smtp.sm_gotmail) { usrerr("503 5.0.0 Need MAIL before RCPT"); break; } SmtpPhase = "server RCPT"; SM_TRY { QuickAbort = true; LogUsrErrs = true; /* limit flooding of our machine */ if (MaxRcptPerMsg > 0 && smtp.sm_nrcpts >= MaxRcptPerMsg) { /* sleep(1); / * slow down? */ usrerr("452 4.5.3 Too many recipients"); goto rcpt_done; } if (!SM_IS_INTERACTIVE(e->e_sendmode) #if _FFR_DM_ONE && (NotFirstDelivery || SM_DM_ONE != e->e_sendmode) #endif /* _FFR_DM_ONE */ ) e->e_flags |= EF_VRFYONLY; #if MILTER /* ** Do not expand recipients at RCPT time (in the call ** to recipient()) if a milter can delete or reject ** a RCPT. If they are expanded, it is impossible ** for removefromlist() to figure out the expanded ** members of the original recipient and mark them ** as QS_DONTSEND. */ if (!(smtp.sm_milterlist && smtp.sm_milterize && !bitset(EF_DISCARD, e->e_flags)) && (smtp.sm_milters.mis_flags & (MIS_FL_DEL_RCPT|MIS_FL_REJ_RCPT)) != 0) e->e_flags |= EF_VRFYONLY; milter_cmd_done = false; milter_cmd_safe = false; #endif /* MILTER */ p = skipword(p, "to"); if (p == NULL) goto rcpt_done; macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r"); a = parseaddr(p, NULLADDR, RF_COPYALL, ' ', &delimptr, e, true); macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL); if (Errors > 0) goto rcpt_done; if (a == NULL) { usrerr("501 5.0.0 Missing recipient"); goto rcpt_done; } if (delimptr != NULL && *delimptr != '\0') *delimptr++ = '\0'; /* put resulting triple from parseaddr() into macros */ if (a->q_mailer != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_mailer}"), a->q_mailer->m_name); else macdefine(&e->e_macro, A_PERM, macid("{rcpt_mailer}"), NULL); if (a->q_host != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), a->q_host); else macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), "localhost"); if (a->q_user != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), a->q_user); else macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), NULL); if (Errors > 0) goto rcpt_done; /* now parse ESMTP arguments */ addr = p; parse_esmtp_args(e, a, p, delimptr, "RCPT", args, rcpt_esmtp_args); if (Errors > 0) goto rcpt_done; #if MILTER /* ** rscheck() can trigger an "exception" ** in which case the execution continues at ** SM_EXCEPT(exc, "[!F]*") ** This means milter_cmd_safe is not set ** and hence milter is not invoked. ** Would it be "safe" to change that, i.e., use ** milter_cmd_safe = true; ** here so a milter is informed (if requested) ** about RCPTs that are rejected by check_rcpt? */ # if _FFR_MILTER_CHECK_REJECTIONS_TOO milter_cmd_safe = true; # endif #endif /* do config file checking of the recipient */ macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r"); if (rscheck("check_rcpt", addr, NULL, e, RSF_RMCOMM|RSF_COUNT, 3, NULL, e->e_id, p_addr_st) != EX_OK || Errors > 0) goto rcpt_done; macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL); /* If discarding, don't bother to verify user */ if (bitset(EF_DISCARD, e->e_flags)) a->q_state = QS_VERIFIED; #if MILTER milter_cmd_safe = true; #endif /* save in recipient list after ESMTP mods */ a = recipient(a, &e->e_sendqueue, 0, e); /* may trigger exception... */ #if MILTER milter_rcpt_added = true; #endif if(!(Errors > 0) && QS_IS_BADADDR(a->q_state)) { /* punt -- should keep message in ADDRESS.... */ usrerr("550 5.1.1 Addressee unknown"); } #if MILTER rcpt_done: if (smtp.sm_milterlist && smtp.sm_milterize && !bitset(EF_DISCARD, e->e_flags)) { char state; char *response; /* how to get the error codes? */ if (Errors > 0) { macdefine(&e->e_macro, A_PERM, macid("{rcpt_mailer}"), "error"); if (a != NULL && a->q_status != NULL && a->q_rstatus != NULL) { macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), a->q_status); macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), a->q_rstatus); } else { if (addr_st.q_host != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), addr_st.q_host); if (addr_st.q_user != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), addr_st.q_user); } } response = milter_envrcpt(args, e, &state, Errors > 0); milter_cmd_done = true; MILTER_REPLY("to"); } #endif /* MILTER */ /* no errors during parsing, but might be a duplicate */ e->e_to = a->q_paddr; if (!(Errors > 0) && !QS_IS_BADADDR(a->q_state)) { if (smtp.sm_nrcpts == 0) initsys(e); message("250 2.1.5 Recipient ok%s", QS_IS_QUEUEUP(a->q_state) ? " (will queue)" : ""); smtp.sm_nrcpts++; } /* Is this needed? */ #if !MILTER rcpt_done: #endif /* !MILTER */ macdefine(&e->e_macro, A_PERM, macid("{rcpt_mailer}"), NULL); macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), NULL); macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), NULL); macdefine(&e->e_macro, A_PERM, macid("{dsn_notify}"), NULL); if (Errors > 0) { ++n_badrcpts; NBADRCPTS; } } SM_EXCEPT(exc, "[!F]*") { /* An exception occurred while processing RCPT */ e->e_flags &= ~(EF_FATALERRS|EF_PM_NOTIFY); ++n_badrcpts; NBADRCPTS; #if MILTER if (smtp.sm_milterlist && smtp.sm_milterize && !bitset(EF_DISCARD, e->e_flags) && !milter_cmd_done && milter_cmd_safe) { char state; char *response; macdefine(&e->e_macro, A_PERM, macid("{rcpt_mailer}"), "error"); /* how to get the error codes? */ if (addr_st.q_host != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), addr_st.q_host); else if (a != NULL && a->q_status != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), a->q_status); if (addr_st.q_user != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), addr_st.q_user); else if (a != NULL && a->q_rstatus != NULL) macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), a->q_rstatus); response = milter_envrcpt(args, e, &state, true); milter_cmd_done = true; MILTER_REPLY("to"); macdefine(&e->e_macro, A_PERM, macid("{rcpt_mailer}"), NULL); macdefine(&e->e_macro, A_PERM, macid("{rcpt_host}"), NULL); macdefine(&e->e_macro, A_PERM, macid("{rcpt_addr}"), NULL); } if (smtp.sm_milterlist && smtp.sm_milterize && milter_rcpt_added && milter_cmd_done && milter_cmd_fail) { (void) removefromlist(addr, &e->e_sendqueue, e); milter_cmd_fail = false; if (smtp.sm_e_nrcpts_orig < e->e_nrcpts) e->e_nrcpts = smtp.sm_e_nrcpts_orig; } #endif /* MILTER */ } SM_END_TRY break; case CMDDATA: /* data -- text of mail */ DELAY_CONN("DATA"); if (!smtp_data(&smtp, e)) goto doquit; break; case CMDRSET: /* rset -- reset state */ if (tTd(94, 100)) message("451 4.0.0 Test failure"); else message("250 2.0.0 Reset state"); CLEAR_STATE(cmdbuf); break; case CMDVRFY: /* vrfy -- verify address */ case CMDEXPN: /* expn -- expand address */ vrfy = c->cmd_code == CMDVRFY; DELAY_CONN(vrfy ? "VRFY" : "EXPN"); if (tempfail) { if (LogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "SMTP %s command (%.100s) from %s tempfailed (due to previous checks)", vrfy ? "VRFY" : "EXPN", p, CurSmtpClient); /* RFC 821 doesn't allow 4xy reply code */ usrerr("550 5.7.1 Please try again later"); break; } wt = checksmtpattack(&n_verifies, MAXVRFYCOMMANDS, false, vrfy ? "VRFY" : "EXPN", e); STOP_IF_ATTACK(wt); previous = curtime(); if ((vrfy && bitset(PRIV_NOVRFY, PrivacyFlags)) || (!vrfy && !bitset(SRV_OFFER_EXPN, features))) { if (vrfy) message("252 2.5.2 Cannot VRFY user; try RCPT to attempt delivery (or try finger)"); else message("502 5.7.0 Sorry, we do not allow this operation"); if (LogLevel > 5) sm_syslog(LOG_INFO, e->e_id, "%s: %s [rejected]", CurSmtpClient, shortenstring(inp, MAXSHORTSTR)); break; } else if (!gothello && bitset(vrfy ? PRIV_NEEDVRFYHELO : PRIV_NEEDEXPNHELO, PrivacyFlags)) { usrerr("503 5.0.0 I demand that you introduce yourself first"); break; } if (Errors > 0) break; if (LogLevel > 5) sm_syslog(LOG_INFO, e->e_id, "%s: %s", CurSmtpClient, shortenstring(inp, MAXSHORTSTR)); SM_TRY { QuickAbort = true; vrfyqueue = NULL; if (vrfy) e->e_flags |= EF_VRFYONLY; while (*p != '\0' && isascii(*p) && isspace(*p)) p++; if (*p == '\0') { usrerr("501 5.5.2 Argument required"); } else { /* do config file checking of the address */ if (rscheck(vrfy ? "check_vrfy" : "check_expn", p, NULL, e, RSF_RMCOMM, 3, NULL, NOQID, NULL) != EX_OK || Errors > 0) sm_exc_raisenew_x(&EtypeQuickAbort, 1); (void) sendtolist(p, NULLADDR, &vrfyqueue, 0, e); } if (wt > 0) { time_t t; t = wt - (curtime() - previous); if (t > 0) (void) sleep(t); } if (Errors > 0) sm_exc_raisenew_x(&EtypeQuickAbort, 1); if (vrfyqueue == NULL) { usrerr("554 5.5.2 Nothing to %s", vrfy ? "VRFY" : "EXPN"); } while (vrfyqueue != NULL) { if (!QS_IS_UNDELIVERED(vrfyqueue->q_state)) { vrfyqueue = vrfyqueue->q_next; continue; } /* see if there is more in the vrfy list */ a = vrfyqueue; while ((a = a->q_next) != NULL && (!QS_IS_UNDELIVERED(a->q_state))) continue; printvrfyaddr(vrfyqueue, a == NULL, vrfy); vrfyqueue = a; } } SM_EXCEPT(exc, "[!F]*") { /* ** An exception occurred while processing VRFY/EXPN */ sm_exc_free(exc); goto undo; } SM_END_TRY break; case CMDETRN: /* etrn -- force queue flush */ DELAY_CONN("ETRN"); /* Don't leak queue information via debug flags */ if (!bitset(SRV_OFFER_ETRN, features) || UseMSP || (RealUid != 0 && RealUid != TrustedUid && OpMode == MD_SMTP)) { /* different message for MSA ? */ message("502 5.7.0 Sorry, we do not allow this operation"); if (LogLevel > 5) sm_syslog(LOG_INFO, e->e_id, "%s: %s [rejected]", CurSmtpClient, shortenstring(inp, MAXSHORTSTR)); break; } if (tempfail) { if (LogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "SMTP ETRN command (%.100s) from %s tempfailed (due to previous checks)", p, CurSmtpClient); usrerr(MSG_TEMPFAIL); break; } if (strlen(p) <= 0) { usrerr("500 5.5.2 Parameter required"); break; } /* crude way to avoid denial-of-service attacks */ STOP_IF_ATTACK(checksmtpattack(&n_etrn, MAXETRNCOMMANDS, true, "ETRN", e)); /* ** Do config file checking of the parameter. ** Even though we have srv_features now, we still ** need this ruleset because the former is called ** when the connection has been established, while ** this ruleset is called when the command is ** actually issued and therefore has all information ** available to make a decision. */ if (rscheck("check_etrn", p, NULL, e, RSF_RMCOMM, 3, NULL, NOQID, NULL) != EX_OK || Errors > 0) break; if (LogLevel > 5) sm_syslog(LOG_INFO, e->e_id, "%s: ETRN %s", CurSmtpClient, shortenstring(p, MAXSHORTSTR)); id = p; if (*id == '#') { int i, qgrp; id++; qgrp = name2qid(id); if (!ISVALIDQGRP(qgrp)) { usrerr("459 4.5.4 Queue %s unknown", id); break; } for (i = 0; i < NumQueue && Queue[i] != NULL; i++) Queue[i]->qg_nextrun = (time_t) -1; Queue[qgrp]->qg_nextrun = 0; ok = run_work_group(Queue[qgrp]->qg_wgrp, RWG_FORK|RWG_FORCE); if (ok && Errors == 0) message("250 2.0.0 Queuing for queue group %s started", id); break; } if (*id == '@') id++; else *--id = '@'; new = (QUEUE_CHAR *) sm_malloc(sizeof(QUEUE_CHAR)); if (new == NULL) { syserr("500 5.5.0 ETRN out of memory"); break; } new->queue_match = id; new->queue_negate = false; new->queue_next = NULL; QueueLimitRecipient = new; ok = runqueue(true, false, false, true); sm_free(QueueLimitRecipient); /* XXX */ QueueLimitRecipient = NULL; if (ok && Errors == 0) message("250 2.0.0 Queuing for node %s started", p); break; case CMDHELP: /* help -- give user info */ DELAY_CONN("HELP"); help(p, e); break; case CMDNOOP: /* noop -- do nothing */ DELAY_CONN("NOOP"); STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands, true, "NOOP", e)); message("250 2.0.0 OK"); break; case CMDQUIT: /* quit -- leave mail */ message("221 2.0.0 %s closing connection", MyHostName); #if PIPELINING (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT); #endif /* PIPELINING */ if (smtp.sm_nrcpts > 0) logundelrcpts(e, "aborted by sender", 9, false); /* arrange to ignore any current send list */ e->e_sendqueue = NULL; #if STARTTLS /* shutdown TLS connection */ if (tls_active) { (void) endtls(srv_ssl, "server"); tls_active = false; } #endif /* STARTTLS */ #if SASL if (authenticating == SASL_IS_AUTH) { sasl_dispose(&conn); authenticating = SASL_NOT_AUTH; /* XXX sasl_done(); this is a child */ } #endif /* SASL */ doquit: /* avoid future 050 messages */ disconnect(1, e); #if MILTER /* close out milter filters */ milter_quit(e); #endif /* MILTER */ if (tTd(92, 2)) sm_dprintf("QUIT: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n", e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel); if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags)) logsender(e, NULL); e->e_flags &= ~EF_LOGSENDER; if (lognullconnection && LogLevel > 5 && nullserver == NULL) { char *d; d = macvalue(macid("{daemon_name}"), e); if (d == NULL) d = "stdin"; /* ** even though this id is "bogus", it makes ** it simpler to "grep" related events, e.g., ** timeouts for the same connection. */ sm_syslog(LOG_INFO, e->e_id, "%s did not issue MAIL/EXPN/VRFY/ETRN during connection to %s", CurSmtpClient, d); } if (tTd(93, 100)) { /* return to handle next connection */ return; } finis(true, true, ExitStat); /* NOTREACHED */ /* just to avoid bogus warning from some compilers */ exit(EX_OSERR); case CMDVERB: /* set verbose mode */ DELAY_CONN("VERB"); if (!bitset(SRV_OFFER_EXPN, features) || !bitset(SRV_OFFER_VERB, features)) { /* this would give out the same info */ message("502 5.7.0 Verbose unavailable"); break; } STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands, true, "VERB", e)); Verbose = 1; set_delivery_mode(SM_DELIVER, e); message("250 2.0.0 Verbose mode"); break; #if SMTPDEBUG case CMDDBGQSHOW: /* show queues */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Send Queue="); printaddr(smioout, e->e_sendqueue, true); break; case CMDDBGDEBUG: /* set debug mode */ tTsetup(tTdvect, sizeof(tTdvect), "0-99.1"); tTflag(p); message("200 2.0.0 Debug set"); break; #else /* SMTPDEBUG */ case CMDDBGQSHOW: /* show queues */ case CMDDBGDEBUG: /* set debug mode */ #endif /* SMTPDEBUG */ case CMDLOGBOGUS: /* bogus command */ DELAY_CONN("Bogus"); if (LogLevel > 0) sm_syslog(LOG_CRIT, e->e_id, "\"%s\" command from %s (%.100s)", c->cmd_name, CurSmtpClient, anynet_ntoa(&RealHostAddr)); /* FALLTHROUGH */ case CMDERROR: /* unknown command */ #if MAXBADCOMMANDS > 0 if (++n_badcmds > MAXBADCOMMANDS) { stopattack: message("421 4.7.0 %s Too many bad commands; closing connection", MyHostName); /* arrange to ignore any current send list */ e->e_sendqueue = NULL; goto doquit; } #endif /* MAXBADCOMMANDS > 0 */ #if MILTER && SMFI_VERSION > 2 if (smtp.sm_milterlist && smtp.sm_milterize && !bitset(EF_DISCARD, e->e_flags)) { char state; char *response; if (MilterLogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "Sending \"%s\" to Milter", inp); response = milter_unknown(inp, e, &state); MILTER_REPLY("unknown"); if (state == SMFIR_REPLYCODE || state == SMFIR_REJECT || state == SMFIR_TEMPFAIL || state == SMFIR_SHUTDOWN) { /* MILTER_REPLY already gave an error */ break; } } #endif /* MILTER && SMFI_VERSION > 2 */ usrerr("500 5.5.1 Command unrecognized: \"%s\"", shortenstring(inp, MAXSHORTSTR)); break; case CMDUNIMPL: DELAY_CONN("Unimpl"); usrerr("502 5.5.1 Command not implemented: \"%s\"", shortenstring(inp, MAXSHORTSTR)); break; default: DELAY_CONN("default"); errno = 0; syserr("500 5.5.0 smtp: unknown code %d", c->cmd_code); break; } #if SASL } #endif /* SASL */ } SM_EXCEPT(exc, "[!F]*") { /* ** The only possible exception is "E:mta.quickabort". ** There is nothing to do except fall through and loop. */ } SM_END_TRY } } /* ** SMTP_DATA -- implement the SMTP DATA command. ** ** Parameters: ** smtp -- status of SMTP connection. ** e -- envelope. ** ** Returns: ** true iff SMTP session can continue. ** ** Side Effects: ** possibly sends message. */ static bool smtp_data(smtp, e) SMTP_T *smtp; ENVELOPE *e; { #if MILTER bool milteraccept; #endif /* MILTER */ bool aborting; bool doublequeue; bool rv = true; ADDRESS *a; ENVELOPE *ee; char *id; char *oldid; unsigned int features; char buf[32]; SmtpPhase = "server DATA"; if (!smtp->sm_gotmail) { usrerr("503 5.0.0 Need MAIL command"); return true; } else if (smtp->sm_nrcpts <= 0) { usrerr("503 5.0.0 Need RCPT (recipient)"); return true; } (void) sm_snprintf(buf, sizeof(buf), "%u", smtp->sm_nrcpts); if (rscheck("check_data", buf, NULL, e, RSF_RMCOMM|RSF_UNSTRUCTURED|RSF_COUNT, 3, NULL, e->e_id, NULL) != EX_OK) return true; #if MILTER && SMFI_VERSION > 3 if (smtp->sm_milterlist && smtp->sm_milterize && !bitset(EF_DISCARD, e->e_flags)) { char state; char *response; int savelogusrerrs = LogUsrErrs; response = milter_data_cmd(e, &state); switch (state) { case SMFIR_REPLYCODE: if (MilterLogLevel > 3) { sm_syslog(LOG_INFO, e->e_id, "Milter: cmd=data, reject=%s", response); LogUsrErrs = false; } #if _FFR_MILTER_ENHSC if (ISSMTPCODE(response)) (void) extenhsc(response + 4, ' ', e->e_enhsc); #endif /* _FFR_MILTER_ENHSC */ usrerr(response); if (strncmp(response, "421 ", 4) == 0 || strncmp(response, "421-", 4) == 0) { e->e_sendqueue = NULL; return false; } return true; case SMFIR_REJECT: if (MilterLogLevel > 3) { sm_syslog(LOG_INFO, e->e_id, "Milter: cmd=data, reject=550 5.7.1 Command rejected"); LogUsrErrs = false; } #if _FFR_MILTER_ENHSC (void) sm_strlcpy(e->e_enhsc, "5.7.1", sizeof(e->e_enhsc)); #endif /* _FFR_MILTER_ENHSC */ usrerr("550 5.7.1 Command rejected"); return true; case SMFIR_DISCARD: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: cmd=data, discard"); e->e_flags |= EF_DISCARD; break; case SMFIR_TEMPFAIL: if (MilterLogLevel > 3) { sm_syslog(LOG_INFO, e->e_id, "Milter: cmd=data, reject=%s", MSG_TEMPFAIL); LogUsrErrs = false; } #if _FFR_MILTER_ENHSC (void) extenhsc(MSG_TEMPFAIL + 4, ' ', e->e_enhsc); #endif /* _FFR_MILTER_ENHSC */ usrerr(MSG_TEMPFAIL); return true; case SMFIR_SHUTDOWN: if (MilterLogLevel > 3) { sm_syslog(LOG_INFO, e->e_id, "Milter: cmd=data, reject=421 4.7.0 %s closing connection", MyHostName); LogUsrErrs = false; } usrerr("421 4.7.0 %s closing connection", MyHostName); e->e_sendqueue = NULL; return false; } LogUsrErrs = savelogusrerrs; if (response != NULL) sm_free(response); /* XXX */ } #endif /* MILTER && SMFI_VERSION > 3 */ /* put back discard bit */ if (smtp->sm_discard) e->e_flags |= EF_DISCARD; /* check to see if we need to re-expand aliases */ /* also reset QS_BADADDR on already-diagnosted addrs */ doublequeue = false; for (a = e->e_sendqueue; a != NULL; a = a->q_next) { if (QS_IS_VERIFIED(a->q_state) && !bitset(EF_DISCARD, e->e_flags)) { /* need to re-expand aliases */ doublequeue = true; } if (QS_IS_BADADDR(a->q_state)) { /* make this "go away" */ a->q_state = QS_DONTSEND; } } /* collect the text of the message */ SmtpPhase = "collect"; buffer_errors(); collect(InChannel, true, NULL, e, true); /* redefine message size */ (void) sm_snprintf(buf, sizeof(buf), "%ld", PRT_NONNEGL(e->e_msgsize)); macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf); /* rscheck() will set Errors or EF_DISCARD if it trips */ (void) rscheck("check_eom", buf, NULL, e, RSF_UNSTRUCTURED|RSF_COUNT, 3, NULL, e->e_id, NULL); #if MILTER milteraccept = true; if (smtp->sm_milterlist && smtp->sm_milterize && Errors <= 0 && !bitset(EF_DISCARD, e->e_flags)) { char state; char *response; response = milter_data(e, &state); switch (state) { case SMFIR_REPLYCODE: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: data, reject=%s", response); milteraccept = false; #if _FFR_MILTER_ENHSC if (ISSMTPCODE(response)) (void) extenhsc(response + 4, ' ', e->e_enhsc); #endif /* _FFR_MILTER_ENHSC */ usrerr(response); if (strncmp(response, "421 ", 4) == 0 || strncmp(response, "421-", 4) == 0) rv = false; break; case SMFIR_REJECT: milteraccept = false; if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: data, reject=554 5.7.1 Command rejected"); usrerr("554 5.7.1 Command rejected"); break; case SMFIR_DISCARD: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: data, discard"); milteraccept = false; e->e_flags |= EF_DISCARD; break; case SMFIR_TEMPFAIL: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: data, reject=%s", MSG_TEMPFAIL); milteraccept = false; #if _FFR_MILTER_ENHSC (void) extenhsc(MSG_TEMPFAIL + 4, ' ', e->e_enhsc); #endif /* _FFR_MILTER_ENHSC */ usrerr(MSG_TEMPFAIL); break; case SMFIR_SHUTDOWN: if (MilterLogLevel > 3) sm_syslog(LOG_INFO, e->e_id, "Milter: data, reject=421 4.7.0 %s closing connection", MyHostName); milteraccept = false; usrerr("421 4.7.0 %s closing connection", MyHostName); rv = false; break; } if (response != NULL) sm_free(response); } /* Milter may have changed message size */ (void) sm_snprintf(buf, sizeof(buf), "%ld", PRT_NONNEGL(e->e_msgsize)); macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf); /* abort message filters that didn't get the body & log msg is OK */ if (smtp->sm_milterlist && smtp->sm_milterize) { milter_abort(e); if (milteraccept && MilterLogLevel > 9) sm_syslog(LOG_INFO, e->e_id, "Milter accept: message"); } /* ** If SuperSafe is SAFE_REALLY_POSTMILTER, and we don't have milter or ** milter accepted message, sync it now ** ** XXX This is almost a copy of the code in collect(): put it into ** a function that is called from both places? */ if (milteraccept && SuperSafe == SAFE_REALLY_POSTMILTER) { int afd; SM_FILE_T *volatile df; char *dfname; df = e->e_dfp; dfname = queuename(e, DATAFL_LETTER); if (sm_io_setinfo(df, SM_BF_COMMIT, NULL) < 0 && errno != EINVAL) { int save_errno; save_errno = errno; if (save_errno == EEXIST) { struct stat st; int dfd; if (stat(dfname, &st) < 0) st.st_size = -1; errno = EEXIST; syserr("@collect: bfcommit(%s): already on disk, size=%ld", dfname, (long) st.st_size); dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL); if (dfd >= 0) dumpfd(dfd, true, true); } errno = save_errno; dferror(df, "bfcommit", e); flush_errors(true); finis(save_errno != EEXIST, true, ExitStat); } else if ((afd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL)) < 0) { dferror(df, "sm_io_getinfo", e); flush_errors(true); finis(true, true, ExitStat); /* NOTREACHED */ } else if (fsync(afd) < 0) { dferror(df, "fsync", e); flush_errors(true); finis(true, true, ExitStat); /* NOTREACHED */ } else if (sm_io_close(df, SM_TIME_DEFAULT) < 0) { dferror(df, "sm_io_close", e); flush_errors(true); finis(true, true, ExitStat); /* NOTREACHED */ } /* Now reopen the df file */ e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname, SM_IO_RDONLY, NULL); if (e->e_dfp == NULL) { /* we haven't acked receipt yet, so just chuck this */ syserr("@Cannot reopen %s", dfname); finis(true, true, ExitStat); /* NOTREACHED */ } } #endif /* MILTER */ /* Check if quarantining stats should be updated */ if (e->e_quarmsg != NULL) markstats(e, NULL, STATS_QUARANTINE); /* ** If a header/body check (header checks or milter) ** set EF_DISCARD, don't queueup the message -- ** that would lose the EF_DISCARD bit and deliver ** the message. */ if (bitset(EF_DISCARD, e->e_flags)) doublequeue = false; aborting = Errors > 0; if (!(aborting || bitset(EF_DISCARD, e->e_flags)) && (QueueMode == QM_QUARANTINE || e->e_quarmsg == NULL) && !split_by_recipient(e)) aborting = bitset(EF_FATALERRS, e->e_flags); if (aborting) { ADDRESS *q; /* Log who the mail would have gone to */ logundelrcpts(e, e->e_message, 8, false); /* ** If something above refused the message, we still haven't ** accepted responsibility for it. Don't send DSNs. */ for (q = e->e_sendqueue; q != NULL; q = q->q_next) q->q_flags &= ~Q_PINGFLAGS; flush_errors(true); buffer_errors(); goto abortmessage; } /* from now on, we have to operate silently */ buffer_errors(); #if 0 /* ** Clear message, it may contain an error from the SMTP dialogue. ** This error must not show up in the queue. ** Some error message should show up, e.g., alias database ** not available, but others shouldn't, e.g., from check_rcpt. */ e->e_message = NULL; #endif /* 0 */ /* ** Arrange to send to everyone. ** If sending to multiple people, mail back ** errors rather than reporting directly. ** In any case, don't mail back errors for ** anything that has happened up to ** now (the other end will do this). ** Truncate our transcript -- the mail has gotten ** to us successfully, and if we have ** to mail this back, it will be easier ** on the reader. ** Then send to everyone. ** Finally give a reply code. If an error has ** already been given, don't mail a ** message back. ** We goose error returns by clearing error bit. */ SmtpPhase = "delivery"; (void) sm_io_setinfo(e->e_xfp, SM_BF_TRUNCATE, NULL); id = e->e_id; #if NAMED_BIND _res.retry = TimeOuts.res_retry[RES_TO_FIRST]; _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST]; #endif /* NAMED_BIND */ for (ee = e; ee != NULL; ee = ee->e_sibling) { /* make sure we actually do delivery */ ee->e_flags &= ~EF_CLRQUEUE; /* from now on, operate silently */ ee->e_errormode = EM_MAIL; if (doublequeue) { /* make sure it is in the queue */ queueup(ee, false, true); } else { int mode; /* send to all recipients */ mode = SM_DEFAULT; #if _FFR_DM_ONE if (SM_DM_ONE == e->e_sendmode) { if (NotFirstDelivery) { mode = SM_QUEUE; e->e_sendmode = SM_QUEUE; } else { mode = SM_FORK; NotFirstDelivery = true; } } #endif /* _FFR_DM_ONE */ sendall(ee, mode); } ee->e_to = NULL; } /* put back id for SMTP logging in putoutmsg() */ oldid = CurEnv->e_id; CurEnv->e_id = id; /* issue success message */ #if _FFR_MSG_ACCEPT if (MessageAccept != NULL && *MessageAccept != '\0') { char msg[MAXLINE]; expand(MessageAccept, msg, sizeof(msg), e); message("250 2.0.0 %s", msg); } else #endif /* _FFR_MSG_ACCEPT */ message("250 2.0.0 %s Message accepted for delivery", id); CurEnv->e_id = oldid; /* if we just queued, poke it */ if (doublequeue) { bool anything_to_send = false; sm_getla(); for (ee = e; ee != NULL; ee = ee->e_sibling) { if (WILL_BE_QUEUED(ee->e_sendmode)) continue; if (shouldqueue(ee->e_msgpriority, ee->e_ctime)) { ee->e_sendmode = SM_QUEUE; continue; } else if (QueueMode != QM_QUARANTINE && ee->e_quarmsg != NULL) { ee->e_sendmode = SM_QUEUE; continue; } anything_to_send = true; /* close all the queue files */ closexscript(ee); if (ee->e_dfp != NULL) { (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT); ee->e_dfp = NULL; } unlockqueue(ee); } if (anything_to_send) { #if PIPELINING /* ** XXX if we don't do this, we get 250 twice ** because it is also flushed in the child. */ (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT); #endif /* PIPELINING */ (void) doworklist(e, true, true); } } abortmessage: if (tTd(92, 2)) sm_dprintf("abortmessage: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n", e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel); if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags)) logsender(e, NULL); e->e_flags &= ~EF_LOGSENDER; /* clean up a bit */ smtp->sm_gotmail = false; /* ** Call dropenvelope if and only if the envelope is *not* ** being processed by the child process forked by doworklist(). */ if (aborting || bitset(EF_DISCARD, e->e_flags)) (void) dropenvelope(e, true, false); else { for (ee = e; ee != NULL; ee = ee->e_sibling) { if (!doublequeue && QueueMode != QM_QUARANTINE && ee->e_quarmsg != NULL) { (void) dropenvelope(ee, true, false); continue; } if (WILL_BE_QUEUED(ee->e_sendmode)) (void) dropenvelope(ee, true, false); } } CurEnv = e; features = e->e_features; sm_rpool_free(e->e_rpool); newenvelope(e, e, sm_rpool_new_x(NULL)); e->e_flags = BlankEnvelope.e_flags; e->e_features = features; /* restore connection quarantining */ if (smtp->sm_quarmsg == NULL) { e->e_quarmsg = NULL; macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), ""); } else { e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, smtp->sm_quarmsg); macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), e->e_quarmsg); } return rv; } /* ** LOGUNDELRCPTS -- log undelivered (or all) recipients. ** ** Parameters: ** e -- envelope. ** msg -- message for Stat= ** level -- log level. ** all -- log all recipients. ** ** Returns: ** none. ** ** Side Effects: ** logs undelivered (or all) recipients */ void logundelrcpts(e, msg, level, all) ENVELOPE *e; char *msg; int level; bool all; { ADDRESS *a; if (LogLevel <= level || msg == NULL || *msg == '\0') return; /* Clear $h so relay= doesn't get mislogged by logdelivery() */ macdefine(&e->e_macro, A_PERM, 'h', NULL); /* Log who the mail would have gone to */ for (a = e->e_sendqueue; a != NULL; a = a->q_next) { if (!QS_IS_UNDELIVERED(a->q_state) && !all) continue; e->e_to = a->q_paddr; logdelivery(NULL, NULL, #if _FFR_MILTER_ENHSC (a->q_status == NULL && e->e_enhsc[0] != '\0') ? e->e_enhsc : #endif /* _FFR_MILTER_ENHSC */ a->q_status, msg, NULL, (time_t) 0, e); } e->e_to = NULL; } /* ** CHECKSMTPATTACK -- check for denial-of-service attack by repetition ** ** Parameters: ** pcounter -- pointer to a counter for this command. ** maxcount -- maximum value for this counter before we ** slow down. ** waitnow -- sleep now (in this routine)? ** cname -- command name for logging. ** e -- the current envelope. ** ** Returns: ** time to wait, ** STOP_ATTACK if twice as many commands as allowed and ** MaxChildren > 0. ** ** Side Effects: ** Slows down if we seem to be under attack. */ static time_t checksmtpattack(pcounter, maxcount, waitnow, cname, e) volatile unsigned int *pcounter; unsigned int maxcount; bool waitnow; char *cname; ENVELOPE *e; { if (maxcount <= 0) /* no limit */ return (time_t) 0; if (++(*pcounter) >= maxcount) { unsigned int shift; time_t s; if (*pcounter == maxcount && LogLevel > 5) { sm_syslog(LOG_INFO, e->e_id, "%s: possible SMTP attack: command=%.40s, count=%u", CurSmtpClient, cname, *pcounter); } shift = *pcounter - maxcount; s = 1 << shift; if (shift > MAXSHIFT || s >= MAXTIMEOUT || s <= 0) s = MAXTIMEOUT; #define IS_ATTACK(s) ((MaxChildren > 0 && *pcounter >= maxcount * 2) \ ? STOP_ATTACK : (time_t) s) /* sleep at least 1 second before returning */ (void) sleep(*pcounter / maxcount); s -= *pcounter / maxcount; if (s >= MAXTIMEOUT || s < 0) s = MAXTIMEOUT; if (waitnow && s > 0) { (void) sleep(s); return IS_ATTACK(0); } return IS_ATTACK(s); } return (time_t) 0; } /* ** SETUP_SMTPD_IO -- setup I/O fd correctly for the SMTP server ** ** Parameters: ** none. ** ** Returns: ** nothing. ** ** Side Effects: ** may change I/O fd. */ static void setup_smtpd_io() { int inchfd, outchfd, outfd; inchfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL); outchfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL); outfd = sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL); if (outchfd != outfd) { /* arrange for debugging output to go to remote host */ (void) dup2(outchfd, outfd); } /* ** if InChannel and OutChannel are stdin/stdout ** and connected to ttys ** and fcntl(STDIN, F_SETFL, O_NONBLOCKING) also changes STDOUT, ** then "chain" them together. */ if (inchfd == STDIN_FILENO && outchfd == STDOUT_FILENO && isatty(inchfd) && isatty(outchfd)) { int inmode, outmode; inmode = fcntl(inchfd, F_GETFL, 0); if (inmode == -1) { if (LogLevel > 11) sm_syslog(LOG_INFO, NOQID, "fcntl(inchfd, F_GETFL) failed: %s", sm_errstring(errno)); return; } outmode = fcntl(outchfd, F_GETFL, 0); if (outmode == -1) { if (LogLevel > 11) sm_syslog(LOG_INFO, NOQID, "fcntl(outchfd, F_GETFL) failed: %s", sm_errstring(errno)); return; } if (bitset(O_NONBLOCK, inmode) || bitset(O_NONBLOCK, outmode) || fcntl(inchfd, F_SETFL, inmode | O_NONBLOCK) == -1) return; outmode = fcntl(outchfd, F_GETFL, 0); if (outmode != -1 && bitset(O_NONBLOCK, outmode)) { /* changing InChannel also changes OutChannel */ sm_io_automode(OutChannel, InChannel); if (tTd(97, 4) && LogLevel > 9) sm_syslog(LOG_INFO, NOQID, "set automode for I (%d)/O (%d) in SMTP server", inchfd, outchfd); } /* undo change of inchfd */ (void) fcntl(inchfd, F_SETFL, inmode); } } /* ** SKIPWORD -- skip a fixed word. ** ** Parameters: ** p -- place to start looking. ** w -- word to skip. ** ** Returns: ** p following w. ** NULL on error. ** ** Side Effects: ** clobbers the p data area. */ static char * skipword(p, w) register char *volatile p; char *w; { register char *q; char *firstp = p; /* find beginning of word */ SKIP_SPACE(p); q = p; /* find end of word */ while (*p != '\0' && *p != ':' && !(isascii(*p) && isspace(*p))) p++; while (isascii(*p) && isspace(*p)) *p++ = '\0'; if (*p != ':') { syntax: usrerr("501 5.5.2 Syntax error in parameters scanning \"%s\"", shortenstring(firstp, MAXSHORTSTR)); return NULL; } *p++ = '\0'; SKIP_SPACE(p); if (*p == '\0') goto syntax; /* see if the input word matches desired word */ if (sm_strcasecmp(q, w)) goto syntax; return p; } /* ** RESET_MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line ** ** Parameters: ** e -- the envelope. ** ** Returns: ** none. */ void reset_mail_esmtp_args(e) ENVELOPE *e; { /* "size": no reset */ /* "body" */ SevenBitInput = SevenBitInput_Saved; e->e_bodytype = NULL; /* "envid" */ e->e_envid = NULL; macdefine(&e->e_macro, A_PERM, macid("{dsn_envid}"), NULL); /* "ret" */ e->e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN); macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), NULL); #if SASL /* "auth" */ macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"), NULL); e->e_auth_param = ""; # if _FFR_AUTH_PASSING macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{auth_author}"), NULL); # endif /* _FFR_AUTH_PASSING */ #endif /* SASL */ /* "by" */ e->e_deliver_by = 0; e->e_dlvr_flag = 0; } /* ** MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line ** ** Parameters: ** a -- address (unused, for compatibility with rcpt_esmtp_args) ** kp -- the parameter key. ** vp -- the value of that parameter. ** e -- the envelope. ** ** Returns: ** none. */ void mail_esmtp_args(a, kp, vp, e) ADDRESS *a; char *kp; char *vp; ENVELOPE *e; { if (sm_strcasecmp(kp, "size") == 0) { if (vp == NULL) { usrerr("501 5.5.2 SIZE requires a value"); /* NOTREACHED */ } macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), vp); errno = 0; e->e_msgsize = strtol(vp, (char **) NULL, 10); if (e->e_msgsize == LONG_MAX && errno == ERANGE) { usrerr("552 5.2.3 Message size exceeds maximum value"); /* NOTREACHED */ } if (e->e_msgsize < 0) { usrerr("552 5.2.3 Message size invalid"); /* NOTREACHED */ } } else if (sm_strcasecmp(kp, "body") == 0) { if (vp == NULL) { usrerr("501 5.5.2 BODY requires a value"); /* NOTREACHED */ } else if (sm_strcasecmp(vp, "8bitmime") == 0) { SevenBitInput = false; } else if (sm_strcasecmp(vp, "7bit") == 0) { SevenBitInput = true; } else { usrerr("501 5.5.4 Unknown BODY type %s", vp); /* NOTREACHED */ } e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, vp); } else if (sm_strcasecmp(kp, "envid") == 0) { if (!bitset(SRV_OFFER_DSN, e->e_features)) { usrerr("504 5.7.0 Sorry, ENVID not supported, we do not allow DSN"); /* NOTREACHED */ } if (vp == NULL) { usrerr("501 5.5.2 ENVID requires a value"); /* NOTREACHED */ } if (!xtextok(vp)) { usrerr("501 5.5.4 Syntax error in ENVID parameter value"); /* NOTREACHED */ } if (e->e_envid != NULL) { usrerr("501 5.5.0 Duplicate ENVID parameter"); /* NOTREACHED */ } e->e_envid = sm_rpool_strdup_x(e->e_rpool, vp); macdefine(&e->e_macro, A_PERM, macid("{dsn_envid}"), e->e_envid); } else if (sm_strcasecmp(kp, "ret") == 0) { if (!bitset(SRV_OFFER_DSN, e->e_features)) { usrerr("504 5.7.0 Sorry, RET not supported, we do not allow DSN"); /* NOTREACHED */ } if (vp == NULL) { usrerr("501 5.5.2 RET requires a value"); /* NOTREACHED */ } if (bitset(EF_RET_PARAM, e->e_flags)) { usrerr("501 5.5.0 Duplicate RET parameter"); /* NOTREACHED */ } e->e_flags |= EF_RET_PARAM; if (sm_strcasecmp(vp, "hdrs") == 0) e->e_flags |= EF_NO_BODY_RETN; else if (sm_strcasecmp(vp, "full") != 0) { usrerr("501 5.5.2 Bad argument \"%s\" to RET", vp); /* NOTREACHED */ } macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), vp); } #if SASL else if (sm_strcasecmp(kp, "auth") == 0) { int len; char *q; char *auth_param; /* the value of the AUTH=x */ bool saveQuickAbort = QuickAbort; bool saveSuprErrs = SuprErrs; bool saveExitStat = ExitStat; if (vp == NULL) { usrerr("501 5.5.2 AUTH= requires a value"); /* NOTREACHED */ } if (e->e_auth_param != NULL) { usrerr("501 5.5.0 Duplicate AUTH parameter"); /* NOTREACHED */ } if ((q = strchr(vp, ' ')) != NULL) len = q - vp + 1; else len = strlen(vp) + 1; auth_param = xalloc(len); (void) sm_strlcpy(auth_param, vp, len); if (!xtextok(auth_param)) { usrerr("501 5.5.4 Syntax error in AUTH parameter value"); /* just a warning? */ /* NOTREACHED */ } /* XXX define this always or only if trusted? */ macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"), auth_param); /* ** call Strust_auth to find out whether ** auth_param is acceptable (trusted) ** we shouldn't trust it if not authenticated ** (required by RFC, leave it to ruleset?) */ SuprErrs = true; QuickAbort = false; if (strcmp(auth_param, "<>") != 0 && (rscheck("trust_auth", auth_param, NULL, e, RSF_RMCOMM, 9, NULL, NOQID, NULL) != EX_OK || Errors > 0)) { if (tTd(95, 8)) { q = e->e_auth_param; sm_dprintf("auth=\"%.100s\" not trusted user=\"%.100s\"\n", auth_param, (q == NULL) ? "" : q); } /* not trusted */ e->e_auth_param = "<>"; # if _FFR_AUTH_PASSING macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{auth_author}"), NULL); # endif /* _FFR_AUTH_PASSING */ } else { if (tTd(95, 8)) sm_dprintf("auth=\"%.100s\" trusted\n", auth_param); e->e_auth_param = sm_rpool_strdup_x(e->e_rpool, auth_param); } sm_free(auth_param); /* XXX */ /* reset values */ Errors = 0; QuickAbort = saveQuickAbort; SuprErrs = saveSuprErrs; ExitStat = saveExitStat; } #endif /* SASL */ #define PRTCHAR(c) ((isascii(c) && isprint(c)) ? (c) : '?') /* ** "by" is only accepted if DeliverByMin >= 0. ** We maybe could add this to the list of server_features. */ else if (sm_strcasecmp(kp, "by") == 0 && DeliverByMin >= 0) { char *s; if (vp == NULL) { usrerr("501 5.5.2 BY= requires a value"); /* NOTREACHED */ } errno = 0; e->e_deliver_by = strtol(vp, &s, 10); if (e->e_deliver_by == LONG_MIN || e->e_deliver_by == LONG_MAX || e->e_deliver_by > 999999999l || e->e_deliver_by < -999999999l) { usrerr("501 5.5.2 BY=%s out of range", vp); /* NOTREACHED */ } if (s == NULL || *s != ';') { usrerr("501 5.5.2 BY= missing ';'"); /* NOTREACHED */ } e->e_dlvr_flag = 0; ++s; /* XXX: spaces allowed? */ SKIP_SPACE(s); switch (tolower(*s)) { case 'n': e->e_dlvr_flag = DLVR_NOTIFY; break; case 'r': e->e_dlvr_flag = DLVR_RETURN; if (e->e_deliver_by <= 0) { usrerr("501 5.5.4 mode R requires BY time > 0"); /* NOTREACHED */ } if (DeliverByMin > 0 && e->e_deliver_by > 0 && e->e_deliver_by < DeliverByMin) { usrerr("555 5.5.2 time %ld less than %ld", e->e_deliver_by, (long) DeliverByMin); /* NOTREACHED */ } break; default: usrerr("501 5.5.2 illegal by-mode '%c'", PRTCHAR(*s)); /* NOTREACHED */ } ++s; /* XXX: spaces allowed? */ SKIP_SPACE(s); switch (tolower(*s)) { case 't': e->e_dlvr_flag |= DLVR_TRACE; break; case '\0': break; default: usrerr("501 5.5.2 illegal by-trace '%c'", PRTCHAR(*s)); /* NOTREACHED */ } /* XXX: check whether more characters follow? */ } else { usrerr("555 5.5.4 %s parameter unrecognized", kp); /* NOTREACHED */ } } /* ** RCPT_ESMTP_ARGS -- process ESMTP arguments from RCPT line ** ** Parameters: ** a -- the address corresponding to the To: parameter. ** kp -- the parameter key. ** vp -- the value of that parameter. ** e -- the envelope. ** ** Returns: ** none. */ void rcpt_esmtp_args(a, kp, vp, e) ADDRESS *a; char *kp; char *vp; ENVELOPE *e; { if (sm_strcasecmp(kp, "notify") == 0) { char *p; if (!bitset(SRV_OFFER_DSN, e->e_features)) { usrerr("504 5.7.0 Sorry, NOTIFY not supported, we do not allow DSN"); /* NOTREACHED */ } if (vp == NULL) { usrerr("501 5.5.2 NOTIFY requires a value"); /* NOTREACHED */ } a->q_flags &= ~(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY); a->q_flags |= QHASNOTIFY; macdefine(&e->e_macro, A_TEMP, macid("{dsn_notify}"), vp); if (sm_strcasecmp(vp, "never") == 0) return; for (p = vp; p != NULL; vp = p) { char *s; s = p = strchr(p, ','); if (p != NULL) *p++ = '\0'; if (sm_strcasecmp(vp, "success") == 0) a->q_flags |= QPINGONSUCCESS; else if (sm_strcasecmp(vp, "failure") == 0) a->q_flags |= QPINGONFAILURE; else if (sm_strcasecmp(vp, "delay") == 0) a->q_flags |= QPINGONDELAY; else { usrerr("501 5.5.4 Bad argument \"%s\" to NOTIFY", vp); /* NOTREACHED */ } if (s != NULL) *s = ','; } } else if (sm_strcasecmp(kp, "orcpt") == 0) { + char *p; + if (!bitset(SRV_OFFER_DSN, e->e_features)) { usrerr("504 5.7.0 Sorry, ORCPT not supported, we do not allow DSN"); /* NOTREACHED */ } if (vp == NULL) { usrerr("501 5.5.2 ORCPT requires a value"); /* NOTREACHED */ } - if (strchr(vp, ';') == NULL || !xtextok(vp)) + if (a->q_orcpt != NULL) { + usrerr("501 5.5.0 Duplicate ORCPT parameter"); + /* NOTREACHED */ + } + p = strchr(vp, ';'); + if (p == NULL) + { usrerr("501 5.5.4 Syntax error in ORCPT parameter value"); /* NOTREACHED */ } - if (a->q_orcpt != NULL) + *p = '\0'; + if (!isatom(vp) || !xtextok(p + 1)) { - usrerr("501 5.5.0 Duplicate ORCPT parameter"); + *p = ';'; + usrerr("501 5.5.4 Syntax error in ORCPT parameter value"); /* NOTREACHED */ } + *p = ';'; a->q_orcpt = sm_rpool_strdup_x(e->e_rpool, vp); } else { usrerr("555 5.5.4 %s parameter unrecognized", kp); /* NOTREACHED */ } } /* ** PRINTVRFYADDR -- print an entry in the verify queue ** ** Parameters: ** a -- the address to print. ** last -- set if this is the last one. ** vrfy -- set if this is a VRFY command. ** ** Returns: ** none. ** ** Side Effects: ** Prints the appropriate 250 codes. */ #define OFFF (3 + 1 + 5 + 1) /* offset in fmt: SMTP reply + enh. code */ static void printvrfyaddr(a, last, vrfy) register ADDRESS *a; bool last; bool vrfy; { char fmtbuf[30]; if (vrfy && a->q_mailer != NULL && !bitnset(M_VRFY250, a->q_mailer->m_flags)) (void) sm_strlcpy(fmtbuf, "252", sizeof(fmtbuf)); else (void) sm_strlcpy(fmtbuf, "250", sizeof(fmtbuf)); fmtbuf[3] = last ? ' ' : '-'; (void) sm_strlcpy(&fmtbuf[4], "2.1.5 ", sizeof(fmtbuf) - 4); if (a->q_fullname == NULL) { if ((a->q_mailer == NULL || a->q_mailer->m_addrtype == NULL || sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) && strchr(a->q_user, '@') == NULL) (void) sm_strlcpy(&fmtbuf[OFFF], "<%s@%s>", sizeof(fmtbuf) - OFFF); else (void) sm_strlcpy(&fmtbuf[OFFF], "<%s>", sizeof(fmtbuf) - OFFF); message(fmtbuf, a->q_user, MyHostName); } else { if ((a->q_mailer == NULL || a->q_mailer->m_addrtype == NULL || sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) && strchr(a->q_user, '@') == NULL) (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s@%s>", sizeof(fmtbuf) - OFFF); else (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s>", sizeof(fmtbuf) - OFFF); message(fmtbuf, a->q_fullname, a->q_user, MyHostName); } } #if SASL /* ** SASLMECHS -- get list of possible AUTH mechanisms ** ** Parameters: ** conn -- SASL connection info. ** mechlist -- output parameter for list of mechanisms. ** ** Returns: ** number of mechs. */ static int saslmechs(conn, mechlist) sasl_conn_t *conn; char **mechlist; { int len, num, result; /* "user" is currently unused */ # if SASL >= 20000 result = sasl_listmech(conn, NULL, "", " ", "", (const char **) mechlist, (unsigned int *)&len, &num); # else /* SASL >= 20000 */ result = sasl_listmech(conn, "user", /* XXX */ "", " ", "", mechlist, (unsigned int *)&len, (unsigned int *)&num); # endif /* SASL >= 20000 */ if (result != SASL_OK) { if (LogLevel > 9) sm_syslog(LOG_WARNING, NOQID, "AUTH error: listmech=%d, num=%d", result, num); num = 0; } if (num > 0) { if (LogLevel > 11) sm_syslog(LOG_INFO, NOQID, "AUTH: available mech=%s, allowed mech=%s", *mechlist, AuthMechanisms); *mechlist = intersect(AuthMechanisms, *mechlist, NULL); } else { *mechlist = NULL; /* be paranoid... */ if (result == SASL_OK && LogLevel > 9) sm_syslog(LOG_WARNING, NOQID, "AUTH warning: no mechanisms"); } return num; } # if SASL >= 20000 /* ** PROXY_POLICY -- define proxy policy for AUTH ** ** Parameters: ** conn -- unused. ** context -- unused. ** requested_user -- authorization identity. ** rlen -- authorization identity length. ** auth_identity -- authentication identity. ** alen -- authentication identity length. ** def_realm -- default user realm. ** urlen -- user realm length. ** propctx -- unused. ** ** Returns: ** ok? ** ** Side Effects: ** sets {auth_authen} macro. */ int proxy_policy(conn, context, requested_user, rlen, auth_identity, alen, def_realm, urlen, propctx) sasl_conn_t *conn; void *context; const char *requested_user; unsigned rlen; const char *auth_identity; unsigned alen; const char *def_realm; unsigned urlen; struct propctx *propctx; { if (auth_identity == NULL) return SASL_FAIL; macdefine(&BlankEnvelope.e_macro, A_TEMP, macid("{auth_authen}"), xtextify((char *) auth_identity, "=<>\")")); return SASL_OK; } # else /* SASL >= 20000 */ /* ** PROXY_POLICY -- define proxy policy for AUTH ** ** Parameters: ** context -- unused. ** auth_identity -- authentication identity. ** requested_user -- authorization identity. ** user -- allowed user (output). ** errstr -- possible error string (output). ** ** Returns: ** ok? */ int proxy_policy(context, auth_identity, requested_user, user, errstr) void *context; const char *auth_identity; const char *requested_user; const char **user; const char **errstr; { if (user == NULL || auth_identity == NULL) return SASL_FAIL; *user = newstr(auth_identity); return SASL_OK; } # endif /* SASL >= 20000 */ #endif /* SASL */ #if STARTTLS /* ** INITSRVTLS -- initialize server side TLS ** ** Parameters: ** tls_ok -- should tls initialization be done? ** ** Returns: ** succeeded? ** ** Side Effects: ** sets tls_ok_srv which is a static variable in this module. ** Do NOT remove assignments to it! */ bool initsrvtls(tls_ok) bool tls_ok; { if (!tls_ok) return false; /* do NOT remove assignment */ tls_ok_srv = inittls(&srv_ctx, TLS_Srv_Opts, Srv_SSL_Options, true, SrvCertFile, SrvKeyFile, CACertPath, CACertFile, DHParams); return tls_ok_srv; } #endif /* STARTTLS */ /* ** SRVFEATURES -- get features for SMTP server ** ** Parameters: ** e -- envelope (should be session context). ** clientname -- name of client. ** features -- default features for this invocation. ** ** Returns: ** server features. */ /* table with options: it uses just one character, how about strings? */ static struct { char srvf_opt; unsigned int srvf_flag; } srv_feat_table[] = { { 'A', SRV_OFFER_AUTH }, { 'B', SRV_OFFER_VERB }, { 'C', SRV_REQ_SEC }, { 'D', SRV_OFFER_DSN }, { 'E', SRV_OFFER_ETRN }, { 'L', SRV_REQ_AUTH }, #if PIPELINING # if _FFR_NO_PIPE { 'N', SRV_NO_PIPE }, # endif /* _FFR_NO_PIPE */ { 'P', SRV_OFFER_PIPE }, #endif /* PIPELINING */ { 'R', SRV_VRFY_CLT }, /* same as V; not documented */ { 'S', SRV_OFFER_TLS }, /* { 'T', SRV_TMP_FAIL }, */ { 'V', SRV_VRFY_CLT }, { 'X', SRV_OFFER_EXPN }, /* { 'Y', SRV_OFFER_VRFY }, */ { '\0', SRV_NONE } }; static unsigned int srvfeatures(e, clientname, features) ENVELOPE *e; char *clientname; unsigned int features; { int r, i, j; char **pvp, c, opt; char pvpbuf[PSBUFSIZE]; pvp = NULL; r = rscap("srv_features", clientname, "", e, &pvp, pvpbuf, sizeof(pvpbuf)); if (r != EX_OK) return features; if (pvp == NULL || pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET) return features; if (pvp[1] != NULL && sm_strncasecmp(pvp[1], "temp", 4) == 0) return SRV_TMP_FAIL; /* ** General rule (see sendmail.h, d_flags): ** lower case: required/offered, upper case: Not required/available ** ** Since we can change some features per daemon, we have both ** cases here: turn on/off a feature. */ for (i = 1; pvp[i] != NULL; i++) { c = pvp[i][0]; j = 0; for (;;) { if ((opt = srv_feat_table[j].srvf_opt) == '\0') { if (LogLevel > 9) sm_syslog(LOG_WARNING, e->e_id, "srvfeatures: unknown feature %s", pvp[i]); break; } if (c == opt) { features &= ~(srv_feat_table[j].srvf_flag); break; } if (c == tolower(opt)) { features |= srv_feat_table[j].srvf_flag; break; } ++j; } } return features; } /* ** HELP -- implement the HELP command. ** ** Parameters: ** topic -- the topic we want help for. ** e -- envelope. ** ** Returns: ** none. ** ** Side Effects: ** outputs the help file to message output. */ #define HELPVSTR "#vers " #define HELPVERSION 2 void help(topic, e) char *topic; ENVELOPE *e; { register SM_FILE_T *hf; register char *p; int len; bool noinfo; bool first = true; long sff = SFF_OPENASROOT|SFF_REGONLY; char buf[MAXLINE]; char inp[MAXLINE]; static int foundvers = -1; extern char Version[]; if (DontLockReadFiles) sff |= SFF_NOLOCK; if (!bitnset(DBS_HELPFILEINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_SAFEDIRPATH; if (HelpFile == NULL || (hf = safefopen(HelpFile, O_RDONLY, 0444, sff)) == NULL) { /* no help */ errno = 0; message("502 5.3.0 Sendmail %s -- HELP not implemented", Version); return; } if (topic == NULL || *topic == '\0') { topic = "smtp"; noinfo = false; } else { makelower(topic); noinfo = true; } len = strlen(topic); - while (sm_io_fgets(hf, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + while (sm_io_fgets(hf, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { if (buf[0] == '#') { if (foundvers < 0 && strncmp(buf, HELPVSTR, strlen(HELPVSTR)) == 0) { int h; if (sm_io_sscanf(buf + strlen(HELPVSTR), "%d", &h) == 1) foundvers = h; } continue; } if (strncmp(buf, topic, len) == 0) { if (first) { first = false; /* print version if no/old vers# in file */ if (foundvers < 2 && !noinfo) message("214-2.0.0 This is Sendmail version %s", Version); } p = strpbrk(buf, " \t"); if (p == NULL) p = buf + strlen(buf) - 1; else p++; fixcrlf(p, true); if (foundvers >= 2) { char *lbp; int lbs = sizeof(buf) - (p - buf); lbp = translate_dollars(p, p, &lbs); expand(lbp, inp, sizeof(inp), e); if (p != lbp) sm_free(lbp); p = inp; } message("214-2.0.0 %s", p); noinfo = false; } } if (noinfo) message("504 5.3.0 HELP topic \"%.10s\" unknown", topic); else message("214 2.0.0 End of HELP info"); if (foundvers != 0 && foundvers < HELPVERSION) { if (LogLevel > 1) sm_syslog(LOG_WARNING, e->e_id, "%s too old (require version %d)", HelpFile, HELPVERSION); /* avoid log next time */ foundvers = 0; } (void) sm_io_close(hf, SM_TIME_DEFAULT); } #if SASL /* ** RESET_SASLCONN -- reset SASL connection data ** ** Parameters: ** conn -- SASL connection context ** hostname -- host name ** various connection data ** ** Returns: ** SASL result */ static int reset_saslconn(sasl_conn_t **conn, char *hostname, # if SASL >= 20000 char *remoteip, char *localip, char *auth_id, sasl_ssf_t * ext_ssf) # else /* SASL >= 20000 */ struct sockaddr_in *saddr_r, struct sockaddr_in *saddr_l, sasl_external_properties_t * ext_ssf) # endif /* SASL >= 20000 */ { int result; sasl_dispose(conn); # if SASL >= 20000 result = sasl_server_new("smtp", hostname, NULL, NULL, NULL, NULL, 0, conn); # elif SASL > 10505 /* use empty realm: only works in SASL > 1.5.5 */ result = sasl_server_new("smtp", hostname, "", NULL, 0, conn); # else /* SASL >= 20000 */ /* use no realm -> realm is set to hostname by SASL lib */ result = sasl_server_new("smtp", hostname, NULL, NULL, 0, conn); # endif /* SASL >= 20000 */ if (result != SASL_OK) return result; # if SASL >= 20000 # if NETINET || NETINET6 if (remoteip != NULL && *remoteip != '\0') result = sasl_setprop(*conn, SASL_IPREMOTEPORT, remoteip); if (result != SASL_OK) return result; if (localip != NULL && *localip != '\0') result = sasl_setprop(*conn, SASL_IPLOCALPORT, localip); if (result != SASL_OK) return result; # endif /* NETINET || NETINET6 */ result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf); if (result != SASL_OK) return result; result = sasl_setprop(*conn, SASL_AUTH_EXTERNAL, auth_id); if (result != SASL_OK) return result; # else /* SASL >= 20000 */ # if NETINET if (saddr_r != NULL) result = sasl_setprop(*conn, SASL_IP_REMOTE, saddr_r); if (result != SASL_OK) return result; if (saddr_l != NULL) result = sasl_setprop(*conn, SASL_IP_LOCAL, saddr_l); if (result != SASL_OK) return result; # endif /* NETINET */ result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf); if (result != SASL_OK) return result; # endif /* SASL >= 20000 */ return SASL_OK; } #endif /* SASL */ Index: head/contrib/sendmail/src/tls.c =================================================================== --- head/contrib/sendmail/src/tls.c (revision 249728) +++ head/contrib/sendmail/src/tls.c (revision 249729) @@ -1,1721 +1,1749 @@ /* - * Copyright (c) 2000-2006, 2008, 2009, 2011 Sendmail, Inc. and its suppliers. + * Copyright (c) 2000-2006, 2008, 2009, 2011, 2013 Sendmail, Inc. and its suppliers. * All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: tls.c,v 8.118 2011/03/07 23:20:47 ca Exp $") +SM_RCSID("@(#)$Id: tls.c,v 8.121 2013/01/02 23:54:17 ca Exp $") #if STARTTLS # include # include # include # ifndef HASURANDOMDEV # include # endif /* ! HASURANDOMDEV */ # if !TLS_NO_RSA static RSA *rsa_tmp = NULL; /* temporary RSA key */ static RSA *tmp_rsa_key __P((SSL *, int, int)); # endif /* !TLS_NO_RSA */ # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L static int tls_verify_cb __P((X509_STORE_CTX *)); # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */ static int tls_verify_cb __P((X509_STORE_CTX *, void *)); # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */ # if OPENSSL_VERSION_NUMBER > 0x00907000L static int x509_verify_cb __P((int, X509_STORE_CTX *)); # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L # define CONST097 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */ # define CONST097 const # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */ static void apps_ssl_info_cb __P((CONST097 SSL *, int , int)); static bool tls_ok_f __P((char *, char *, int)); static bool tls_safe_f __P((char *, long, bool)); static int tls_verify_log __P((int, X509_STORE_CTX *, char *)); # if !NO_DH static DH *get_dh512 __P((void)); static unsigned char dh512_p[] = { 0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75, 0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F, 0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3, 0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12, 0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C, 0x47,0x74,0xE8,0x33 }; static unsigned char dh512_g[] = { 0x02 }; static DH * get_dh512() { DH *dh = NULL; if ((dh = DH_new()) == NULL) return NULL; dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL); dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL); if ((dh->p == NULL) || (dh->g == NULL)) return NULL; return dh; } # endif /* !NO_DH */ /* ** TLS_RAND_INIT -- initialize STARTTLS random generator ** ** Parameters: ** randfile -- name of file with random data ** logl -- loglevel ** ** Returns: ** success/failure ** ** Side Effects: ** initializes PRNG for tls library. */ # define MIN_RAND_BYTES 128 /* 1024 bits */ # define RF_OK 0 /* randfile OK */ # define RF_MISS 1 /* randfile == NULL || *randfile == '\0' */ # define RF_UNKNOWN 2 /* unknown prefix for randfile */ # define RI_NONE 0 /* no init yet */ # define RI_SUCCESS 1 /* init was successful */ # define RI_FAIL 2 /* init failed */ static bool tls_rand_init __P((char *, int)); static bool tls_rand_init(randfile, logl) char *randfile; int logl; { # ifndef HASURANDOMDEV /* not required if /dev/urandom exists, OpenSSL does it internally */ bool ok; int randdef; static int done = RI_NONE; /* ** initialize PRNG */ /* did we try this before? if yes: return old value */ if (done != RI_NONE) return done == RI_SUCCESS; /* set default values */ ok = false; done = RI_FAIL; randdef = (randfile == NULL || *randfile == '\0') ? RF_MISS : RF_OK; # if EGD if (randdef == RF_OK && sm_strncasecmp(randfile, "egd:", 4) == 0) { randfile += 4; if (RAND_egd(randfile) < 0) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS: RAND_egd(%s) failed: random number generator not seeded", randfile); } else ok = true; } else # endif /* EGD */ if (randdef == RF_OK && sm_strncasecmp(randfile, "file:", 5) == 0) { int fd; long sff; struct stat st; randfile += 5; sff = SFF_SAFEDIRPATH | SFF_NOWLINK | SFF_NOGWFILES | SFF_NOWWFILES | SFF_NOGRFILES | SFF_NOWRFILES | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT; if (DontLockReadFiles) sff |= SFF_NOLOCK; if ((fd = safeopen(randfile, O_RDONLY, 0, sff)) >= 0) { if (fstat(fd, &st) < 0) { if (LogLevel > logl) sm_syslog(LOG_ERR, NOQID, "STARTTLS: can't fstat(%s)", randfile); } else { bool use, problem; use = true; problem = false; /* max. age of file: 10 minutes */ if (st.st_mtime + 600 < curtime()) { use = bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail); problem = true; if (LogLevel > logl) sm_syslog(LOG_ERR, NOQID, "STARTTLS: RandFile %s too old: %s", randfile, use ? "unsafe" : "unusable"); } if (use && st.st_size < MIN_RAND_BYTES) { use = bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail); problem = true; if (LogLevel > logl) sm_syslog(LOG_ERR, NOQID, "STARTTLS: size(%s) < %d: %s", randfile, MIN_RAND_BYTES, use ? "unsafe" : "unusable"); } if (use) ok = RAND_load_file(randfile, -1) >= MIN_RAND_BYTES; if (use && !ok) { if (LogLevel > logl) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: RAND_load_file(%s) failed: random number generator not seeded", randfile); } if (problem) ok = false; } if (ok || bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail)) { /* add this even if fstat() failed */ RAND_seed((void *) &st, sizeof(st)); } (void) close(fd); } else { if (LogLevel > logl) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: Warning: safeopen(%s) failed", randfile); } } else if (randdef == RF_OK) { if (LogLevel > logl) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: Error: no proper random file definition %s", randfile); randdef = RF_UNKNOWN; } if (randdef == RF_MISS) { if (LogLevel > logl) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: Error: missing random file definition"); } if (!ok && bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail)) { int i; long r; unsigned char buf[MIN_RAND_BYTES]; /* assert((MIN_RAND_BYTES % sizeof(long)) == 0); */ for (i = 0; i <= sizeof(buf) - sizeof(long); i += sizeof(long)) { r = get_random(); (void) memcpy(buf + i, (void *) &r, sizeof(long)); } RAND_seed(buf, sizeof(buf)); if (LogLevel > logl) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: Warning: random number generator not properly seeded"); ok = true; } done = ok ? RI_SUCCESS : RI_FAIL; return ok; # else /* ! HASURANDOMDEV */ return true; # endif /* ! HASURANDOMDEV */ } /* ** INIT_TLS_LIBRARY -- Calls functions which setup TLS library for global use. ** ** Parameters: -** none. +** fipsmode -- use FIPS? ** ** Returns: ** succeeded? */ bool -init_tls_library() +init_tls_library(fipsmode) + bool fipsmode; { + bool bv; + /* basic TLS initialization, ignore result for now */ SSL_library_init(); SSL_load_error_strings(); # if 0 /* this is currently a macro for SSL_library_init */ SSLeay_add_ssl_algorithms(); # endif /* 0 */ - return tls_rand_init(RandFile, 7); + bv = tls_rand_init(RandFile, 7); +# if _FFR_FIPSMODE + if (bv && fipsmode) + { + if (!FIPS_mode_set(1)) + { + unsigned long err; + + err = ERR_get_error(); + if (LogLevel > 0) + sm_syslog(LOG_ERR, NOQID, + "STARTTLS=init, FIPSMode=%s", + ERR_error_string(err, NULL)); + return false; + } + else + { + if (LogLevel > 9) + sm_syslog(LOG_INFO, NOQID, + "STARTTLS=init, FIPSMode=ok"); + } + } +#endif /* _FFR_FIPSMODE */ + return bv; } /* ** TLS_SET_VERIFY -- request client certificate? ** ** Parameters: ** ctx -- TLS context ** ssl -- TLS structure ** vrfy -- require certificate? ** ** Returns: ** none. ** ** Side Effects: ** Sets verification state for TLS ** # if TLS_VRFY_PER_CTX ** Notice: ** This is per TLS context, not per TLS structure; ** the former is global, the latter per connection. ** It would be nice to do this per connection, but this ** doesn't work in the current TLS libraries :-( # endif * TLS_VRFY_PER_CTX * */ void tls_set_verify(ctx, ssl, vrfy) SSL_CTX *ctx; SSL *ssl; bool vrfy; { # if !TLS_VRFY_PER_CTX SSL_set_verify(ssl, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL); # else /* !TLS_VRFY_PER_CTX */ SSL_CTX_set_verify(ctx, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL); # endif /* !TLS_VRFY_PER_CTX */ } /* ** status in initialization ** these flags keep track of the status of the initialization ** i.e., whether a file exists (_EX) and whether it can be used (_OK) ** [due to permissions] */ # define TLS_S_NONE 0x00000000 /* none yet */ # define TLS_S_CERT_EX 0x00000001 /* cert file exists */ # define TLS_S_CERT_OK 0x00000002 /* cert file is ok */ # define TLS_S_KEY_EX 0x00000004 /* key file exists */ # define TLS_S_KEY_OK 0x00000008 /* key file is ok */ # define TLS_S_CERTP_EX 0x00000010 /* CA cert path exists */ # define TLS_S_CERTP_OK 0x00000020 /* CA cert path is ok */ # define TLS_S_CERTF_EX 0x00000040 /* CA cert file exists */ # define TLS_S_CERTF_OK 0x00000080 /* CA cert file is ok */ # define TLS_S_CRLF_EX 0x00000100 /* CRL file exists */ # define TLS_S_CRLF_OK 0x00000200 /* CRL file is ok */ # if _FFR_TLS_1 # define TLS_S_CERT2_EX 0x00001000 /* 2nd cert file exists */ # define TLS_S_CERT2_OK 0x00002000 /* 2nd cert file is ok */ # define TLS_S_KEY2_EX 0x00004000 /* 2nd key file exists */ # define TLS_S_KEY2_OK 0x00008000 /* 2nd key file is ok */ # endif /* _FFR_TLS_1 */ # define TLS_S_DH_OK 0x00200000 /* DH cert is ok */ # define TLS_S_DHPAR_EX 0x00400000 /* DH param file exists */ # define TLS_S_DHPAR_OK 0x00800000 /* DH param file is ok to use */ /* Type of variable */ # define TLS_T_OTHER 0 # define TLS_T_SRV 1 # define TLS_T_CLT 2 /* ** TLS_OK_F -- can var be an absolute filename? ** ** Parameters: ** var -- filename ** fn -- what is the filename used for? ** type -- type of variable ** ** Returns: ** ok? */ static bool tls_ok_f(var, fn, type) char *var; char *fn; int type; { /* must be absolute pathname */ if (var != NULL && *var == '/') return true; if (LogLevel > 12) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s%s missing", type == TLS_T_SRV ? "Server" : (type == TLS_T_CLT ? "Client" : ""), fn); return false; } /* ** TLS_SAFE_F -- is a file safe to use? ** ** Parameters: ** var -- filename ** sff -- flags for safefile() ** srv -- server side? ** ** Returns: ** ok? */ static bool tls_safe_f(var, sff, srv) char *var; long sff; bool srv; { int ret; if ((ret = safefile(var, RunAsUid, RunAsGid, RunAsUserName, sff, S_IRUSR, NULL)) == 0) return true; if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s: file %s unsafe: %s", srv ? "server" : "client", var, sm_errstring(ret)); return false; } /* ** TLS_OK_F -- macro to simplify calls to tls_ok_f ** ** Parameters: ** var -- filename ** fn -- what is the filename used for? ** req -- is the file required? ** st -- status bit to set if ok ** type -- type of variable ** ** Side Effects: ** uses r, ok; may change ok and status. ** */ # define TLS_OK_F(var, fn, req, st, type) if (ok) \ { \ r = tls_ok_f(var, fn, type); \ if (r) \ status |= st; \ else if (req) \ ok = false; \ } /* ** TLS_UNR -- macro to return whether a file should be unreadable ** ** Parameters: ** bit -- flag to test ** req -- flags ** ** Returns: ** 0/SFF_NORFILES */ # define TLS_UNR(bit, req) (bitset(bit, req) ? SFF_NORFILES : 0) # define TLS_OUNR(bit, req) (bitset(bit, req) ? SFF_NOWRFILES : 0) # define TLS_KEYSFF(req) \ (bitnset(DBS_GROUPREADABLEKEYFILE, DontBlameSendmail) ? \ TLS_OUNR(TLS_I_KEY_OUNR, req) : \ TLS_UNR(TLS_I_KEY_UNR, req)) /* ** TLS_SAFE_F -- macro to simplify calls to tls_safe_f ** ** Parameters: ** var -- filename ** sff -- flags for safefile() ** req -- is the file required? ** ex -- does the file exist? ** st -- status bit to set if ok ** srv -- server side? ** ** Side Effects: ** uses r, ok, ex; may change ok and status. ** */ # define TLS_SAFE_F(var, sff, req, ex, st, srv) if (ex && ok) \ { \ r = tls_safe_f(var, sff, srv); \ if (r) \ status |= st; \ else if (req) \ ok = false; \ } /* ** INITTLS -- initialize TLS ** ** Parameters: ** ctx -- pointer to context ** req -- requirements for initialization (see sendmail.h) ** options -- options ** srv -- server side? ** certfile -- filename of certificate ** keyfile -- filename of private key ** cacertpath -- path to CAs ** cacertfile -- file with CA(s) ** dhparam -- parameters for DH ** ** Returns: ** succeeded? */ /* ** The session_id_context identifies the service that created a session. ** This information is used to distinguish between multiple TLS-based ** servers running on the same server. We use the name of the mail system. ** Note: the session cache is not persistent. */ static char server_session_id_context[] = "sendmail8"; /* 0.9.8a and b have a problem with SSL_OP_TLS_BLOCK_PADDING_BUG */ #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG 1 #else # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG 0 #endif bool inittls(ctx, req, options, srv, certfile, keyfile, cacertpath, cacertfile, dhparam) SSL_CTX **ctx; unsigned long req; long options; bool srv; char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam; { # if !NO_DH static DH *dh = NULL; # endif /* !NO_DH */ int r; bool ok; long sff, status; char *who; # if _FFR_TLS_1 char *cf2, *kf2; # endif /* _FFR_TLS_1 */ # if SM_CONF_SHM extern int ShmId; # endif /* SM_CONF_SHM */ # if OPENSSL_VERSION_NUMBER > 0x00907000L BIO *crl_file; X509_CRL *crl; X509_STORE *store; # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG long rt_version; STACK_OF(SSL_COMP) *comp_methods; #endif status = TLS_S_NONE; who = srv ? "server" : "client"; if (ctx == NULL) { syserr("STARTTLS=%s, inittls: ctx == NULL", who); /* NOTREACHED */ SM_ASSERT(ctx != NULL); } /* already initialized? (we could re-init...) */ if (*ctx != NULL) return true; ok = true; # if _FFR_TLS_1 /* ** look for a second filename: it must be separated by a ',' ** no blanks allowed (they won't be skipped). ** we change a global variable here! this change will be undone ** before return from the function but only if it returns true. ** this isn't a problem since in a failure case this function ** won't be called again with the same (overwritten) values. ** otherwise each return must be replaced with a goto endinittls. */ cf2 = NULL; kf2 = NULL; if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL) { *cf2++ = '\0'; if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL) *kf2++ = '\0'; } # endif /* _FFR_TLS_1 */ /* ** Check whether files/paths are defined */ TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req), TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT); TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req), TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT); TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req), TLS_S_CERTP_EX, TLS_T_OTHER); TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req), TLS_S_CERTF_EX, TLS_T_OTHER); # if OPENSSL_VERSION_NUMBER > 0x00907000L TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req), TLS_S_CRLF_EX, TLS_T_OTHER); # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ # if _FFR_TLS_1 /* ** if the second file is specified it must exist ** XXX: it is possible here to define only one of those files */ if (cf2 != NULL) { TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req), TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT); } if (kf2 != NULL) { TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req), TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT); } # endif /* _FFR_TLS_1 */ /* ** valid values for dhparam are (only the first char is checked) ** none no parameters: don't use DH ** 512 generate 512 bit parameters (fixed) ** 1024 generate 1024 bit parameters ** /file/name read parameters from /file/name ** default is: 1024 for server, 512 for client (OK? XXX) */ if (bitset(TLS_I_TRY_DH, req)) { if (dhparam != NULL) { char c = *dhparam; if (c == '1') req |= TLS_I_DH1024; else if (c == '5') req |= TLS_I_DH512; else if (c != 'n' && c != 'N' && c != '/') { if (LogLevel > 12) sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: illegal value '%s' for DHParam", who, dhparam); dhparam = NULL; } } if (dhparam == NULL) { dhparam = srv ? "1" : "5"; req |= (srv ? TLS_I_DH1024 : TLS_I_DH512); } else if (*dhparam == '/') { TLS_OK_F(dhparam, "DHParameters", bitset(TLS_I_DHPAR_EX, req), TLS_S_DHPAR_EX, TLS_T_OTHER); } } if (!ok) return ok; /* certfile etc. must be "safe". */ sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK | SFF_NOGWFILES | SFF_NOWWFILES | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT; if (DontLockReadFiles) sff |= SFF_NOLOCK; TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req), bitset(TLS_I_CERT_EX, req), bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv); TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req), bitset(TLS_I_KEY_EX, req), bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv); TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req), bitset(TLS_I_CERTF_EX, req), bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv); TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req), bitset(TLS_I_DHPAR_EX, req), bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv); # if OPENSSL_VERSION_NUMBER > 0x00907000L TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req), bitset(TLS_I_CRLF_EX, req), bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv); # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ if (!ok) return ok; # if _FFR_TLS_1 if (cf2 != NULL) { TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req), bitset(TLS_I_CERT_EX, req), bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv); } if (kf2 != NULL) { TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req), bitset(TLS_I_KEY_EX, req), bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv); } # endif /* _FFR_TLS_1 */ /* create a method and a new context */ if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() : SSLv23_client_method())) == NULL) { if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed", who, who); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); return false; } # if OPENSSL_VERSION_NUMBER > 0x00907000L if (CRLFile != NULL) { /* get a pointer to the current certificate validation store */ store = SSL_CTX_get_cert_store(*ctx); /* does not fail */ crl_file = BIO_new(BIO_s_file_internal()); if (crl_file != NULL) { if (BIO_read_filename(crl_file, CRLFile) >= 0) { crl = PEM_read_bio_X509_CRL(crl_file, NULL, NULL, NULL); BIO_free(crl_file); X509_STORE_add_crl(store, crl); X509_CRL_free(crl); X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL); X509_STORE_set_verify_cb_func(store, x509_verify_cb); } else { if (LogLevel > 9) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed", who, CRLFile); } /* avoid memory leaks */ BIO_free(crl_file); return false; } } else if (LogLevel > 9) sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: BIO_new=failed", who); } else store = NULL; # if _FFR_CRLPATH if (CRLPath != NULL && store != NULL) { X509_LOOKUP *lookup; lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (lookup == NULL) { if (LogLevel > 9) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed", who, CRLFile); } return false; } X509_LOOKUP_add_dir(lookup, CRLPath, X509_FILETYPE_PEM); X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL); } # endif /* _FFR_CRLPATH */ # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ # if TLS_NO_RSA /* turn off backward compatibility, required for no-rsa */ SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2); # endif /* TLS_NO_RSA */ # if !TLS_NO_RSA /* ** Create a temporary RSA key ** XXX Maybe we shouldn't create this always (even though it ** is only at startup). ** It is a time-consuming operation and it is not always necessary. ** maybe we should do it only on demand... */ if (bitset(TLS_I_RSA_TMP, req) # if SM_CONF_SHM && ShmId != SM_SHM_NO_ID && (rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL, NULL)) == NULL # else /* SM_CONF_SHM */ && 0 /* no shared memory: no need to generate key now */ # endif /* SM_CONF_SHM */ ) { if (LogLevel > 7) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: RSA_generate_key failed", who); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } return false; } # endif /* !TLS_NO_RSA */ /* ** load private key ** XXX change this for DSA-only version */ if (bitset(TLS_S_KEY_OK, status) && SSL_CTX_use_PrivateKey_file(*ctx, keyfile, SSL_FILETYPE_PEM) <= 0) { if (LogLevel > 7) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed", who, keyfile); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } if (bitset(TLS_I_USE_KEY, req)) return false; } /* get the certificate file */ if (bitset(TLS_S_CERT_OK, status) && SSL_CTX_use_certificate_file(*ctx, certfile, SSL_FILETYPE_PEM) <= 0) { if (LogLevel > 7) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_CTX_use_certificate_file(%s) failed", who, certfile); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } if (bitset(TLS_I_USE_CERT, req)) return false; } /* check the private key */ if (bitset(TLS_S_KEY_OK, status) && (r = SSL_CTX_check_private_key(*ctx)) <= 0) { /* Private key does not match the certificate public key */ if (LogLevel > 5) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_CTX_check_private_key failed(%s): %d", who, keyfile, r); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } if (bitset(TLS_I_USE_KEY, req)) return false; } # if _FFR_TLS_1 /* XXX this code is pretty much duplicated from above! */ /* load private key */ if (bitset(TLS_S_KEY2_OK, status) && SSL_CTX_use_PrivateKey_file(*ctx, kf2, SSL_FILETYPE_PEM) <= 0) { if (LogLevel > 7) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed", who, kf2); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } } /* get the certificate file */ if (bitset(TLS_S_CERT2_OK, status) && SSL_CTX_use_certificate_file(*ctx, cf2, SSL_FILETYPE_PEM) <= 0) { if (LogLevel > 7) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_CTX_use_certificate_file(%s) failed", who, cf2); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } } /* also check the private key */ if (bitset(TLS_S_KEY2_OK, status) && (r = SSL_CTX_check_private_key(*ctx)) <= 0) { /* Private key does not match the certificate public key */ if (LogLevel > 5) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d", who, r); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } } # endif /* _FFR_TLS_1 */ /* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */ #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG /* ** In OpenSSL 0.9.8[ab], enabling zlib compression breaks the ** padding bug work-around, leading to false positives and ** failed connections. We may not interoperate with systems ** with the bug, but this is better than breaking on all 0.9.8[ab] ** systems that have zlib support enabled. ** Note: this checks the runtime version of the library, not ** just the compile time version. */ rt_version = SSLeay(); if (rt_version >= 0x00908000L && rt_version <= 0x0090802fL) { comp_methods = SSL_COMP_get_compression_methods(); if (comp_methods != NULL && sk_SSL_COMP_num(comp_methods) > 0) options &= ~SSL_OP_TLS_BLOCK_PADDING_BUG; } #endif SSL_CTX_set_options(*ctx, options); # if !NO_DH /* Diffie-Hellman initialization */ if (bitset(TLS_I_TRY_DH, req)) { if (bitset(TLS_S_DHPAR_OK, status)) { BIO *bio; if ((bio = BIO_new_file(dhparam, "r")) != NULL) { dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); if (dh == NULL && LogLevel > 7) { unsigned long err; err = ERR_get_error(); sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: cannot read DH parameters(%s): %s", who, dhparam, ERR_error_string(err, NULL)); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } } else { if (LogLevel > 5) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: BIO_new_file(%s) failed", who, dhparam); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } } } if (dh == NULL && bitset(TLS_I_DH1024, req)) { DSA *dsa; /* this takes a while! (7-130s on a 450MHz AMD K6-2) */ dsa = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, 0, NULL); dh = DSA_dup_DH(dsa); DSA_free(dsa); } else if (dh == NULL && bitset(TLS_I_DH512, req)) dh = get_dh512(); if (dh == NULL) { if (LogLevel > 9) { unsigned long err; err = ERR_get_error(); sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s", who, dhparam, ERR_error_string(err, NULL)); } if (bitset(TLS_I_REQ_DH, req)) return false; } else { SSL_CTX_set_tmp_dh(*ctx, dh); /* important to avoid small subgroup attacks */ SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE); if (LogLevel > 13) sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, Diffie-Hellman init, key=%d bit (%c)", who, 8 * DH_size(dh), *dhparam); DH_free(dh); } } # endif /* !NO_DH */ /* XXX do we need this cache here? */ if (bitset(TLS_I_CACHE, req)) { SSL_CTX_sess_set_cache_size(*ctx, 1); SSL_CTX_set_timeout(*ctx, 1); SSL_CTX_set_session_id_context(*ctx, (void *) &server_session_id_context, sizeof(server_session_id_context)); (void) SSL_CTX_set_session_cache_mode(*ctx, SSL_SESS_CACHE_SERVER); } else { (void) SSL_CTX_set_session_cache_mode(*ctx, SSL_SESS_CACHE_OFF); } /* load certificate locations and default CA paths */ if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status)) { if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile, cacertpath)) == 1) { # if !TLS_NO_RSA if (bitset(TLS_I_RSA_TMP, req)) SSL_CTX_set_tmp_rsa_callback(*ctx, tmp_rsa_key); # endif /* !TLS_NO_RSA */ /* ** We have to install our own verify callback: ** SSL_VERIFY_PEER requests a client cert but even ** though *FAIL_IF* isn't set, the connection ** will be aborted if the client presents a cert ** that is not "liked" (can't be verified?) by ** the TLS library :-( */ /* ** XXX currently we could call tls_set_verify() ** but we hope that that function will later on ** only set the mode per connection. */ SSL_CTX_set_verify(*ctx, bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE : SSL_VERIFY_PEER, NULL); /* install verify callback */ SSL_CTX_set_cert_verify_callback(*ctx, tls_verify_cb, NULL); SSL_CTX_set_client_CA_list(*ctx, SSL_load_client_CA_file(cacertfile)); } else { /* ** can't load CA data; do we care? ** the data is necessary to authenticate the client, ** which in turn would be necessary ** if we want to allow relaying based on it. */ if (LogLevel > 5) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: load verify locs %s, %s failed: %d", who, cacertpath, cacertfile, r); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } if (bitset(TLS_I_VRFY_LOC, req)) return false; } } /* XXX: make this dependent on an option? */ if (tTd(96, 9)) SSL_CTX_set_info_callback(*ctx, apps_ssl_info_cb); # if _FFR_TLS_1 /* install our own cipher list */ if (CipherList != NULL && *CipherList != '\0') { if (SSL_CTX_set_cipher_list(*ctx, CipherList) <= 0) { if (LogLevel > 7) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_CTX_set_cipher_list(%s) failed, list ignored", who, CipherList); if (LogLevel > 9) - tlslogerr(who); + tlslogerr(LOG_WARNING, who); } /* failure if setting to this list is required? */ } } # endif /* _FFR_TLS_1 */ if (LogLevel > 12) sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, init=%d", who, ok); # if _FFR_TLS_1 # if 0 /* ** this label is required if we want to have a "clean" exit ** see the comments above at the initialization of cf2 */ endinittls: # endif /* 0 */ /* undo damage to global variables */ if (cf2 != NULL) *--cf2 = ','; if (kf2 != NULL) *--kf2 = ','; # endif /* _FFR_TLS_1 */ return ok; } /* ** TLS_GET_INFO -- get information about TLS connection ** ** Parameters: ** ssl -- TLS connection structure ** srv -- server or client ** host -- hostname of other side ** mac -- macro storage ** certreq -- did we ask for a cert? ** ** Returns: ** result of authentication. ** ** Side Effects: ** sets macros: {cipher}, {tls_version}, {verify}, ** {cipher_bits}, {alg_bits}, {cert}, {cert_subject}, ** {cert_issuer}, {cn_subject}, {cn_issuer} */ int tls_get_info(ssl, srv, host, mac, certreq) SSL *ssl; bool srv; char *host; MACROS_T *mac; bool certreq; { const SSL_CIPHER *c; int b, r; long verifyok; char *s, *who; char bitstr[16]; X509 *cert; c = SSL_get_current_cipher(ssl); /* cast is just workaround for compiler warning */ macdefine(mac, A_TEMP, macid("{cipher}"), (char *) SSL_CIPHER_get_name(c)); b = SSL_CIPHER_get_bits(c, &r); (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", b); macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr); (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", r); macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr); s = SSL_CIPHER_get_version(c); if (s == NULL) s = "UNKNOWN"; macdefine(mac, A_TEMP, macid("{tls_version}"), s); who = srv ? "server" : "client"; cert = SSL_get_peer_certificate(ssl); verifyok = SSL_get_verify_result(ssl); if (LogLevel > 14) sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx", who, verifyok, (unsigned long) cert); if (cert != NULL) { unsigned int n; X509_NAME *subj, *issuer; unsigned char md[EVP_MAX_MD_SIZE]; char buf[MAXNAME]; subj = X509_get_subject_name(cert); issuer = X509_get_issuer_name(cert); X509_NAME_oneline(subj, buf, sizeof(buf)); macdefine(mac, A_TEMP, macid("{cert_subject}"), xtextify(buf, "<>\")")); X509_NAME_oneline(issuer, buf, sizeof(buf)); macdefine(mac, A_TEMP, macid("{cert_issuer}"), xtextify(buf, "<>\")")); # define LL_BADCERT 8 #define CHECK_X509_NAME(which) \ do { \ if (r == -1) \ { \ sm_strlcpy(buf, "BadCertificateUnknown", sizeof(buf)); \ if (LogLevel > LL_BADCERT) \ sm_syslog(LOG_INFO, NOQID, \ "STARTTLS=%s, relay=%.100s, field=%s, status=failed to extract CN", \ who, \ host == NULL ? "local" : host, \ which); \ } \ else if ((size_t)r >= sizeof(buf) - 1) \ { \ sm_strlcpy(buf, "BadCertificateTooLong", sizeof(buf)); \ if (LogLevel > 7) \ sm_syslog(LOG_INFO, NOQID, \ "STARTTLS=%s, relay=%.100s, field=%s, status=CN too long", \ who, \ host == NULL ? "local" : host, \ which); \ } \ else if ((size_t)r > strlen(buf)) \ { \ sm_strlcpy(buf, "BadCertificateContainsNUL", \ sizeof(buf)); \ if (LogLevel > 7) \ sm_syslog(LOG_INFO, NOQID, \ "STARTTLS=%s, relay=%.100s, field=%s, status=CN contains NUL", \ who, \ host == NULL ? "local" : host, \ which); \ } \ } while (0) r = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof buf); CHECK_X509_NAME("cn_subject"); macdefine(mac, A_TEMP, macid("{cn_subject}"), xtextify(buf, "<>\")")); r = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof buf); CHECK_X509_NAME("cn_issuer"); macdefine(mac, A_TEMP, macid("{cn_issuer}"), xtextify(buf, "<>\")")); n = 0; if (X509_digest(cert, EVP_md5(), md, &n) != 0 && n > 0) { char md5h[EVP_MAX_MD_SIZE * 3]; static const char hexcodes[] = "0123456789ABCDEF"; SM_ASSERT((n * 3) + 2 < sizeof(md5h)); for (r = 0; r < (int) n; r++) { md5h[r * 3] = hexcodes[(md[r] & 0xf0) >> 4]; md5h[(r * 3) + 1] = hexcodes[(md[r] & 0x0f)]; md5h[(r * 3) + 2] = ':'; } md5h[(n * 3) - 1] = '\0'; macdefine(mac, A_TEMP, macid("{cert_md5}"), md5h); } else macdefine(mac, A_TEMP, macid("{cert_md5}"), ""); } else { macdefine(mac, A_PERM, macid("{cert_subject}"), ""); macdefine(mac, A_PERM, macid("{cert_issuer}"), ""); macdefine(mac, A_PERM, macid("{cn_subject}"), ""); macdefine(mac, A_PERM, macid("{cn_issuer}"), ""); macdefine(mac, A_TEMP, macid("{cert_md5}"), ""); } switch (verifyok) { case X509_V_OK: if (cert != NULL) { s = "OK"; r = TLS_AUTH_OK; } else { s = certreq ? "NO" : "NOT", r = TLS_AUTH_NO; } break; default: s = "FAIL"; r = TLS_AUTH_FAIL; break; } macdefine(mac, A_PERM, macid("{verify}"), s); if (cert != NULL) X509_free(cert); /* do some logging */ if (LogLevel > 8) { char *vers, *s1, *s2, *cbits, *algbits; vers = macget(mac, macid("{tls_version}")); cbits = macget(mac, macid("{cipher_bits}")); algbits = macget(mac, macid("{alg_bits}")); s1 = macget(mac, macid("{verify}")); s2 = macget(mac, macid("{cipher}")); /* XXX: maybe cut off ident info? */ sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, relay=%.100s, version=%.16s, verify=%.16s, cipher=%.64s, bits=%.6s/%.6s", who, host == NULL ? "local" : host, vers, s1, s2, /* sm_snprintf() can deal with NULL */ algbits == NULL ? "0" : algbits, cbits == NULL ? "0" : cbits); if (LogLevel > 11) { /* ** Maybe run xuntextify on the strings? ** That is easier to read but makes it maybe a bit ** more complicated to figure out the right values ** for the access map... */ s1 = macget(mac, macid("{cert_subject}")); s2 = macget(mac, macid("{cert_issuer}")); sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, cert-subject=%.256s, cert-issuer=%.256s, verifymsg=%s", who, s1, s2, X509_verify_cert_error_string(verifyok)); } } return r; } /* ** ENDTLS -- shutdown secure connection ** ** Parameters: ** ssl -- SSL connection information. ** side -- server/client (for logging). ** ** Returns: ** success? (EX_* code) */ int endtls(ssl, side) SSL *ssl; char *side; { int ret = EX_OK; if (ssl != NULL) { int r; if ((r = SSL_shutdown(ssl)) < 0) { if (LogLevel > 11) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, SSL_shutdown failed: %d", side, r); - tlslogerr(side); + tlslogerr(LOG_WARNING, side); } ret = EX_SOFTWARE; } # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL /* ** Bug in OpenSSL (at least up to 0.9.6b): ** From: Lutz.Jaenicke@aet.TU-Cottbus.DE ** Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de> ** To: openssl-users@openssl.org ** Subject: Re: SSL_shutdown() woes (fwd) ** ** The side sending the shutdown alert first will ** not care about the answer of the peer but will ** immediately return with a return value of "0" ** (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate ** the value of "0" and as the shutdown alert of the peer was ** not received (actually, the program did not even wait for ** the answer), an SSL_ERROR_SYSCALL is flagged, because this ** is the default rule in case everything else does not apply. ** ** For your server the problem is different, because it ** receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN), ** then sends its response (SSL_SENT_SHUTDOWN), so for the ** server the shutdown was successfull. ** ** As is by know, you would have to call SSL_shutdown() once ** and ignore an SSL_ERROR_SYSCALL returned. Then call ** SSL_shutdown() again to actually get the server's response. ** ** In the last discussion, Bodo Moeller concluded that a ** rewrite of the shutdown code would be necessary, but ** probably with another API, as the change would not be ** compatible to the way it is now. Things do not become ** easier as other programs do not follow the shutdown ** guidelines anyway, so that a lot error conditions and ** compitibility issues would have to be caught. ** ** For now the recommondation is to ignore the error message. */ else if (r == 0) { if (LogLevel > 15) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, SSL_shutdown not done", side); - tlslogerr(side); + tlslogerr(LOG_WARNING, side); } ret = EX_SOFTWARE; } # endif /* !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL */ SSL_free(ssl); ssl = NULL; } return ret; } # if !TLS_NO_RSA /* ** TMP_RSA_KEY -- return temporary RSA key ** ** Parameters: ** s -- TLS connection structure ** export -- ** keylength -- ** ** Returns: ** temporary RSA key. */ # ifndef MAX_RSA_TMP_CNT # define MAX_RSA_TMP_CNT 1000 /* XXX better value? */ # endif /* ! MAX_RSA_TMP_CNT */ /* ARGUSED0 */ static RSA * tmp_rsa_key(s, export, keylength) SSL *s; int export; int keylength; { # if SM_CONF_SHM extern int ShmId; extern int *PRSATmpCnt; if (ShmId != SM_SHM_NO_ID && rsa_tmp != NULL && ++(*PRSATmpCnt) < MAX_RSA_TMP_CNT) return rsa_tmp; # endif /* SM_CONF_SHM */ if (rsa_tmp != NULL) RSA_free(rsa_tmp); rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL, NULL); if (rsa_tmp == NULL) { if (LogLevel > 0) sm_syslog(LOG_ERR, NOQID, "STARTTLS=server, tmp_rsa_key: RSA_generate_key failed!"); } else { # if SM_CONF_SHM # if 0 /* ** XXX we can't (yet) share the new key... ** The RSA structure contains pointers hence it can't be ** easily kept in shared memory. It must be transformed ** into a continous memory region first, then stored, ** and later read out again (each time re-transformed). */ if (ShmId != SM_SHM_NO_ID) *PRSATmpCnt = 0; # endif /* 0 */ # endif /* SM_CONF_SHM */ if (LogLevel > 9) sm_syslog(LOG_ERR, NOQID, "STARTTLS=server, tmp_rsa_key: new temp RSA key"); } return rsa_tmp; } # endif /* !TLS_NO_RSA */ /* ** APPS_SSL_INFO_CB -- info callback for TLS connections ** ** Parameters: ** s -- TLS connection structure ** where -- state in handshake ** ret -- return code of last operation ** ** Returns: ** none. */ static void apps_ssl_info_cb(s, where, ret) CONST097 SSL *s; int where; int ret; { int w; char *str; BIO *bio_err = NULL; if (LogLevel > 14) sm_syslog(LOG_INFO, NOQID, "STARTTLS: info_callback where=0x%x, ret=%d", where, ret); w = where & ~SSL_ST_MASK; if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (bitset(SSL_ST_CONNECT, w)) str = "SSL_connect"; else if (bitset(SSL_ST_ACCEPT, w)) str = "SSL_accept"; else str = "undefined"; if (bitset(SSL_CB_LOOP, where)) { if (LogLevel > 12) sm_syslog(LOG_NOTICE, NOQID, "STARTTLS: %s:%s", str, SSL_state_string_long(s)); } else if (bitset(SSL_CB_ALERT, where)) { str = bitset(SSL_CB_READ, where) ? "read" : "write"; if (LogLevel > 12) sm_syslog(LOG_NOTICE, NOQID, "STARTTLS: SSL3 alert %s:%s:%s", str, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret)); } else if (bitset(SSL_CB_EXIT, where)) { if (ret == 0) { if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s:failed in %s", str, SSL_state_string_long(s)); } else if (ret < 0) { if (LogLevel > 7) sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s:error in %s", str, SSL_state_string_long(s)); } } } /* ** TLS_VERIFY_LOG -- log verify error for TLS certificates ** ** Parameters: ** ok -- verify ok? ** ctx -- x509 context ** ** Returns: ** 0 -- fatal error ** 1 -- ok */ static int tls_verify_log(ok, ctx, name) int ok; X509_STORE_CTX *ctx; char *name; { SSL *ssl; X509 *cert; int reason, depth; char buf[512]; cert = X509_STORE_CTX_get_current_cert(ctx); reason = X509_STORE_CTX_get_error(ctx); depth = X509_STORE_CTX_get_error_depth(ctx); ssl = (SSL *) X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); if (ssl == NULL) { /* internal error */ sm_syslog(LOG_ERR, NOQID, "STARTTLS: internal error: tls_verify_cb: ssl == NULL"); return 0; } X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); sm_syslog(LOG_INFO, NOQID, "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s", name, depth, buf, ok, X509_verify_cert_error_string(reason)); return 1; } /* ** TLS_VERIFY_CB -- verify callback for TLS certificates ** ** Parameters: ** ctx -- x509 context ** ** Returns: ** accept connection? ** currently: always yes. */ static int # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L tls_verify_cb(ctx) X509_STORE_CTX *ctx; # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */ tls_verify_cb(ctx, unused) X509_STORE_CTX *ctx; void *unused; # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */ { int ok; /* ** man SSL_CTX_set_cert_verify_callback(): ** callback should return 1 to indicate verification success ** and 0 to indicate verification failure. */ ok = X509_verify_cert(ctx); if (ok <= 0) { if (LogLevel > 13) return tls_verify_log(ok, ctx, "TLS"); } return 1; } /* ** TLSLOGERR -- log the errors from the TLS error stack ** ** Parameters: +** level -- syslog level ** who -- server/client (for logging). ** ** Returns: ** none. */ void -tlslogerr(who) +tlslogerr(level, who) + int level; const char *who; { unsigned long l; int line, flags; unsigned long es; char *file, *data; char buf[256]; # define CP (const char **) es = CRYPTO_thread_id(); while ((l = ERR_get_error_line_data(CP &file, &line, CP &data, &flags)) != 0) { - sm_syslog(LOG_WARNING, NOQID, + sm_syslog(level, NOQID, "STARTTLS=%s: %lu:%s:%s:%d:%s", who, es, ERR_error_string(l, buf), file, line, bitset(ERR_TXT_STRING, flags) ? data : ""); } } # if OPENSSL_VERSION_NUMBER > 0x00907000L /* ** X509_VERIFY_CB -- verify callback ** ** Parameters: ** ctx -- x509 context ** ** Returns: ** accept connection? ** currently: always yes. */ static int x509_verify_cb(ok, ctx) int ok; X509_STORE_CTX *ctx; { if (ok == 0) { if (LogLevel > 13) tls_verify_log(ok, ctx, "x509"); if (ctx->error == X509_V_ERR_UNABLE_TO_GET_CRL) { ctx->error = 0; return 1; /* override it */ } } return ok; } # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ #endif /* STARTTLS */ Index: head/contrib/sendmail/src/usersmtp.c =================================================================== --- head/contrib/sendmail/src/usersmtp.c (revision 249728) +++ head/contrib/sendmail/src/usersmtp.c (revision 249729) @@ -1,3330 +1,3330 @@ /* * Copyright (c) 1998-2006, 2008-2010 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: usersmtp.c,v 8.485 2010/07/23 21:09:38 ca Exp $") +SM_RCSID("@(#)$Id: usersmtp.c,v 8.486 2013/03/12 15:24:54 ca Exp $") #include static void esmtp_check __P((char *, bool, MAILER *, MCI *, ENVELOPE *)); static void helo_options __P((char *, bool, MAILER *, MCI *, ENVELOPE *)); static int smtprcptstat __P((ADDRESS *, MAILER *, MCI *, ENVELOPE *)); #if SASL extern void *sm_sasl_malloc __P((unsigned long)); extern void sm_sasl_free __P((void *)); #endif /* SASL */ /* ** USERSMTP -- run SMTP protocol from the user end. ** ** This protocol is described in RFC821. */ #define SMTPCLOSING 421 /* "Service Shutting Down" */ #define ENHSCN(e, d) ((e) == NULL ? (d) : (e)) #define ENHSCN_RPOOL(e, d, rpool) \ ((e) == NULL ? (d) : sm_rpool_strdup_x(rpool, e)) static char SmtpMsgBuffer[MAXLINE]; /* buffer for commands */ static char SmtpReplyBuffer[MAXLINE]; /* buffer for replies */ static bool SmtpNeedIntro; /* need "while talking" in transcript */ /* ** SMTPINIT -- initialize SMTP. ** ** Opens the connection and sends the initial protocol. ** ** Parameters: ** m -- mailer to create connection to. ** mci -- the mailer connection info. ** e -- the envelope. ** onlyhelo -- send only helo command? ** ** Returns: ** none. ** ** Side Effects: ** creates connection and sends initial protocol. */ void smtpinit(m, mci, e, onlyhelo) MAILER *m; register MCI *mci; ENVELOPE *e; bool onlyhelo; { register int r; int state; register char *p; register char *hn; char *enhsc; enhsc = NULL; if (tTd(18, 1)) { sm_dprintf("smtpinit "); mci_dump(sm_debug_file(), mci, false); } /* ** Open the connection to the mailer. */ SmtpError[0] = '\0'; SmtpMsgBuffer[0] = '\0'; CurHostName = mci->mci_host; /* XXX UGLY XXX */ if (CurHostName == NULL) CurHostName = MyHostName; SmtpNeedIntro = true; state = mci->mci_state; switch (state) { case MCIS_MAIL: case MCIS_RCPT: case MCIS_DATA: /* need to clear old information */ smtprset(m, mci, e); /* FALLTHROUGH */ case MCIS_OPEN: if (!onlyhelo) return; break; case MCIS_ERROR: case MCIS_QUITING: case MCIS_SSD: /* shouldn't happen */ smtpquit(m, mci, e); /* FALLTHROUGH */ case MCIS_CLOSED: syserr("451 4.4.0 smtpinit: state CLOSED (was %d)", state); return; case MCIS_OPENING: break; } if (onlyhelo) goto helo; mci->mci_state = MCIS_OPENING; clrsessenvelope(e); /* ** Get the greeting message. ** This should appear spontaneously. Give it five minutes to ** happen. */ SmtpPhase = mci->mci_phase = "client greeting"; sm_setproctitle(true, e, "%s %s: %s", qid_printname(e), CurHostName, mci->mci_phase); r = reply(m, mci, e, TimeOuts.to_initial, esmtp_check, NULL, XS_GREET); if (r < 0) goto tempfail1; if (REPLYTYPE(r) == 4) goto tempfail2; if (REPLYTYPE(r) != 2) goto unavailable; /* ** Send the HELO command. ** My mother taught me to always introduce myself. */ helo: if (bitnset(M_ESMTP, m->m_flags) || bitnset(M_LMTP, m->m_flags)) mci->mci_flags |= MCIF_ESMTP; hn = mci->mci_heloname ? mci->mci_heloname : MyHostName; tryhelo: #if _FFR_IGNORE_EXT_ON_HELO mci->mci_flags &= ~MCIF_HELO; #endif /* _FFR_IGNORE_EXT_ON_HELO */ if (bitnset(M_LMTP, m->m_flags)) { smtpmessage("LHLO %s", m, mci, hn); SmtpPhase = mci->mci_phase = "client LHLO"; } else if (bitset(MCIF_ESMTP, mci->mci_flags) && !bitnset(M_FSMTP, m->m_flags)) { smtpmessage("EHLO %s", m, mci, hn); SmtpPhase = mci->mci_phase = "client EHLO"; } else { smtpmessage("HELO %s", m, mci, hn); SmtpPhase = mci->mci_phase = "client HELO"; #if _FFR_IGNORE_EXT_ON_HELO mci->mci_flags |= MCIF_HELO; #endif /* _FFR_IGNORE_EXT_ON_HELO */ } sm_setproctitle(true, e, "%s %s: %s", qid_printname(e), CurHostName, mci->mci_phase); r = reply(m, mci, e, bitnset(M_LMTP, m->m_flags) ? TimeOuts.to_lhlo : TimeOuts.to_helo, helo_options, NULL, XS_EHLO); if (r < 0) goto tempfail1; else if (REPLYTYPE(r) == 5) { if (bitset(MCIF_ESMTP, mci->mci_flags) && !bitnset(M_LMTP, m->m_flags)) { /* try old SMTP instead */ mci->mci_flags &= ~MCIF_ESMTP; goto tryhelo; } goto unavailable; } else if (REPLYTYPE(r) != 2) goto tempfail2; /* ** Check to see if we actually ended up talking to ourself. ** This means we didn't know about an alias or MX, or we managed ** to connect to an echo server. */ p = strchr(&SmtpReplyBuffer[4], ' '); if (p != NULL) *p = '\0'; if (!bitnset(M_NOLOOPCHECK, m->m_flags) && !bitnset(M_LMTP, m->m_flags) && sm_strcasecmp(&SmtpReplyBuffer[4], MyHostName) == 0) { syserr("553 5.3.5 %s config error: mail loops back to me (MX problem?)", CurHostName); mci_setstat(mci, EX_CONFIG, "5.3.5", "553 5.3.5 system config error"); mci->mci_errno = 0; smtpquit(m, mci, e); return; } /* ** If this is expected to be another sendmail, send some internal ** commands. ** If we're running as MSP, "propagate" -v flag if possible. */ if ((UseMSP && Verbose && bitset(MCIF_VERB, mci->mci_flags)) # if !_FFR_DEPRECATE_MAILER_FLAG_I || bitnset(M_INTERNAL, m->m_flags) # endif /* !_FFR_DEPRECATE_MAILER_FLAG_I */ ) { /* tell it to be verbose */ smtpmessage("VERB", m, mci); r = reply(m, mci, e, TimeOuts.to_miscshort, NULL, &enhsc, XS_DEFAULT); if (r < 0) goto tempfail1; } if (mci->mci_state != MCIS_CLOSED) { mci->mci_state = MCIS_OPEN; return; } /* got a 421 error code during startup */ tempfail1: mci_setstat(mci, EX_TEMPFAIL, ENHSCN(enhsc, "4.4.2"), NULL); if (mci->mci_state != MCIS_CLOSED) smtpquit(m, mci, e); return; tempfail2: /* XXX should use code from other end iff ENHANCEDSTATUSCODES */ mci_setstat(mci, EX_TEMPFAIL, ENHSCN(enhsc, "4.5.0"), SmtpReplyBuffer); if (mci->mci_state != MCIS_CLOSED) smtpquit(m, mci, e); return; unavailable: mci_setstat(mci, EX_UNAVAILABLE, "5.5.0", SmtpReplyBuffer); smtpquit(m, mci, e); return; } /* ** ESMTP_CHECK -- check to see if this implementation likes ESMTP protocol ** ** Parameters: ** line -- the response line. ** firstline -- set if this is the first line of the reply. ** m -- the mailer. ** mci -- the mailer connection info. ** e -- the envelope. ** ** Returns: ** none. */ static void esmtp_check(line, firstline, m, mci, e) char *line; bool firstline; MAILER *m; register MCI *mci; ENVELOPE *e; { if (strstr(line, "ESMTP") != NULL) mci->mci_flags |= MCIF_ESMTP; /* ** Dirty hack below. Quoting the author: ** This was a response to people who wanted SMTP transmission to be ** just-send-8 by default. Essentially, you could put this tag into ** your greeting message to behave as though the F=8 flag was set on ** the mailer. */ if (strstr(line, "8BIT-OK") != NULL) mci->mci_flags |= MCIF_8BITOK; } #if SASL /* specify prototype so compiler can check calls */ static char *str_union __P((char *, char *, SM_RPOOL_T *)); /* ** STR_UNION -- create the union of two lists ** ** Parameters: ** s1, s2 -- lists of items (separated by single blanks). ** rpool -- resource pool from which result is allocated. ** ** Returns: ** the union of both lists. */ static char * str_union(s1, s2, rpool) char *s1, *s2; SM_RPOOL_T *rpool; { char *hr, *h1, *h, *res; int l1, l2, rl; if (s1 == NULL || *s1 == '\0') return s2; if (s2 == NULL || *s2 == '\0') return s1; l1 = strlen(s1); l2 = strlen(s2); rl = l1 + l2; if (rl <= 0) { sm_syslog(LOG_WARNING, NOQID, "str_union: stringlen1=%d, stringlen2=%d, sum=%d, status=overflow", l1, l2, rl); res = NULL; } else res = (char *) sm_rpool_malloc(rpool, rl + 2); if (res == NULL) { if (l1 > l2) return s1; return s2; } (void) sm_strlcpy(res, s1, rl); hr = res + l1; h1 = s2; h = s2; /* walk through s2 */ while (h != NULL && *h1 != '\0') { /* is there something after the current word? */ if ((h = strchr(h1, ' ')) != NULL) *h = '\0'; l1 = strlen(h1); /* does the current word appear in s1 ? */ if (iteminlist(h1, s1, " ") == NULL) { /* add space as delimiter */ *hr++ = ' '; /* copy the item */ memcpy(hr, h1, l1); /* advance pointer in result list */ hr += l1; *hr = '\0'; } if (h != NULL) { /* there are more items */ *h = ' '; h1 = h + 1; } } return res; } #endif /* SASL */ /* ** HELO_OPTIONS -- process the options on a HELO line. ** ** Parameters: ** line -- the response line. ** firstline -- set if this is the first line of the reply. ** m -- the mailer. ** mci -- the mailer connection info. ** e -- the envelope (unused). ** ** Returns: ** none. */ static void helo_options(line, firstline, m, mci, e) char *line; bool firstline; MAILER *m; register MCI *mci; ENVELOPE *e; { register char *p; #if _FFR_IGNORE_EXT_ON_HELO static bool logged = false; #endif /* _FFR_IGNORE_EXT_ON_HELO */ if (firstline) { mci_clr_extensions(mci); #if _FFR_IGNORE_EXT_ON_HELO logged = false; #endif /* _FFR_IGNORE_EXT_ON_HELO */ return; } #if _FFR_IGNORE_EXT_ON_HELO else if (bitset(MCIF_HELO, mci->mci_flags)) { if (LogLevel > 8 && !logged) { sm_syslog(LOG_WARNING, NOQID, "server=%s [%s] returned extensions despite HELO command", macvalue(macid("{server_name}"), e), macvalue(macid("{server_addr}"), e)); logged = true; } return; } #endif /* _FFR_IGNORE_EXT_ON_HELO */ if (strlen(line) < 5) return; line += 4; p = strpbrk(line, " ="); if (p != NULL) *p++ = '\0'; if (sm_strcasecmp(line, "size") == 0) { mci->mci_flags |= MCIF_SIZE; if (p != NULL) mci->mci_maxsize = atol(p); } else if (sm_strcasecmp(line, "8bitmime") == 0) { mci->mci_flags |= MCIF_8BITMIME; mci->mci_flags &= ~MCIF_7BIT; } else if (sm_strcasecmp(line, "expn") == 0) mci->mci_flags |= MCIF_EXPN; else if (sm_strcasecmp(line, "dsn") == 0) mci->mci_flags |= MCIF_DSN; else if (sm_strcasecmp(line, "enhancedstatuscodes") == 0) mci->mci_flags |= MCIF_ENHSTAT; else if (sm_strcasecmp(line, "pipelining") == 0) mci->mci_flags |= MCIF_PIPELINED; else if (sm_strcasecmp(line, "verb") == 0) mci->mci_flags |= MCIF_VERB; #if STARTTLS else if (sm_strcasecmp(line, "starttls") == 0) mci->mci_flags |= MCIF_TLS; #endif /* STARTTLS */ else if (sm_strcasecmp(line, "deliverby") == 0) { mci->mci_flags |= MCIF_DLVR_BY; if (p != NULL) mci->mci_min_by = atol(p); } #if SASL else if (sm_strcasecmp(line, "auth") == 0) { if (p != NULL && *p != '\0' && !bitset(MCIF_AUTH2, mci->mci_flags)) { if (mci->mci_saslcap != NULL) { /* ** Create the union with previous auth ** offerings because we recognize "auth " ** and "auth=" (old format). */ mci->mci_saslcap = str_union(mci->mci_saslcap, p, mci->mci_rpool); mci->mci_flags |= MCIF_AUTH2; } else { int l; l = strlen(p) + 1; mci->mci_saslcap = (char *) sm_rpool_malloc(mci->mci_rpool, l); if (mci->mci_saslcap != NULL) { (void) sm_strlcpy(mci->mci_saslcap, p, l); mci->mci_flags |= MCIF_AUTH; } } } if (tTd(95, 5)) sm_syslog(LOG_DEBUG, NOQID, "AUTH flags=%lx, mechs=%s", mci->mci_flags, mci->mci_saslcap); } #endif /* SASL */ } #if SASL static int getsimple __P((void *, int, const char **, unsigned *)); static int getsecret __P((sasl_conn_t *, void *, int, sasl_secret_t **)); static int saslgetrealm __P((void *, int, const char **, const char **)); static int readauth __P((char *, bool, SASL_AI_T *m, SM_RPOOL_T *)); static int getauth __P((MCI *, ENVELOPE *, SASL_AI_T *)); static char *removemech __P((char *, char *, SM_RPOOL_T *)); static int attemptauth __P((MAILER *, MCI *, ENVELOPE *, SASL_AI_T *)); static sasl_callback_t callbacks[] = { { SASL_CB_GETREALM, (sasl_callback_ft)&saslgetrealm, NULL }, #define CB_GETREALM_IDX 0 { SASL_CB_PASS, (sasl_callback_ft)&getsecret, NULL }, #define CB_PASS_IDX 1 { SASL_CB_USER, (sasl_callback_ft)&getsimple, NULL }, #define CB_USER_IDX 2 { SASL_CB_AUTHNAME, (sasl_callback_ft)&getsimple, NULL }, #define CB_AUTHNAME_IDX 3 { SASL_CB_VERIFYFILE, (sasl_callback_ft)&safesaslfile, NULL }, #define CB_SAFESASL_IDX 4 { SASL_CB_LIST_END, NULL, NULL } }; /* ** INIT_SASL_CLIENT -- initialize client side of Cyrus-SASL ** ** Parameters: ** none. ** ** Returns: ** SASL_OK -- if successful. ** SASL error code -- otherwise. ** ** Side Effects: ** checks/sets sasl_clt_init. ** ** Note: ** Callbacks are ignored if sasl_client_init() has ** been called before (by a library such as libnss_ldap) */ static bool sasl_clt_init = false; static int init_sasl_client() { int result; if (sasl_clt_init) return SASL_OK; result = sasl_client_init(callbacks); /* should we retry later again or just remember that it failed? */ if (result == SASL_OK) sasl_clt_init = true; return result; } /* ** STOP_SASL_CLIENT -- shutdown client side of Cyrus-SASL ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** checks/sets sasl_clt_init. */ void stop_sasl_client() { if (!sasl_clt_init) return; sasl_clt_init = false; sasl_done(); } /* ** GETSASLDATA -- process the challenges from the SASL protocol ** ** This gets the relevant sasl response data out of the reply ** from the server. ** ** Parameters: ** line -- the response line. ** firstline -- set if this is the first line of the reply. ** m -- the mailer. ** mci -- the mailer connection info. ** e -- the envelope (unused). ** ** Returns: ** none. */ static void getsasldata __P((char *, bool, MAILER *, MCI *, ENVELOPE *)); static void getsasldata(line, firstline, m, mci, e) char *line; bool firstline; MAILER *m; register MCI *mci; ENVELOPE *e; { int len; int result; # if SASL < 20000 char *out; # endif /* SASL < 20000 */ /* if not a continue we don't care about it */ len = strlen(line); if ((len <= 4) || (line[0] != '3') || !isascii(line[1]) || !isdigit(line[1]) || !isascii(line[2]) || !isdigit(line[2])) { SM_FREE_CLR(mci->mci_sasl_string); return; } /* forget about "334 " */ line += 4; len -= 4; # if SASL >= 20000 /* XXX put this into a macro/function? It's duplicated below */ if (mci->mci_sasl_string != NULL) { if (mci->mci_sasl_string_len <= len) { sm_free(mci->mci_sasl_string); /* XXX */ mci->mci_sasl_string = xalloc(len + 1); } } else mci->mci_sasl_string = xalloc(len + 1); result = sasl_decode64(line, len, mci->mci_sasl_string, len + 1, (unsigned int *) &mci->mci_sasl_string_len); if (result != SASL_OK) { mci->mci_sasl_string_len = 0; *mci->mci_sasl_string = '\0'; } # else /* SASL >= 20000 */ out = (char *) sm_rpool_malloc_x(mci->mci_rpool, len + 1); result = sasl_decode64(line, len, out, (unsigned int *) &len); if (result != SASL_OK) { len = 0; *out = '\0'; } /* ** mci_sasl_string is "shared" with Cyrus-SASL library; hence ** it can't be in an rpool unless we use the same memory ** management mechanism (with same rpool!) for Cyrus SASL. */ if (mci->mci_sasl_string != NULL) { if (mci->mci_sasl_string_len <= len) { sm_free(mci->mci_sasl_string); /* XXX */ mci->mci_sasl_string = xalloc(len + 1); } } else mci->mci_sasl_string = xalloc(len + 1); memcpy(mci->mci_sasl_string, out, len); mci->mci_sasl_string[len] = '\0'; mci->mci_sasl_string_len = len; # endif /* SASL >= 20000 */ return; } /* ** READAUTH -- read auth values from a file ** ** Parameters: ** filename -- name of file to read. ** safe -- if set, this is a safe read. ** sai -- where to store auth_info. ** rpool -- resource pool for sai. ** ** Returns: ** EX_OK -- data succesfully read. ** EX_UNAVAILABLE -- no valid filename. ** EX_TEMPFAIL -- temporary failure. */ static char *sasl_info_name[] = { "user id", "authentication id", "password", "realm", "mechlist" }; static int readauth(filename, safe, sai, rpool) char *filename; bool safe; SASL_AI_T *sai; SM_RPOOL_T *rpool; { SM_FILE_T *f; long sff; pid_t pid; int lc; char *s; char buf[MAXLINE]; if (filename == NULL || filename[0] == '\0') return EX_UNAVAILABLE; #if !_FFR_ALLOW_SASLINFO /* ** make sure we don't use a program that is not ** accesible to the user who specified a different authinfo file. ** However, currently we don't pass this info (authinfo file ** specified by user) around, so we just turn off program access. */ if (filename[0] == '|') { auto int fd; int i; char *p; char *argv[MAXPV + 1]; i = 0; for (p = strtok(&filename[1], " \t"); p != NULL; p = strtok(NULL, " \t")) { if (i >= MAXPV) break; argv[i++] = p; } argv[i] = NULL; pid = prog_open(argv, &fd, CurEnv); if (pid < 0) f = NULL; else f = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &fd, SM_IO_RDONLY, NULL); } else #endif /* !_FFR_ALLOW_SASLINFO */ { pid = -1; sff = SFF_REGONLY|SFF_SAFEDIRPATH|SFF_NOWLINK |SFF_NOGWFILES|SFF_NOWWFILES|SFF_NOWRFILES; # if _FFR_GROUPREADABLEAUTHINFOFILE if (!bitnset(DBS_GROUPREADABLEAUTHINFOFILE, DontBlameSendmail)) # endif /* _FFR_GROUPREADABLEAUTHINFOFILE */ sff |= SFF_NOGRFILES; if (DontLockReadFiles) sff |= SFF_NOLOCK; #if _FFR_ALLOW_SASLINFO /* ** XXX: make sure we don't read or open files that are not ** accesible to the user who specified a different authinfo ** file. */ sff |= SFF_MUSTOWN; #else /* _FFR_ALLOW_SASLINFO */ if (safe) sff |= SFF_OPENASROOT; #endif /* _FFR_ALLOW_SASLINFO */ f = safefopen(filename, O_RDONLY, 0, sff); } if (f == NULL) { if (LogLevel > 5) sm_syslog(LOG_ERR, NOQID, "AUTH=client, error: can't open %s: %s", filename, sm_errstring(errno)); return EX_TEMPFAIL; } lc = 0; while (lc <= SASL_MECHLIST && - sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL) + sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { if (buf[0] != '#') { (*sai)[lc] = sm_rpool_strdup_x(rpool, buf); if ((s = strchr((*sai)[lc], '\n')) != NULL) *s = '\0'; lc++; } } (void) sm_io_close(f, SM_TIME_DEFAULT); if (pid > 0) (void) waitfor(pid); if (lc < SASL_PASSWORD) { if (LogLevel > 8) sm_syslog(LOG_ERR, NOQID, "AUTH=client, error: can't read %s from %s", sasl_info_name[lc + 1], filename); return EX_TEMPFAIL; } return EX_OK; } /* ** GETAUTH -- get authinfo from ruleset call ** ** {server_name}, {server_addr} must be set ** ** Parameters: ** mci -- the mailer connection structure. ** e -- the envelope (including the sender to specify). ** sai -- pointer to authinfo (result). ** ** Returns: ** EX_OK -- ruleset was succesfully called, data may not ** be available, sai must be checked. ** EX_UNAVAILABLE -- ruleset unavailable (or failed). ** EX_TEMPFAIL -- temporary failure (from ruleset). ** ** Side Effects: ** Fills in sai if successful. */ static int getauth(mci, e, sai) MCI *mci; ENVELOPE *e; SASL_AI_T *sai; { int i, r, l, got, ret; char **pvp; char pvpbuf[PSBUFSIZE]; r = rscap("authinfo", macvalue(macid("{server_name}"), e), macvalue(macid("{server_addr}"), e), e, &pvp, pvpbuf, sizeof(pvpbuf)); if (r != EX_OK) return EX_UNAVAILABLE; /* other than expected return value: ok (i.e., no auth) */ if (pvp == NULL || pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET) return EX_OK; if (pvp[1] != NULL && sm_strncasecmp(pvp[1], "temp", 4) == 0) return EX_TEMPFAIL; /* ** parse the data, put it into sai ** format: "TDstring" (including the '"' !) ** where T is a tag: 'U', ... ** D is a delimiter: ':' or '=' */ ret = EX_OK; /* default return value */ i = 0; got = 0; while (i < SASL_ENTRIES) { if (pvp[i + 1] == NULL) break; if (pvp[i + 1][0] != '"') break; switch (pvp[i + 1][1]) { case 'U': case 'u': r = SASL_USER; break; case 'I': case 'i': r = SASL_AUTHID; break; case 'P': case 'p': r = SASL_PASSWORD; break; case 'R': case 'r': r = SASL_DEFREALM; break; case 'M': case 'm': r = SASL_MECHLIST; break; default: goto fail; } l = strlen(pvp[i + 1]); /* check syntax */ if (l <= 3 || pvp[i + 1][l - 1] != '"') goto fail; /* remove closing quote */ pvp[i + 1][l - 1] = '\0'; /* remove "TD and " */ l -= 4; (*sai)[r] = (char *) sm_rpool_malloc(mci->mci_rpool, l + 1); if ((*sai)[r] == NULL) goto tempfail; if (pvp[i + 1][2] == ':') { /* ':text' (just copy) */ (void) sm_strlcpy((*sai)[r], pvp[i + 1] + 3, l + 1); got |= 1 << r; } else if (pvp[i + 1][2] == '=') { unsigned int len; /* '=base64' (decode) */ # if SASL >= 20000 ret = sasl_decode64(pvp[i + 1] + 3, (unsigned int) l, (*sai)[r], (unsigned int) l + 1, &len); # else /* SASL >= 20000 */ ret = sasl_decode64(pvp[i + 1] + 3, (unsigned int) l, (*sai)[r], &len); # endif /* SASL >= 20000 */ if (ret != SASL_OK) goto fail; got |= 1 << r; } else goto fail; if (tTd(95, 5)) sm_syslog(LOG_DEBUG, NOQID, "getauth %s=%s", sasl_info_name[r], (*sai)[r]); ++i; } /* did we get the expected data? */ /* XXX: EXTERNAL mechanism only requires (and only uses) SASL_USER */ if (!(bitset(SASL_USER_BIT|SASL_AUTHID_BIT, got) && bitset(SASL_PASSWORD_BIT, got))) goto fail; /* no authid? copy uid */ if (!bitset(SASL_AUTHID_BIT, got)) { l = strlen((*sai)[SASL_USER]) + 1; (*sai)[SASL_AUTHID] = (char *) sm_rpool_malloc(mci->mci_rpool, l + 1); if ((*sai)[SASL_AUTHID] == NULL) goto tempfail; (void) sm_strlcpy((*sai)[SASL_AUTHID], (*sai)[SASL_USER], l); } /* no uid? copy authid */ if (!bitset(SASL_USER_BIT, got)) { l = strlen((*sai)[SASL_AUTHID]) + 1; (*sai)[SASL_USER] = (char *) sm_rpool_malloc(mci->mci_rpool, l + 1); if ((*sai)[SASL_USER] == NULL) goto tempfail; (void) sm_strlcpy((*sai)[SASL_USER], (*sai)[SASL_AUTHID], l); } return EX_OK; tempfail: ret = EX_TEMPFAIL; fail: if (LogLevel > 8) sm_syslog(LOG_WARNING, NOQID, "AUTH=client, relay=%.64s [%.16s], authinfo %sfailed", macvalue(macid("{server_name}"), e), macvalue(macid("{server_addr}"), e), ret == EX_TEMPFAIL ? "temp" : ""); for (i = 0; i <= SASL_MECHLIST; i++) (*sai)[i] = NULL; /* just clear; rpool */ return ret; } # if SASL >= 20000 /* ** GETSIMPLE -- callback to get userid or authid ** ** Parameters: ** context -- sai ** id -- what to do ** result -- (pointer to) result ** len -- (pointer to) length of result ** ** Returns: ** OK/failure values */ static int getsimple(context, id, result, len) void *context; int id; const char **result; unsigned *len; { SASL_AI_T *sai; if (result == NULL || context == NULL) return SASL_BADPARAM; sai = (SASL_AI_T *) context; switch (id) { case SASL_CB_USER: *result = (*sai)[SASL_USER]; if (tTd(95, 5)) sm_syslog(LOG_DEBUG, NOQID, "AUTH username '%s'", *result); if (len != NULL) *len = *result != NULL ? strlen(*result) : 0; break; case SASL_CB_AUTHNAME: *result = (*sai)[SASL_AUTHID]; if (tTd(95, 5)) sm_syslog(LOG_DEBUG, NOQID, "AUTH authid '%s'", *result); if (len != NULL) *len = *result != NULL ? strlen(*result) : 0; break; case SASL_CB_LANGUAGE: *result = NULL; if (len != NULL) *len = 0; break; default: return SASL_BADPARAM; } return SASL_OK; } /* ** GETSECRET -- callback to get password ** ** Parameters: ** conn -- connection information ** context -- sai ** id -- what to do ** psecret -- (pointer to) result ** ** Returns: ** OK/failure values */ static int getsecret(conn, context, id, psecret) sasl_conn_t *conn; SM_UNUSED(void *context); int id; sasl_secret_t **psecret; { int len; char *authpass; MCI *mci; if (conn == NULL || psecret == NULL || id != SASL_CB_PASS) return SASL_BADPARAM; mci = (MCI *) context; authpass = mci->mci_sai[SASL_PASSWORD]; len = strlen(authpass); /* ** use an rpool because we are responsible for free()ing the secret, ** but we can't free() it until after the auth completes */ *psecret = (sasl_secret_t *) sm_rpool_malloc(mci->mci_rpool, sizeof(sasl_secret_t) + len + 1); if (*psecret == NULL) return SASL_FAIL; (void) sm_strlcpy((char *) (*psecret)->data, authpass, len + 1); (*psecret)->len = (unsigned long) len; return SASL_OK; } # else /* SASL >= 20000 */ /* ** GETSIMPLE -- callback to get userid or authid ** ** Parameters: ** context -- sai ** id -- what to do ** result -- (pointer to) result ** len -- (pointer to) length of result ** ** Returns: ** OK/failure values */ static int getsimple(context, id, result, len) void *context; int id; const char **result; unsigned *len; { char *h, *s; # if SASL > 10509 bool addrealm; # endif /* SASL > 10509 */ size_t l; SASL_AI_T *sai; char *authid = NULL; if (result == NULL || context == NULL) return SASL_BADPARAM; sai = (SASL_AI_T *) context; /* ** Unfortunately it is not clear whether this routine should ** return a copy of a string or just a pointer to a string. ** The Cyrus-SASL plugins treat these return values differently, e.g., ** plugins/cram.c free()s authid, plugings/digestmd5.c does not. ** The best solution to this problem is to fix Cyrus-SASL, but it ** seems there is nobody who creates patches... Hello CMU!? ** The second best solution is to have flags that tell this routine ** whether to return an malloc()ed copy. ** The next best solution is to always return an malloc()ed copy, ** and suffer from some memory leak, which is ugly for persistent ** queue runners. ** For now we go with the last solution... ** We can't use rpools (which would avoid this particular problem) ** as explained in sasl.c. */ switch (id) { case SASL_CB_USER: l = strlen((*sai)[SASL_USER]) + 1; s = sm_sasl_malloc(l); if (s == NULL) { if (len != NULL) *len = 0; *result = NULL; return SASL_NOMEM; } (void) sm_strlcpy(s, (*sai)[SASL_USER], l); *result = s; if (tTd(95, 5)) sm_syslog(LOG_DEBUG, NOQID, "AUTH username '%s'", *result); if (len != NULL) *len = *result != NULL ? strlen(*result) : 0; break; case SASL_CB_AUTHNAME: h = (*sai)[SASL_AUTHID]; # if SASL > 10509 /* XXX maybe other mechanisms too?! */ addrealm = (*sai)[SASL_MECH] != NULL && sm_strcasecmp((*sai)[SASL_MECH], "CRAM-MD5") == 0; /* ** Add realm to authentication id unless authid contains ** '@' (i.e., a realm) or the default realm is empty. */ if (addrealm && h != NULL && strchr(h, '@') == NULL) { /* has this been done before? */ if ((*sai)[SASL_ID_REALM] == NULL) { char *realm; realm = (*sai)[SASL_DEFREALM]; /* do not add an empty realm */ if (*realm == '\0') { authid = h; (*sai)[SASL_ID_REALM] = NULL; } else { l = strlen(h) + strlen(realm) + 2; /* should use rpool, but from where? */ authid = sm_sasl_malloc(l); if (authid != NULL) { (void) sm_snprintf(authid, l, "%s@%s", h, realm); (*sai)[SASL_ID_REALM] = authid; } else { authid = h; (*sai)[SASL_ID_REALM] = NULL; } } } else authid = (*sai)[SASL_ID_REALM]; } else # endif /* SASL > 10509 */ authid = h; l = strlen(authid) + 1; s = sm_sasl_malloc(l); if (s == NULL) { if (len != NULL) *len = 0; *result = NULL; return SASL_NOMEM; } (void) sm_strlcpy(s, authid, l); *result = s; if (tTd(95, 5)) sm_syslog(LOG_DEBUG, NOQID, "AUTH authid '%s'", *result); if (len != NULL) *len = authid ? strlen(authid) : 0; break; case SASL_CB_LANGUAGE: *result = NULL; if (len != NULL) *len = 0; break; default: return SASL_BADPARAM; } return SASL_OK; } /* ** GETSECRET -- callback to get password ** ** Parameters: ** conn -- connection information ** context -- sai ** id -- what to do ** psecret -- (pointer to) result ** ** Returns: ** OK/failure values */ static int getsecret(conn, context, id, psecret) sasl_conn_t *conn; SM_UNUSED(void *context); int id; sasl_secret_t **psecret; { int len; char *authpass; SASL_AI_T *sai; if (conn == NULL || psecret == NULL || id != SASL_CB_PASS) return SASL_BADPARAM; sai = (SASL_AI_T *) context; authpass = (*sai)[SASL_PASSWORD]; len = strlen(authpass); *psecret = (sasl_secret_t *) sm_sasl_malloc(sizeof(sasl_secret_t) + len + 1); if (*psecret == NULL) return SASL_FAIL; (void) sm_strlcpy((*psecret)->data, authpass, len + 1); (*psecret)->len = (unsigned long) len; return SASL_OK; } # endif /* SASL >= 20000 */ /* ** SAFESASLFILE -- callback for sasl: is file safe? ** ** Parameters: ** context -- pointer to context between invocations (unused) ** file -- name of file to check ** type -- type of file to check ** ** Returns: ** SASL_OK -- file can be used ** SASL_CONTINUE -- don't use file ** SASL_FAIL -- failure (not used here) ** */ int #if SASL > 10515 safesaslfile(context, file, type) #else /* SASL > 10515 */ safesaslfile(context, file) #endif /* SASL > 10515 */ void *context; # if SASL >= 20000 const char *file; # else /* SASL >= 20000 */ char *file; # endif /* SASL >= 20000 */ #if SASL > 10515 # if SASL >= 20000 sasl_verify_type_t type; # else /* SASL >= 20000 */ int type; # endif /* SASL >= 20000 */ #endif /* SASL > 10515 */ { long sff; int r; #if SASL <= 10515 size_t len; #endif /* SASL <= 10515 */ char *p; if (file == NULL || *file == '\0') return SASL_OK; sff = SFF_SAFEDIRPATH|SFF_NOWLINK|SFF_NOWWFILES|SFF_ROOTOK; #if SASL <= 10515 if ((p = strrchr(file, '/')) == NULL) p = file; else ++p; /* everything beside libs and .conf files must not be readable */ len = strlen(p); if ((len <= 3 || strncmp(p, "lib", 3) != 0) && (len <= 5 || strncmp(p + len - 5, ".conf", 5) != 0)) { if (!bitnset(DBS_GROUPREADABLESASLDBFILE, DontBlameSendmail)) sff |= SFF_NORFILES; if (!bitnset(DBS_GROUPWRITABLESASLDBFILE, DontBlameSendmail)) sff |= SFF_NOGWFILES; } #else /* SASL <= 10515 */ /* files containing passwords should be not readable */ if (type == SASL_VRFY_PASSWD) { if (bitnset(DBS_GROUPREADABLESASLDBFILE, DontBlameSendmail)) sff |= SFF_NOWRFILES; else sff |= SFF_NORFILES; if (!bitnset(DBS_GROUPWRITABLESASLDBFILE, DontBlameSendmail)) sff |= SFF_NOGWFILES; } #endif /* SASL <= 10515 */ p = (char *) file; if ((r = safefile(p, RunAsUid, RunAsGid, RunAsUserName, sff, S_IRUSR, NULL)) == 0) return SASL_OK; if (LogLevel > (r != ENOENT ? 8 : 10)) sm_syslog(LOG_WARNING, NOQID, "error: safesasl(%s) failed: %s", p, sm_errstring(r)); return SASL_CONTINUE; } /* ** SASLGETREALM -- return the realm for SASL ** ** return the realm for the client ** ** Parameters: ** context -- context shared between invocations ** availrealms -- list of available realms ** {realm, realm, ...} ** result -- pointer to result ** ** Returns: ** failure/success */ static int saslgetrealm(context, id, availrealms, result) void *context; int id; const char **availrealms; const char **result; { char *r; SASL_AI_T *sai; sai = (SASL_AI_T *) context; if (sai == NULL) return SASL_FAIL; r = (*sai)[SASL_DEFREALM]; if (LogLevel > 12) sm_syslog(LOG_INFO, NOQID, "AUTH=client, realm=%s, available realms=%s", r == NULL ? "" : r, (availrealms == NULL || *availrealms == NULL) ? "" : *availrealms); /* check whether context is in list */ if (availrealms != NULL && *availrealms != NULL) { if (iteminlist(context, (char *)(*availrealms + 1), " ,}") == NULL) { if (LogLevel > 8) sm_syslog(LOG_ERR, NOQID, "AUTH=client, realm=%s not in list=%s", r, *availrealms); return SASL_FAIL; } } *result = r; return SASL_OK; } /* ** ITEMINLIST -- does item appear in list? ** ** Check whether item appears in list (which must be separated by a ** character in delim) as a "word", i.e. it must appear at the begin ** of the list or after a space, and it must end with a space or the ** end of the list. ** ** Parameters: ** item -- item to search. ** list -- list of items. ** delim -- list of delimiters. ** ** Returns: ** pointer to occurrence (NULL if not found). */ char * iteminlist(item, list, delim) char *item; char *list; char *delim; { char *s; int len; if (list == NULL || *list == '\0') return NULL; if (item == NULL || *item == '\0') return NULL; s = list; len = strlen(item); while (s != NULL && *s != '\0') { if (sm_strncasecmp(s, item, len) == 0 && (s[len] == '\0' || strchr(delim, s[len]) != NULL)) return s; s = strpbrk(s, delim); if (s != NULL) while (*++s == ' ') continue; } return NULL; } /* ** REMOVEMECH -- remove item [rem] from list [list] ** ** Parameters: ** rem -- item to remove ** list -- list of items ** rpool -- resource pool from which result is allocated. ** ** Returns: ** pointer to new list (NULL in case of error). */ static char * removemech(rem, list, rpool) char *rem; char *list; SM_RPOOL_T *rpool; { char *ret; char *needle; int len; if (list == NULL) return NULL; if (rem == NULL || *rem == '\0') { /* take out what? */ return NULL; } /* find the item in the list */ if ((needle = iteminlist(rem, list, " ")) == NULL) { /* not in there: return original */ return list; } /* length of string without rem */ len = strlen(list) - strlen(rem); if (len <= 0) { ret = (char *) sm_rpool_malloc_x(rpool, 1); *ret = '\0'; return ret; } ret = (char *) sm_rpool_malloc_x(rpool, len); memset(ret, '\0', len); /* copy from start to removed item */ memcpy(ret, list, needle - list); /* length of rest of string past removed item */ len = strlen(needle) - strlen(rem) - 1; if (len > 0) { /* not last item -- copy into string */ memcpy(ret + (needle - list), list + (needle - list) + strlen(rem) + 1, len); } else ret[(needle - list) - 1] = '\0'; return ret; } /* ** ATTEMPTAUTH -- try to AUTHenticate using one mechanism ** ** Parameters: ** m -- the mailer. ** mci -- the mailer connection structure. ** e -- the envelope (including the sender to specify). ** sai - sasl authinfo ** ** Returns: ** EX_OK -- authentication was successful. ** EX_NOPERM -- authentication failed. ** EX_IOERR -- authentication dialogue failed (I/O problem?). ** EX_TEMPFAIL -- temporary failure. ** */ static int attemptauth(m, mci, e, sai) MAILER *m; MCI *mci; ENVELOPE *e; SASL_AI_T *sai; { int saslresult, smtpresult; # if SASL >= 20000 sasl_ssf_t ssf; const char *auth_id; const char *out; # else /* SASL >= 20000 */ sasl_external_properties_t ssf; char *out; # endif /* SASL >= 20000 */ unsigned int outlen; sasl_interact_t *client_interact = NULL; char *mechusing; sasl_security_properties_t ssp; /* MUST NOT be a multiple of 4: bug in some sasl_encode64() versions */ char in64[MAXOUTLEN + 1]; #if NETINET || (NETINET6 && SASL >= 20000) extern SOCKADDR CurHostAddr; #endif /* NETINET || (NETINET6 && SASL >= 20000) */ /* no mechanism selected (yet) */ (*sai)[SASL_MECH] = NULL; /* dispose old connection */ if (mci->mci_conn != NULL) sasl_dispose(&(mci->mci_conn)); /* make a new client sasl connection */ # if SASL >= 20000 /* ** We provide the callbacks again because global callbacks in ** sasl_client_init() are ignored if SASL has been initialized ** before, for example, by a library such as libnss-ldap. */ saslresult = sasl_client_new(bitnset(M_LMTP, m->m_flags) ? "lmtp" : "smtp", CurHostName, NULL, NULL, callbacks, 0, &mci->mci_conn); # else /* SASL >= 20000 */ saslresult = sasl_client_new(bitnset(M_LMTP, m->m_flags) ? "lmtp" : "smtp", CurHostName, NULL, 0, &mci->mci_conn); # endif /* SASL >= 20000 */ if (saslresult != SASL_OK) return EX_TEMPFAIL; /* set properties */ (void) memset(&ssp, '\0', sizeof(ssp)); /* XXX should these be options settable via .cf ? */ ssp.max_ssf = MaxSLBits; ssp.maxbufsize = MAXOUTLEN; # if 0 ssp.security_flags = SASL_SEC_NOPLAINTEXT; # endif /* 0 */ saslresult = sasl_setprop(mci->mci_conn, SASL_SEC_PROPS, &ssp); if (saslresult != SASL_OK) return EX_TEMPFAIL; # if SASL >= 20000 /* external security strength factor, authentication id */ ssf = 0; auth_id = NULL; # if STARTTLS out = macvalue(macid("{cert_subject}"), e); if (out != NULL && *out != '\0') auth_id = out; out = macvalue(macid("{cipher_bits}"), e); if (out != NULL && *out != '\0') ssf = atoi(out); # endif /* STARTTLS */ saslresult = sasl_setprop(mci->mci_conn, SASL_SSF_EXTERNAL, &ssf); if (saslresult != SASL_OK) return EX_TEMPFAIL; saslresult = sasl_setprop(mci->mci_conn, SASL_AUTH_EXTERNAL, auth_id); if (saslresult != SASL_OK) return EX_TEMPFAIL; # if NETINET || NETINET6 /* set local/remote ipv4 addresses */ if (mci->mci_out != NULL && ( # if NETINET6 CurHostAddr.sa.sa_family == AF_INET6 || # endif /* NETINET6 */ CurHostAddr.sa.sa_family == AF_INET)) { SOCKADDR_LEN_T addrsize; SOCKADDR saddr_l; char localip[60], remoteip[60]; switch (CurHostAddr.sa.sa_family) { case AF_INET: addrsize = sizeof(struct sockaddr_in); break; # if NETINET6 case AF_INET6: addrsize = sizeof(struct sockaddr_in6); break; # endif /* NETINET6 */ default: break; } if (iptostring(&CurHostAddr, addrsize, remoteip, sizeof(remoteip))) { if (sasl_setprop(mci->mci_conn, SASL_IPREMOTEPORT, remoteip) != SASL_OK) return EX_TEMPFAIL; } addrsize = sizeof(saddr_l); if (getsockname(sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL), (struct sockaddr *) &saddr_l, &addrsize) == 0) { if (iptostring(&saddr_l, addrsize, localip, sizeof(localip))) { if (sasl_setprop(mci->mci_conn, SASL_IPLOCALPORT, localip) != SASL_OK) return EX_TEMPFAIL; } } } # endif /* NETINET || NETINET6 */ /* start client side of sasl */ saslresult = sasl_client_start(mci->mci_conn, mci->mci_saslcap, &client_interact, &out, &outlen, (const char **) &mechusing); # else /* SASL >= 20000 */ /* external security strength factor, authentication id */ ssf.ssf = 0; ssf.auth_id = NULL; # if STARTTLS out = macvalue(macid("{cert_subject}"), e); if (out != NULL && *out != '\0') ssf.auth_id = out; out = macvalue(macid("{cipher_bits}"), e); if (out != NULL && *out != '\0') ssf.ssf = atoi(out); # endif /* STARTTLS */ saslresult = sasl_setprop(mci->mci_conn, SASL_SSF_EXTERNAL, &ssf); if (saslresult != SASL_OK) return EX_TEMPFAIL; # if NETINET /* set local/remote ipv4 addresses */ if (mci->mci_out != NULL && CurHostAddr.sa.sa_family == AF_INET) { SOCKADDR_LEN_T addrsize; struct sockaddr_in saddr_l; if (sasl_setprop(mci->mci_conn, SASL_IP_REMOTE, (struct sockaddr_in *) &CurHostAddr) != SASL_OK) return EX_TEMPFAIL; addrsize = sizeof(struct sockaddr_in); if (getsockname(sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL), (struct sockaddr *) &saddr_l, &addrsize) == 0) { if (sasl_setprop(mci->mci_conn, SASL_IP_LOCAL, &saddr_l) != SASL_OK) return EX_TEMPFAIL; } } # endif /* NETINET */ /* start client side of sasl */ saslresult = sasl_client_start(mci->mci_conn, mci->mci_saslcap, NULL, &client_interact, &out, &outlen, (const char **) &mechusing); # endif /* SASL >= 20000 */ if (saslresult != SASL_OK && saslresult != SASL_CONTINUE) { if (saslresult == SASL_NOMECH && LogLevel > 8) { sm_syslog(LOG_NOTICE, e->e_id, "AUTH=client, available mechanisms do not fulfill requirements"); } return EX_TEMPFAIL; } /* just point current mechanism to the data in the sasl library */ (*sai)[SASL_MECH] = mechusing; /* send the info across the wire */ if (out == NULL /* login and digest-md5 up to 1.5.28 set out="" */ || (outlen == 0 && (sm_strcasecmp(mechusing, "LOGIN") == 0 || sm_strcasecmp(mechusing, "DIGEST-MD5") == 0)) ) { /* no initial response */ smtpmessage("AUTH %s", m, mci, mechusing); } else if (outlen == 0) { /* ** zero-length initial response, per RFC 2554 4.: ** "Unlike a zero-length client answer to a 334 reply, a zero- ** length initial response is sent as a single equals sign" */ smtpmessage("AUTH %s =", m, mci, mechusing); } else { saslresult = sasl_encode64(out, outlen, in64, sizeof(in64), NULL); if (saslresult != SASL_OK) /* internal error */ { if (LogLevel > 8) sm_syslog(LOG_ERR, e->e_id, "encode64 for AUTH failed"); return EX_TEMPFAIL; } smtpmessage("AUTH %s %s", m, mci, mechusing, in64); } # if SASL < 20000 sm_sasl_free(out); /* XXX only if no rpool is used */ # endif /* SASL < 20000 */ /* get the reply */ smtpresult = reply(m, mci, e, TimeOuts.to_auth, getsasldata, NULL, XS_AUTH); for (;;) { /* check return code from server */ if (smtpresult == 235) { macdefine(&mci->mci_macro, A_TEMP, macid("{auth_type}"), mechusing); return EX_OK; } if (smtpresult == -1) return EX_IOERR; if (REPLYTYPE(smtpresult) == 5) return EX_NOPERM; /* ugly, but ... */ if (REPLYTYPE(smtpresult) != 3) { /* should we fail deliberately, see RFC 2554 4. ? */ /* smtpmessage("*", m, mci); */ return EX_TEMPFAIL; } saslresult = sasl_client_step(mci->mci_conn, mci->mci_sasl_string, mci->mci_sasl_string_len, &client_interact, &out, &outlen); if (saslresult != SASL_OK && saslresult != SASL_CONTINUE) { if (tTd(95, 5)) sm_dprintf("AUTH FAIL=%s (%d)\n", sasl_errstring(saslresult, NULL, NULL), saslresult); /* fail deliberately, see RFC 2554 4. */ smtpmessage("*", m, mci); /* ** but we should only fail for this authentication ** mechanism; how to do that? */ smtpresult = reply(m, mci, e, TimeOuts.to_auth, getsasldata, NULL, XS_AUTH); return EX_NOPERM; } if (outlen > 0) { saslresult = sasl_encode64(out, outlen, in64, sizeof(in64), NULL); if (saslresult != SASL_OK) { /* give an error reply to the other side! */ smtpmessage("*", m, mci); return EX_TEMPFAIL; } } else in64[0] = '\0'; # if SASL < 20000 sm_sasl_free(out); /* XXX only if no rpool is used */ # endif /* SASL < 20000 */ smtpmessage("%s", m, mci, in64); smtpresult = reply(m, mci, e, TimeOuts.to_auth, getsasldata, NULL, XS_AUTH); } /* NOTREACHED */ } /* ** SMTPAUTH -- try to AUTHenticate ** ** This will try mechanisms in the order the sasl library decided until: ** - there are no more mechanisms ** - a mechanism succeeds ** - the sasl library fails initializing ** ** Parameters: ** m -- the mailer. ** mci -- the mailer connection info. ** e -- the envelope. ** ** Returns: ** EX_OK -- authentication was successful ** EX_UNAVAILABLE -- authentication not possible, e.g., ** no data available. ** EX_NOPERM -- authentication failed. ** EX_TEMPFAIL -- temporary failure. ** ** Notice: AuthInfo is used for all connections, hence we must ** return EX_TEMPFAIL only if we really want to retry, i.e., ** iff getauth() tempfailed or getauth() was used and ** authentication tempfailed. */ int smtpauth(m, mci, e) MAILER *m; MCI *mci; ENVELOPE *e; { int result; int i; bool usedgetauth; mci->mci_sasl_auth = false; for (i = 0; i < SASL_MECH ; i++) mci->mci_sai[i] = NULL; result = getauth(mci, e, &(mci->mci_sai)); if (result == EX_TEMPFAIL) return result; usedgetauth = true; /* no data available: don't try to authenticate */ if (result == EX_OK && mci->mci_sai[SASL_AUTHID] == NULL) return result; if (result != EX_OK) { if (SASLInfo == NULL) return EX_UNAVAILABLE; /* read authinfo from file */ result = readauth(SASLInfo, true, &(mci->mci_sai), mci->mci_rpool); if (result != EX_OK) return result; usedgetauth = false; } /* check whether sufficient data is available */ if (mci->mci_sai[SASL_PASSWORD] == NULL || *(mci->mci_sai)[SASL_PASSWORD] == '\0') return EX_UNAVAILABLE; if ((mci->mci_sai[SASL_AUTHID] == NULL || *(mci->mci_sai)[SASL_AUTHID] == '\0') && (mci->mci_sai[SASL_USER] == NULL || *(mci->mci_sai)[SASL_USER] == '\0')) return EX_UNAVAILABLE; /* set the context for the callback function to sai */ # if SASL >= 20000 callbacks[CB_PASS_IDX].context = (void *) mci; # else /* SASL >= 20000 */ callbacks[CB_PASS_IDX].context = (void *) &mci->mci_sai; # endif /* SASL >= 20000 */ callbacks[CB_USER_IDX].context = (void *) &mci->mci_sai; callbacks[CB_AUTHNAME_IDX].context = (void *) &mci->mci_sai; callbacks[CB_GETREALM_IDX].context = (void *) &mci->mci_sai; #if 0 callbacks[CB_SAFESASL_IDX].context = (void *) &mci->mci_sai; #endif /* 0 */ /* set default value for realm */ if ((mci->mci_sai)[SASL_DEFREALM] == NULL) (mci->mci_sai)[SASL_DEFREALM] = sm_rpool_strdup_x(e->e_rpool, macvalue('j', CurEnv)); /* set default value for list of mechanism to use */ if ((mci->mci_sai)[SASL_MECHLIST] == NULL || *(mci->mci_sai)[SASL_MECHLIST] == '\0') (mci->mci_sai)[SASL_MECHLIST] = AuthMechanisms; /* create list of mechanisms to try */ mci->mci_saslcap = intersect((mci->mci_sai)[SASL_MECHLIST], mci->mci_saslcap, mci->mci_rpool); /* initialize sasl client library */ result = init_sasl_client(); if (result != SASL_OK) return usedgetauth ? EX_TEMPFAIL : EX_UNAVAILABLE; do { result = attemptauth(m, mci, e, &(mci->mci_sai)); if (result == EX_OK) mci->mci_sasl_auth = true; else if (result == EX_TEMPFAIL || result == EX_NOPERM) { mci->mci_saslcap = removemech((mci->mci_sai)[SASL_MECH], mci->mci_saslcap, mci->mci_rpool); if (mci->mci_saslcap == NULL || *(mci->mci_saslcap) == '\0') return usedgetauth ? result : EX_UNAVAILABLE; } else return result; } while (result != EX_OK); return result; } #endif /* SASL */ /* ** SMTPMAILFROM -- send MAIL command ** ** Parameters: ** m -- the mailer. ** mci -- the mailer connection structure. ** e -- the envelope (including the sender to specify). */ int smtpmailfrom(m, mci, e) MAILER *m; MCI *mci; ENVELOPE *e; { int r; char *bufp; char *bodytype; char *enhsc; char buf[MAXNAME + 1]; char optbuf[MAXLINE]; if (tTd(18, 2)) sm_dprintf("smtpmailfrom: CurHost=%s\n", CurHostName); enhsc = NULL; /* ** Check if connection is gone, if so ** it's a tempfail and we use mci_errno ** for the reason. */ if (mci->mci_state == MCIS_CLOSED) { errno = mci->mci_errno; return EX_TEMPFAIL; } /* set up appropriate options to include */ if (bitset(MCIF_SIZE, mci->mci_flags) && e->e_msgsize > 0) { (void) sm_snprintf(optbuf, sizeof(optbuf), " SIZE=%ld", e->e_msgsize); bufp = &optbuf[strlen(optbuf)]; } else { optbuf[0] = '\0'; bufp = optbuf; } bodytype = e->e_bodytype; if (bitset(MCIF_8BITMIME, mci->mci_flags)) { if (bodytype == NULL && bitset(MM_MIME8BIT, MimeMode) && bitset(EF_HAS8BIT, e->e_flags) && !bitset(EF_DONT_MIME, e->e_flags) && !bitnset(M_8BITS, m->m_flags)) bodytype = "8BITMIME"; if (bodytype != NULL && SPACELEFT(optbuf, bufp) > strlen(bodytype) + 7) { (void) sm_snprintf(bufp, SPACELEFT(optbuf, bufp), " BODY=%s", bodytype); bufp += strlen(bufp); } } else if (bitnset(M_8BITS, m->m_flags) || !bitset(EF_HAS8BIT, e->e_flags) || bitset(MCIF_8BITOK, mci->mci_flags)) { /* EMPTY */ /* just pass it through */ } #if MIME8TO7 else if (bitset(MM_CVTMIME, MimeMode) && !bitset(EF_DONT_MIME, e->e_flags) && (!bitset(MM_PASS8BIT, MimeMode) || bitset(EF_IS_MIME, e->e_flags))) { /* must convert from 8bit MIME format to 7bit encoded */ mci->mci_flags |= MCIF_CVT8TO7; } #endif /* MIME8TO7 */ else if (!bitset(MM_PASS8BIT, MimeMode)) { /* cannot just send a 8-bit version */ extern char MsgBuf[]; usrerrenh("5.6.3", "%s does not support 8BITMIME", CurHostName); mci_setstat(mci, EX_NOTSTICKY, "5.6.3", MsgBuf); return EX_DATAERR; } if (bitset(MCIF_DSN, mci->mci_flags)) { if (e->e_envid != NULL && SPACELEFT(optbuf, bufp) > strlen(e->e_envid) + 7) { (void) sm_snprintf(bufp, SPACELEFT(optbuf, bufp), " ENVID=%s", e->e_envid); bufp += strlen(bufp); } /* RET= parameter */ if (bitset(EF_RET_PARAM, e->e_flags) && SPACELEFT(optbuf, bufp) > 9) { (void) sm_snprintf(bufp, SPACELEFT(optbuf, bufp), " RET=%s", bitset(EF_NO_BODY_RETN, e->e_flags) ? "HDRS" : "FULL"); bufp += strlen(bufp); } } if (bitset(MCIF_AUTH, mci->mci_flags) && e->e_auth_param != NULL && SPACELEFT(optbuf, bufp) > strlen(e->e_auth_param) + 7 #if SASL && (!bitset(SASL_AUTH_AUTH, SASLOpts) || mci->mci_sasl_auth) #endif /* SASL */ ) { (void) sm_snprintf(bufp, SPACELEFT(optbuf, bufp), " AUTH=%s", e->e_auth_param); bufp += strlen(bufp); } /* ** 17 is the max length required, we could use log() to compute ** the exact length (and check IS_DLVR_TRACE()) */ if (bitset(MCIF_DLVR_BY, mci->mci_flags) && IS_DLVR_BY(e) && SPACELEFT(optbuf, bufp) > 17) { long dby; /* ** Avoid problems with delays (for R) since the check ** in deliver() whether min-deliver-time is sufficient. ** Alternatively we could pass the computed time to this ** function. */ dby = e->e_deliver_by - (curtime() - e->e_ctime); if (dby <= 0 && IS_DLVR_RETURN(e)) dby = mci->mci_min_by <= 0 ? 1 : mci->mci_min_by; (void) sm_snprintf(bufp, SPACELEFT(optbuf, bufp), " BY=%ld;%c%s", dby, IS_DLVR_RETURN(e) ? 'R' : 'N', IS_DLVR_TRACE(e) ? "T" : ""); bufp += strlen(bufp); } /* ** Send the MAIL command. ** Designates the sender. */ mci->mci_state = MCIS_MAIL; if (bitset(EF_RESPONSE, e->e_flags) && !bitnset(M_NO_NULL_FROM, m->m_flags)) buf[0] = '\0'; else expand("\201g", buf, sizeof(buf), e); if (buf[0] == '<') { /* strip off (put back on below) */ bufp = &buf[strlen(buf) - 1]; if (*bufp == '>') *bufp = '\0'; bufp = &buf[1]; } else bufp = buf; if (bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags) || !bitnset(M_FROMPATH, m->m_flags)) { smtpmessage("MAIL From:<%s>%s", m, mci, bufp, optbuf); } else { smtpmessage("MAIL From:<@%s%c%s>%s", m, mci, MyHostName, *bufp == '@' ? ',' : ':', bufp, optbuf); } SmtpPhase = mci->mci_phase = "client MAIL"; sm_setproctitle(true, e, "%s %s: %s", qid_printname(e), CurHostName, mci->mci_phase); r = reply(m, mci, e, TimeOuts.to_mail, NULL, &enhsc, XS_MAIL); if (r < 0) { /* communications failure */ mci_setstat(mci, EX_TEMPFAIL, "4.4.2", NULL); return EX_TEMPFAIL; } else if (r == SMTPCLOSING) { /* service shutting down: handled by reply() */ return EX_TEMPFAIL; } else if (REPLYTYPE(r) == 4) { mci_setstat(mci, EX_NOTSTICKY, ENHSCN(enhsc, smtptodsn(r)), SmtpReplyBuffer); return EX_TEMPFAIL; } else if (REPLYTYPE(r) == 2) { return EX_OK; } else if (r == 501) { /* syntax error in arguments */ mci_setstat(mci, EX_NOTSTICKY, ENHSCN(enhsc, "5.5.2"), SmtpReplyBuffer); return EX_DATAERR; } else if (r == 553) { /* mailbox name not allowed */ mci_setstat(mci, EX_NOTSTICKY, ENHSCN(enhsc, "5.1.3"), SmtpReplyBuffer); return EX_DATAERR; } else if (r == 552) { /* exceeded storage allocation */ mci_setstat(mci, EX_NOTSTICKY, ENHSCN(enhsc, "5.3.4"), SmtpReplyBuffer); if (bitset(MCIF_SIZE, mci->mci_flags)) e->e_flags |= EF_NO_BODY_RETN; return EX_UNAVAILABLE; } else if (REPLYTYPE(r) == 5) { /* unknown error */ mci_setstat(mci, EX_NOTSTICKY, ENHSCN(enhsc, "5.0.0"), SmtpReplyBuffer); return EX_UNAVAILABLE; } if (LogLevel > 1) { sm_syslog(LOG_CRIT, e->e_id, "%.100s: SMTP MAIL protocol error: %s", CurHostName, shortenstring(SmtpReplyBuffer, 403)); } /* protocol error -- close up */ mci_setstat(mci, EX_PROTOCOL, ENHSCN(enhsc, "5.5.1"), SmtpReplyBuffer); smtpquit(m, mci, e); return EX_PROTOCOL; } /* ** SMTPRCPT -- designate recipient. ** ** Parameters: ** to -- address of recipient. ** m -- the mailer we are sending to. ** mci -- the connection info for this transaction. ** e -- the envelope for this transaction. ** ** Returns: ** exit status corresponding to recipient status. ** ** Side Effects: ** Sends the mail via SMTP. */ int smtprcpt(to, m, mci, e, ctladdr, xstart) ADDRESS *to; register MAILER *m; MCI *mci; ENVELOPE *e; ADDRESS *ctladdr; time_t xstart; { char *bufp; char optbuf[MAXLINE]; #if PIPELINING /* ** If there is status waiting from the other end, read it. ** This should normally happen because of SMTP pipelining. */ while (mci->mci_nextaddr != NULL && sm_io_getinfo(mci->mci_in, SM_IO_IS_READABLE, NULL) > 0) { int r; r = smtprcptstat(mci->mci_nextaddr, m, mci, e); if (r != EX_OK) { markfailure(e, mci->mci_nextaddr, mci, r, false); giveresponse(r, mci->mci_nextaddr->q_status, m, mci, ctladdr, xstart, e, to); } mci->mci_nextaddr = mci->mci_nextaddr->q_pchain; } #endif /* PIPELINING */ /* ** Check if connection is gone, if so ** it's a tempfail and we use mci_errno ** for the reason. */ if (mci->mci_state == MCIS_CLOSED) { errno = mci->mci_errno; return EX_TEMPFAIL; } optbuf[0] = '\0'; bufp = optbuf; /* ** Warning: in the following it is assumed that the free space ** in bufp is sizeof(optbuf) */ if (bitset(MCIF_DSN, mci->mci_flags)) { if (IS_DLVR_NOTIFY(e) && !bitset(MCIF_DLVR_BY, mci->mci_flags)) { /* RFC 2852: 4.1.4.2 */ if (!bitset(QHASNOTIFY, to->q_flags)) to->q_flags |= QPINGONFAILURE|QPINGONDELAY|QHASNOTIFY; else if (bitset(QPINGONSUCCESS, to->q_flags) || bitset(QPINGONFAILURE, to->q_flags) || bitset(QPINGONDELAY, to->q_flags)) to->q_flags |= QPINGONDELAY; } /* NOTIFY= parameter */ if (bitset(QHASNOTIFY, to->q_flags) && bitset(QPRIMARY, to->q_flags) && !bitnset(M_LOCALMAILER, m->m_flags)) { bool firstone = true; (void) sm_strlcat(bufp, " NOTIFY=", sizeof(optbuf)); if (bitset(QPINGONSUCCESS, to->q_flags)) { (void) sm_strlcat(bufp, "SUCCESS", sizeof(optbuf)); firstone = false; } if (bitset(QPINGONFAILURE, to->q_flags)) { if (!firstone) (void) sm_strlcat(bufp, ",", sizeof(optbuf)); (void) sm_strlcat(bufp, "FAILURE", sizeof(optbuf)); firstone = false; } if (bitset(QPINGONDELAY, to->q_flags)) { if (!firstone) (void) sm_strlcat(bufp, ",", sizeof(optbuf)); (void) sm_strlcat(bufp, "DELAY", sizeof(optbuf)); firstone = false; } if (firstone) (void) sm_strlcat(bufp, "NEVER", sizeof(optbuf)); bufp += strlen(bufp); } /* ORCPT= parameter */ if (to->q_orcpt != NULL && SPACELEFT(optbuf, bufp) > strlen(to->q_orcpt) + 7) { (void) sm_snprintf(bufp, SPACELEFT(optbuf, bufp), " ORCPT=%s", to->q_orcpt); bufp += strlen(bufp); } } smtpmessage("RCPT To:<%s>%s", m, mci, to->q_user, optbuf); mci->mci_state = MCIS_RCPT; SmtpPhase = mci->mci_phase = "client RCPT"; sm_setproctitle(true, e, "%s %s: %s", qid_printname(e), CurHostName, mci->mci_phase); #if PIPELINING /* ** If running SMTP pipelining, we will pick up status later */ if (bitset(MCIF_PIPELINED, mci->mci_flags)) return EX_OK; #endif /* PIPELINING */ return smtprcptstat(to, m, mci, e); } /* ** SMTPRCPTSTAT -- get recipient status ** ** This is only called during SMTP pipelining ** ** Parameters: ** to -- address of recipient. ** m -- mailer being sent to. ** mci -- the mailer connection information. ** e -- the envelope for this message. ** ** Returns: ** EX_* -- protocol status */ static int smtprcptstat(to, m, mci, e) ADDRESS *to; MAILER *m; register MCI *mci; register ENVELOPE *e; { int r; int save_errno; char *enhsc; /* ** Check if connection is gone, if so ** it's a tempfail and we use mci_errno ** for the reason. */ if (mci->mci_state == MCIS_CLOSED) { errno = mci->mci_errno; return EX_TEMPFAIL; } enhsc = NULL; r = reply(m, mci, e, TimeOuts.to_rcpt, NULL, &enhsc, XS_RCPT); save_errno = errno; to->q_rstatus = sm_rpool_strdup_x(e->e_rpool, SmtpReplyBuffer); to->q_status = ENHSCN_RPOOL(enhsc, smtptodsn(r), e->e_rpool); if (!bitnset(M_LMTP, m->m_flags)) to->q_statmta = mci->mci_host; if (r < 0 || REPLYTYPE(r) == 4) { mci->mci_retryrcpt = true; errno = save_errno; return EX_TEMPFAIL; } else if (REPLYTYPE(r) == 2) { char *t; if ((t = mci->mci_tolist) != NULL) { char *p; *t++ = ','; for (p = to->q_paddr; *p != '\0'; *t++ = *p++) continue; *t = '\0'; mci->mci_tolist = t; } #if PIPELINING mci->mci_okrcpts++; #endif /* PIPELINING */ return EX_OK; } else if (r == 550) { to->q_status = ENHSCN_RPOOL(enhsc, "5.1.1", e->e_rpool); return EX_NOUSER; } else if (r == 551) { to->q_status = ENHSCN_RPOOL(enhsc, "5.1.6", e->e_rpool); return EX_NOUSER; } else if (r == 553) { to->q_status = ENHSCN_RPOOL(enhsc, "5.1.3", e->e_rpool); return EX_NOUSER; } else if (REPLYTYPE(r) == 5) { return EX_UNAVAILABLE; } if (LogLevel > 1) { sm_syslog(LOG_CRIT, e->e_id, "%.100s: SMTP RCPT protocol error: %s", CurHostName, shortenstring(SmtpReplyBuffer, 403)); } mci_setstat(mci, EX_PROTOCOL, ENHSCN(enhsc, "5.5.1"), SmtpReplyBuffer); return EX_PROTOCOL; } /* ** SMTPDATA -- send the data and clean up the transaction. ** ** Parameters: ** m -- mailer being sent to. ** mci -- the mailer connection information. ** e -- the envelope for this message. ** ** Returns: ** exit status corresponding to DATA command. */ int smtpdata(m, mci, e, ctladdr, xstart) MAILER *m; register MCI *mci; register ENVELOPE *e; ADDRESS *ctladdr; time_t xstart; { register int r; int rstat; int xstat; int timeout; char *enhsc; /* ** Check if connection is gone, if so ** it's a tempfail and we use mci_errno ** for the reason. */ if (mci->mci_state == MCIS_CLOSED) { errno = mci->mci_errno; return EX_TEMPFAIL; } enhsc = NULL; /* ** Send the data. ** First send the command and check that it is ok. ** Then send the data (if there are valid recipients). ** Follow it up with a dot to terminate. ** Finally get the results of the transaction. */ /* send the command and check ok to proceed */ smtpmessage("DATA", m, mci); #if PIPELINING if (mci->mci_nextaddr != NULL) { char *oldto = e->e_to; /* pick up any pending RCPT responses for SMTP pipelining */ while (mci->mci_nextaddr != NULL) { int r; e->e_to = mci->mci_nextaddr->q_paddr; r = smtprcptstat(mci->mci_nextaddr, m, mci, e); if (r != EX_OK) { markfailure(e, mci->mci_nextaddr, mci, r, false); giveresponse(r, mci->mci_nextaddr->q_status, m, mci, ctladdr, xstart, e, mci->mci_nextaddr); if (r == EX_TEMPFAIL) mci->mci_nextaddr->q_state = QS_RETRY; } mci->mci_nextaddr = mci->mci_nextaddr->q_pchain; } e->e_to = oldto; /* ** Connection might be closed in response to a RCPT command, ** i.e., the server responded with 421. In that case (at ** least) one RCPT has a temporary failure, hence we don't ** need to check mci_okrcpts (as it is done below) to figure ** out which error to return. */ if (mci->mci_state == MCIS_CLOSED) { errno = mci->mci_errno; return EX_TEMPFAIL; } } #endif /* PIPELINING */ /* now proceed with DATA phase */ SmtpPhase = mci->mci_phase = "client DATA 354"; mci->mci_state = MCIS_DATA; sm_setproctitle(true, e, "%s %s: %s", qid_printname(e), CurHostName, mci->mci_phase); r = reply(m, mci, e, TimeOuts.to_datainit, NULL, &enhsc, XS_DATA); if (r < 0 || REPLYTYPE(r) == 4) { if (r >= 0) smtpquit(m, mci, e); errno = mci->mci_errno; return EX_TEMPFAIL; } else if (REPLYTYPE(r) == 5) { smtprset(m, mci, e); #if PIPELINING if (mci->mci_okrcpts <= 0) return mci->mci_retryrcpt ? EX_TEMPFAIL : EX_UNAVAILABLE; #endif /* PIPELINING */ return EX_UNAVAILABLE; } else if (REPLYTYPE(r) != 3) { if (LogLevel > 1) { sm_syslog(LOG_CRIT, e->e_id, "%.100s: SMTP DATA-1 protocol error: %s", CurHostName, shortenstring(SmtpReplyBuffer, 403)); } smtprset(m, mci, e); mci_setstat(mci, EX_PROTOCOL, ENHSCN(enhsc, "5.5.1"), SmtpReplyBuffer); #if PIPELINING if (mci->mci_okrcpts <= 0) return mci->mci_retryrcpt ? EX_TEMPFAIL : EX_PROTOCOL; #endif /* PIPELINING */ return EX_PROTOCOL; } #if PIPELINING if (mci->mci_okrcpts > 0) { #endif /* PIPELINING */ /* ** Set timeout around data writes. Make it at least large ** enough for DNS timeouts on all recipients plus some fudge ** factor. The main thing is that it should not be infinite. */ if (tTd(18, 101)) { /* simulate a DATA timeout */ timeout = 10; } else timeout = DATA_PROGRESS_TIMEOUT * 1000; sm_io_setinfo(mci->mci_out, SM_IO_WHAT_TIMEOUT, &timeout); /* ** Output the actual message. */ if (!(*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER)) goto writeerr; if (tTd(18, 101)) { /* simulate a DATA timeout */ (void) sleep(2); } if (!(*e->e_putbody)(mci, e, NULL)) goto writeerr; /* ** Cleanup after sending message. */ #if PIPELINING } #endif /* PIPELINING */ #if _FFR_CATCH_BROKEN_MTAS if (sm_io_getinfo(mci->mci_in, SM_IO_IS_READABLE, NULL) > 0) { /* terminate the message */ (void) sm_io_fprintf(mci->mci_out, SM_TIME_DEFAULT, ".%s", m->m_eol); if (TrafficLogFile != NULL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d >>> .\n", (int) CurrentPid); if (Verbose) nmessage(">>> ."); sm_syslog(LOG_CRIT, e->e_id, "%.100s: SMTP DATA-1 protocol error: remote server returned response before final dot", CurHostName); mci->mci_errno = EIO; mci->mci_state = MCIS_ERROR; mci_setstat(mci, EX_PROTOCOL, "5.5.0", NULL); smtpquit(m, mci, e); return EX_PROTOCOL; } #endif /* _FFR_CATCH_BROKEN_MTAS */ if (sm_io_error(mci->mci_out)) { /* error during processing -- don't send the dot */ mci->mci_errno = EIO; mci->mci_state = MCIS_ERROR; mci_setstat(mci, EX_IOERR, "4.4.2", NULL); smtpquit(m, mci, e); return EX_IOERR; } /* terminate the message */ if (sm_io_fprintf(mci->mci_out, SM_TIME_DEFAULT, "%s.%s", bitset(MCIF_INLONGLINE, mci->mci_flags) ? m->m_eol : "", m->m_eol) == SM_IO_EOF) goto writeerr; if (TrafficLogFile != NULL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d >>> .\n", (int) CurrentPid); if (Verbose) nmessage(">>> ."); /* check for the results of the transaction */ SmtpPhase = mci->mci_phase = "client DATA status"; sm_setproctitle(true, e, "%s %s: %s", qid_printname(e), CurHostName, mci->mci_phase); if (bitnset(M_LMTP, m->m_flags)) return EX_OK; r = reply(m, mci, e, TimeOuts.to_datafinal, NULL, &enhsc, XS_EOM); if (r < 0) return EX_TEMPFAIL; if (mci->mci_state == MCIS_DATA) mci->mci_state = MCIS_OPEN; xstat = EX_NOTSTICKY; if (r == 452) rstat = EX_TEMPFAIL; else if (REPLYTYPE(r) == 4) rstat = xstat = EX_TEMPFAIL; else if (REPLYTYPE(r) == 2) rstat = xstat = EX_OK; else if (REPLYCLASS(r) != 5) rstat = xstat = EX_PROTOCOL; else if (REPLYTYPE(r) == 5) rstat = EX_UNAVAILABLE; else rstat = EX_PROTOCOL; mci_setstat(mci, xstat, ENHSCN(enhsc, smtptodsn(r)), SmtpReplyBuffer); if (bitset(MCIF_ENHSTAT, mci->mci_flags) && (r = isenhsc(SmtpReplyBuffer + 4, ' ')) > 0) r += 5; else r = 4; e->e_statmsg = sm_rpool_strdup_x(e->e_rpool, &SmtpReplyBuffer[r]); SmtpPhase = mci->mci_phase = "idle"; sm_setproctitle(true, e, "%s: %s", CurHostName, mci->mci_phase); if (rstat != EX_PROTOCOL) return rstat; if (LogLevel > 1) { sm_syslog(LOG_CRIT, e->e_id, "%.100s: SMTP DATA-2 protocol error: %s", CurHostName, shortenstring(SmtpReplyBuffer, 403)); } return rstat; writeerr: mci->mci_errno = errno; mci->mci_state = MCIS_ERROR; mci_setstat(mci, EX_TEMPFAIL, "4.4.2", NULL); /* ** If putbody() couldn't finish due to a timeout, ** rewind it here in the timeout handler. See ** comments at the end of putbody() for reasoning. */ if (e->e_dfp != NULL) (void) bfrewind(e->e_dfp); errno = mci->mci_errno; syserr("451 4.4.1 timeout writing message to %s", CurHostName); smtpquit(m, mci, e); return EX_TEMPFAIL; } /* ** SMTPGETSTAT -- get status code from DATA in LMTP ** ** Parameters: ** m -- the mailer to which we are sending the message. ** mci -- the mailer connection structure. ** e -- the current envelope. ** ** Returns: ** The exit status corresponding to the reply code. */ int smtpgetstat(m, mci, e) MAILER *m; MCI *mci; ENVELOPE *e; { int r; int off; int status, xstat; char *enhsc; enhsc = NULL; /* check for the results of the transaction */ r = reply(m, mci, e, TimeOuts.to_datafinal, NULL, &enhsc, XS_DATA2); if (r < 0) return EX_TEMPFAIL; xstat = EX_NOTSTICKY; if (REPLYTYPE(r) == 4) status = EX_TEMPFAIL; else if (REPLYTYPE(r) == 2) status = xstat = EX_OK; else if (REPLYCLASS(r) != 5) status = xstat = EX_PROTOCOL; else if (REPLYTYPE(r) == 5) status = EX_UNAVAILABLE; else status = EX_PROTOCOL; if (bitset(MCIF_ENHSTAT, mci->mci_flags) && (off = isenhsc(SmtpReplyBuffer + 4, ' ')) > 0) off += 5; else off = 4; e->e_statmsg = sm_rpool_strdup_x(e->e_rpool, &SmtpReplyBuffer[off]); mci_setstat(mci, xstat, ENHSCN(enhsc, smtptodsn(r)), SmtpReplyBuffer); if (LogLevel > 1 && status == EX_PROTOCOL) { sm_syslog(LOG_CRIT, e->e_id, "%.100s: SMTP DATA-3 protocol error: %s", CurHostName, shortenstring(SmtpReplyBuffer, 403)); } return status; } /* ** SMTPQUIT -- close the SMTP connection. ** ** Parameters: ** m -- a pointer to the mailer. ** mci -- the mailer connection information. ** e -- the current envelope. ** ** Returns: ** none. ** ** Side Effects: ** sends the final protocol and closes the connection. */ void smtpquit(m, mci, e) register MAILER *m; register MCI *mci; ENVELOPE *e; { bool oldSuprErrs = SuprErrs; int rcode; char *oldcurhost; if (mci->mci_state == MCIS_CLOSED) { mci_close(mci, "smtpquit:1"); return; } oldcurhost = CurHostName; CurHostName = mci->mci_host; /* XXX UGLY XXX */ if (CurHostName == NULL) CurHostName = MyHostName; #if PIPELINING mci->mci_okrcpts = 0; #endif /* PIPELINING */ /* ** Suppress errors here -- we may be processing a different ** job when we do the quit connection, and we don't want the ** new job to be penalized for something that isn't it's ** problem. */ SuprErrs = true; /* send the quit message if we haven't gotten I/O error */ if (mci->mci_state != MCIS_ERROR && mci->mci_state != MCIS_QUITING) { SmtpPhase = "client QUIT"; mci->mci_state = MCIS_QUITING; smtpmessage("QUIT", m, mci); (void) reply(m, mci, e, TimeOuts.to_quit, NULL, NULL, XS_QUIT); SuprErrs = oldSuprErrs; if (mci->mci_state == MCIS_CLOSED) goto end; } /* now actually close the connection and pick up the zombie */ rcode = endmailer(mci, e, NULL); if (rcode != EX_OK) { char *mailer = NULL; if (mci->mci_mailer != NULL && mci->mci_mailer->m_name != NULL) mailer = mci->mci_mailer->m_name; /* look for naughty mailers */ sm_syslog(LOG_ERR, e->e_id, "smtpquit: mailer%s%s exited with exit value %d", mailer == NULL ? "" : " ", mailer == NULL ? "" : mailer, rcode); } SuprErrs = oldSuprErrs; end: CurHostName = oldcurhost; return; } /* ** SMTPRSET -- send a RSET (reset) command ** ** Parameters: ** m -- a pointer to the mailer. ** mci -- the mailer connection information. ** e -- the current envelope. ** ** Returns: ** none. ** ** Side Effects: ** closes the connection if there is no reply to RSET. */ void smtprset(m, mci, e) register MAILER *m; register MCI *mci; ENVELOPE *e; { int r; CurHostName = mci->mci_host; /* XXX UGLY XXX */ if (CurHostName == NULL) CurHostName = MyHostName; #if PIPELINING mci->mci_okrcpts = 0; #endif /* PIPELINING */ /* ** Check if connection is gone, if so ** it's a tempfail and we use mci_errno ** for the reason. */ if (mci->mci_state == MCIS_CLOSED) { errno = mci->mci_errno; return; } SmtpPhase = "client RSET"; smtpmessage("RSET", m, mci); r = reply(m, mci, e, TimeOuts.to_rset, NULL, NULL, XS_DEFAULT); if (r < 0) return; /* ** Any response is deemed to be acceptable. ** The standard does not state the proper action ** to take when a value other than 250 is received. ** ** However, if 421 is returned for the RSET, leave ** mci_state alone (MCIS_SSD can be set in reply() ** and MCIS_CLOSED can be set in smtpquit() if ** reply() gets a 421 and calls smtpquit()). */ if (mci->mci_state != MCIS_SSD && mci->mci_state != MCIS_CLOSED) mci->mci_state = MCIS_OPEN; else if (mci->mci_exitstat == EX_OK) mci_setstat(mci, EX_TEMPFAIL, "4.5.0", NULL); } /* ** SMTPPROBE -- check the connection state ** ** Parameters: ** mci -- the mailer connection information. ** ** Returns: ** none. ** ** Side Effects: ** closes the connection if there is no reply to RSET. */ int smtpprobe(mci) register MCI *mci; { int r; MAILER *m = mci->mci_mailer; ENVELOPE *e; extern ENVELOPE BlankEnvelope; CurHostName = mci->mci_host; /* XXX UGLY XXX */ if (CurHostName == NULL) CurHostName = MyHostName; e = &BlankEnvelope; SmtpPhase = "client probe"; smtpmessage("RSET", m, mci); r = reply(m, mci, e, TimeOuts.to_miscshort, NULL, NULL, XS_DEFAULT); if (REPLYTYPE(r) != 2) smtpquit(m, mci, e); return r; } /* ** REPLY -- read arpanet reply ** ** Parameters: ** m -- the mailer we are reading the reply from. ** mci -- the mailer connection info structure. ** e -- the current envelope. ** timeout -- the timeout for reads. ** pfunc -- processing function called on each line of response. ** If null, no special processing is done. ** enhstat -- optional, returns enhanced error code string (if set) ** rtype -- type of SmtpMsgBuffer: does it contains secret data? ** ** Returns: ** reply code it reads. ** ** Side Effects: ** flushes the mail file. */ int reply(m, mci, e, timeout, pfunc, enhstat, rtype) MAILER *m; MCI *mci; ENVELOPE *e; time_t timeout; void (*pfunc) __P((char *, bool, MAILER *, MCI *, ENVELOPE *)); char **enhstat; int rtype; { register char *bufp; register int r; bool firstline = true; char junkbuf[MAXLINE]; static char enhstatcode[ENHSCLEN]; int save_errno; /* ** Flush the output before reading response. ** ** For SMTP pipelining, it would be better if we didn't do ** this if there was already data waiting to be read. But ** to do it properly means pushing it to the I/O library, ** since it really needs to be done below the buffer layer. */ if (mci->mci_out != NULL) (void) sm_io_flush(mci->mci_out, SM_TIME_DEFAULT); if (tTd(18, 1)) sm_dprintf("reply\n"); /* ** Read the input line, being careful not to hang. */ bufp = SmtpReplyBuffer; set_tls_rd_tmo(timeout); for (;;) { register char *p; /* actually do the read */ if (e->e_xfp != NULL) /* for debugging */ (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT); /* if we are in the process of closing just give the code */ if (mci->mci_state == MCIS_CLOSED) return SMTPCLOSING; /* don't try to read from a non-existent fd */ if (mci->mci_in == NULL) { if (mci->mci_errno == 0) mci->mci_errno = EBADF; /* errors on QUIT should be ignored */ if (strncmp(SmtpMsgBuffer, "QUIT", 4) == 0) { errno = mci->mci_errno; mci_close(mci, "reply:1"); return -1; } mci->mci_state = MCIS_ERROR; smtpquit(m, mci, e); errno = mci->mci_errno; return -1; } if (mci->mci_out != NULL) (void) sm_io_flush(mci->mci_out, SM_TIME_DEFAULT); /* get the line from the other side */ p = sfgets(bufp, MAXLINE, mci->mci_in, timeout, SmtpPhase); save_errno = errno; mci->mci_lastuse = curtime(); if (p == NULL) { bool oldholderrs; extern char MsgBuf[]; /* errors on QUIT should be ignored */ if (strncmp(SmtpMsgBuffer, "QUIT", 4) == 0) { mci_close(mci, "reply:2"); return -1; } /* if the remote end closed early, fake an error */ errno = save_errno; if (errno == 0) { (void) sm_snprintf(SmtpReplyBuffer, sizeof(SmtpReplyBuffer), "421 4.4.1 Connection reset by %s", CURHOSTNAME); #ifdef ECONNRESET errno = ECONNRESET; #else /* ECONNRESET */ errno = EPIPE; #endif /* ECONNRESET */ } mci->mci_errno = errno; oldholderrs = HoldErrs; HoldErrs = true; usrerr("451 4.4.1 reply: read error from %s", CURHOSTNAME); mci_setstat(mci, EX_TEMPFAIL, "4.4.2", MsgBuf); /* if debugging, pause so we can see state */ if (tTd(18, 100)) (void) pause(); mci->mci_state = MCIS_ERROR; smtpquit(m, mci, e); #if XDEBUG { char wbuf[MAXLINE]; p = wbuf; if (e->e_to != NULL) { (void) sm_snprintf(p, SPACELEFT(wbuf, p), "%s... ", shortenstring(e->e_to, MAXSHORTSTR)); p += strlen(p); } (void) sm_snprintf(p, SPACELEFT(wbuf, p), "reply(%.100s) during %s", CURHOSTNAME, SmtpPhase); checkfd012(wbuf); } #endif /* XDEBUG */ HoldErrs = oldholderrs; errno = save_errno; return -1; } fixcrlf(bufp, true); /* EHLO failure is not a real error */ if (e->e_xfp != NULL && (bufp[0] == '4' || (bufp[0] == '5' && strncmp(SmtpMsgBuffer, "EHLO", 4) != 0))) { /* serious error -- log the previous command */ if (SmtpNeedIntro) { /* inform user who we are chatting with */ (void) sm_io_fprintf(CurEnv->e_xfp, SM_TIME_DEFAULT, "... while talking to %s:\n", CURHOSTNAME); SmtpNeedIntro = false; } if (SmtpMsgBuffer[0] != '\0') { (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, ">>> %s\n", (rtype == XS_STARTTLS) ? "STARTTLS dialogue" : ((rtype == XS_AUTH) ? "AUTH dialogue" : SmtpMsgBuffer)); SmtpMsgBuffer[0] = '\0'; } /* now log the message as from the other side */ (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "<<< %s\n", bufp); } /* display the input for verbose mode */ if (Verbose) nmessage("050 %s", bufp); /* ignore improperly formatted input */ if (!ISSMTPREPLY(bufp)) continue; if (bitset(MCIF_ENHSTAT, mci->mci_flags) && enhstat != NULL && extenhsc(bufp + 4, ' ', enhstatcode) > 0) *enhstat = enhstatcode; /* process the line */ if (pfunc != NULL) (*pfunc)(bufp, firstline, m, mci, e); /* decode the reply code */ r = atoi(bufp); /* extra semantics: 0xx codes are "informational" */ if (r < 100) { firstline = false; continue; } firstline = false; /* if no continuation lines, return this line */ if (bufp[3] != '-') break; /* first line of real reply -- ignore rest */ bufp = junkbuf; } /* ** Now look at SmtpReplyBuffer -- only care about the first ** line of the response from here on out. */ /* save temporary failure messages for posterity */ if (SmtpReplyBuffer[0] == '4') (void) sm_strlcpy(SmtpError, SmtpReplyBuffer, sizeof(SmtpError)); /* reply code 421 is "Service Shutting Down" */ if (r == SMTPCLOSING && mci->mci_state != MCIS_SSD && mci->mci_state != MCIS_QUITING) { /* send the quit protocol */ mci->mci_state = MCIS_SSD; smtpquit(m, mci, e); } return r; } /* ** SMTPMESSAGE -- send message to server ** ** Parameters: ** f -- format ** m -- the mailer to control formatting. ** a, b, c -- parameters ** ** Returns: ** none. ** ** Side Effects: ** writes message to mci->mci_out. */ /*VARARGS1*/ void #ifdef __STDC__ smtpmessage(char *f, MAILER *m, MCI *mci, ...) #else /* __STDC__ */ smtpmessage(f, m, mci, va_alist) char *f; MAILER *m; MCI *mci; va_dcl #endif /* __STDC__ */ { SM_VA_LOCAL_DECL SM_VA_START(ap, mci); (void) sm_vsnprintf(SmtpMsgBuffer, sizeof(SmtpMsgBuffer), f, ap); SM_VA_END(ap); if (tTd(18, 1) || Verbose) nmessage(">>> %s", SmtpMsgBuffer); if (TrafficLogFile != NULL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d >>> %s\n", (int) CurrentPid, SmtpMsgBuffer); if (mci->mci_out != NULL) { (void) sm_io_fprintf(mci->mci_out, SM_TIME_DEFAULT, "%s%s", SmtpMsgBuffer, m == NULL ? "\r\n" : m->m_eol); } else if (tTd(18, 1)) { sm_dprintf("smtpmessage: NULL mci_out\n"); } } Index: head/contrib/sendmail/src/util.c =================================================================== --- head/contrib/sendmail/src/util.c (revision 249728) +++ head/contrib/sendmail/src/util.c (revision 249729) @@ -1,2869 +1,2868 @@ /* * Copyright (c) 1998-2007, 2009 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: util.c,v 8.425 2012/03/03 00:10:43 ca Exp $") +SM_RCSID("@(#)$Id: util.c,v 8.426 2013/03/12 15:24:54 ca Exp $") #include #include #include /* ** NEWSTR -- Create a copy of a C string ** ** Parameters: ** s -- the string to copy. ** ** Returns: ** pointer to newly allocated string. */ char * newstr(s) const char *s; { size_t l; char *n; l = strlen(s); SM_ASSERT(l + 1 > l); n = xalloc(l + 1); sm_strlcpy(n, s, l + 1); return n; } /* ** ADDQUOTES -- Adds quotes & quote bits to a string. ** ** Runs through a string and adds backslashes and quote bits. ** ** Parameters: ** s -- the string to modify. ** rpool -- resource pool from which to allocate result ** ** Returns: ** pointer to quoted string. */ char * addquotes(s, rpool) char *s; SM_RPOOL_T *rpool; { int len = 0; char c; char *p = s, *q, *r; if (s == NULL) return NULL; /* Find length of quoted string */ while ((c = *p++) != '\0') { len++; if (c == '\\' || c == '"') len++; } q = r = sm_rpool_malloc_x(rpool, len + 3); p = s; /* add leading quote */ *q++ = '"'; while ((c = *p++) != '\0') { /* quote \ or " */ if (c == '\\' || c == '"') *q++ = '\\'; *q++ = c; } *q++ = '"'; *q = '\0'; return r; } /* ** STRIPBACKSLASH -- Strip all leading backslashes from a string, provided ** the following character is alpha-numerical. ** ** This is done in place. ** ** Parameters: ** s -- the string to strip. ** ** Returns: ** none. */ void stripbackslash(s) char *s; { char *p, *q, c; if (s == NULL || *s == '\0') return; p = q = s; while (*p == '\\' && (p[1] == '\\' || (isascii(p[1]) && isalnum(p[1])))) p++; do { c = *q++ = *p++; } while (c != '\0'); } /* ** RFC822_STRING -- Checks string for proper RFC822 string quoting. ** ** Runs through a string and verifies RFC822 special characters ** are only found inside comments, quoted strings, or backslash ** escaped. Also verified balanced quotes and parenthesis. ** ** Parameters: ** s -- the string to modify. ** ** Returns: ** true iff the string is RFC822 compliant, false otherwise. */ bool rfc822_string(s) char *s; { bool quoted = false; int commentlev = 0; char *c = s; if (s == NULL) return false; while (*c != '\0') { /* escaped character */ if (*c == '\\') { c++; if (*c == '\0') return false; } else if (commentlev == 0 && *c == '"') quoted = !quoted; else if (!quoted) { if (*c == ')') { /* unbalanced ')' */ if (commentlev == 0) return false; else commentlev--; } else if (*c == '(') commentlev++; else if (commentlev == 0 && strchr(MustQuoteChars, *c) != NULL) return false; } c++; } /* unbalanced '"' or '(' */ return !quoted && commentlev == 0; } /* ** SHORTEN_RFC822_STRING -- Truncate and rebalance an RFC822 string ** ** Arbitrarily shorten (in place) an RFC822 string and rebalance ** comments and quotes. ** ** Parameters: ** string -- the string to shorten ** length -- the maximum size, 0 if no maximum ** ** Returns: ** true if string is changed, false otherwise ** ** Side Effects: ** Changes string in place, possibly resulting ** in a shorter string. */ bool shorten_rfc822_string(string, length) char *string; size_t length; { bool backslash = false; bool modified = false; bool quoted = false; size_t slen; int parencount = 0; char *ptr = string; /* ** If have to rebalance an already short enough string, ** need to do it within allocated space. */ slen = strlen(string); if (length == 0 || slen < length) length = slen; while (*ptr != '\0') { if (backslash) { backslash = false; goto increment; } if (*ptr == '\\') backslash = true; else if (*ptr == '(') { if (!quoted) parencount++; } else if (*ptr == ')') { if (--parencount < 0) parencount = 0; } /* Inside a comment, quotes don't matter */ if (parencount <= 0 && *ptr == '"') quoted = !quoted; increment: /* Check for sufficient space for next character */ if (length - (ptr - string) <= (size_t) ((backslash ? 1 : 0) + parencount + (quoted ? 1 : 0))) { /* Not enough, backtrack */ if (*ptr == '\\') backslash = false; else if (*ptr == '(' && !quoted) parencount--; else if (*ptr == '"' && parencount == 0) quoted = false; break; } ptr++; } /* Rebalance */ while (parencount-- > 0) { if (*ptr != ')') { modified = true; *ptr = ')'; } ptr++; } if (quoted) { if (*ptr != '"') { modified = true; *ptr = '"'; } ptr++; } if (*ptr != '\0') { modified = true; *ptr = '\0'; } return modified; } /* ** FIND_CHARACTER -- find an unquoted character in an RFC822 string ** ** Find an unquoted, non-commented character in an RFC822 ** string and return a pointer to its location in the ** string. ** ** Parameters: ** string -- the string to search ** character -- the character to find ** ** Returns: ** pointer to the character, or ** a pointer to the end of the line if character is not found */ char * find_character(string, character) char *string; int character; { bool backslash = false; bool quoted = false; int parencount = 0; while (string != NULL && *string != '\0') { if (backslash) { backslash = false; if (!quoted && character == '\\' && *string == '\\') break; string++; continue; } switch (*string) { case '\\': backslash = true; break; case '(': if (!quoted) parencount++; break; case ')': if (--parencount < 0) parencount = 0; break; } /* Inside a comment, nothing matters */ if (parencount > 0) { string++; continue; } if (*string == '"') quoted = !quoted; else if (*string == character && !quoted) break; string++; } /* Return pointer to the character */ return string; } /* ** CHECK_BODYTYPE -- check bodytype parameter ** ** Parameters: ** bodytype -- bodytype parameter ** ** Returns: ** BODYTYPE_* according to parameter ** */ int check_bodytype(bodytype) char *bodytype; { /* check body type for legality */ if (bodytype == NULL) return BODYTYPE_NONE; if (sm_strcasecmp(bodytype, "7BIT") == 0) return BODYTYPE_7BIT; if (sm_strcasecmp(bodytype, "8BITMIME") == 0) return BODYTYPE_8BITMIME; return BODYTYPE_ILLEGAL; } /* ** TRUNCATE_AT_DELIM -- truncate string at a delimiter and append "..." ** ** Parameters: ** str -- string to truncate ** len -- maximum length (including '\0') (0 for unlimited) ** delim -- delimiter character ** ** Returns: ** None. */ void truncate_at_delim(str, len, delim) char *str; size_t len; int delim; { char *p; if (str == NULL || len == 0 || strlen(str) < len) return; *(str + len - 1) = '\0'; while ((p = strrchr(str, delim)) != NULL) { *p = '\0'; if (p - str + 4 < len) { *p++ = (char) delim; *p = '\0'; (void) sm_strlcat(str, "...", len); return; } } /* Couldn't find a place to append "..." */ if (len > 3) (void) sm_strlcpy(str, "...", len); else str[0] = '\0'; } /* ** XALLOC -- Allocate memory, raise an exception on error ** ** Parameters: ** sz -- size of area to allocate. ** ** Returns: ** pointer to data region. ** ** Exceptions: ** SmHeapOutOfMemory (F:sm.heap) -- cannot allocate memory ** ** Side Effects: ** Memory is allocated. */ char * #if SM_HEAP_CHECK xalloc_tagged(sz, file, line) register int sz; char *file; int line; #else /* SM_HEAP_CHECK */ xalloc(sz) register int sz; #endif /* SM_HEAP_CHECK */ { register char *p; SM_REQUIRE(sz >= 0); /* some systems can't handle size zero mallocs */ if (sz <= 0) sz = 1; /* scaffolding for testing error handling code */ sm_xtrap_raise_x(&SmHeapOutOfMemory); p = sm_malloc_tagged((unsigned) sz, file, line, sm_heap_group()); if (p == NULL) { sm_exc_raise_x(&SmHeapOutOfMemory); } return p; } /* ** COPYPLIST -- copy list of pointers. ** ** This routine is the equivalent of strdup for lists of ** pointers. ** ** Parameters: ** list -- list of pointers to copy. ** Must be NULL terminated. ** copycont -- if true, copy the contents of the vector ** (which must be a string) also. ** rpool -- resource pool from which to allocate storage, ** or NULL ** ** Returns: ** a copy of 'list'. */ char ** copyplist(list, copycont, rpool) char **list; bool copycont; SM_RPOOL_T *rpool; { register char **vp; register char **newvp; for (vp = list; *vp != NULL; vp++) continue; vp++; newvp = (char **) sm_rpool_malloc_x(rpool, (vp - list) * sizeof(*vp)); memmove((char *) newvp, (char *) list, (int) (vp - list) * sizeof(*vp)); if (copycont) { for (vp = newvp; *vp != NULL; vp++) *vp = sm_rpool_strdup_x(rpool, *vp); } return newvp; } /* ** COPYQUEUE -- copy address queue. ** ** This routine is the equivalent of strdup for address queues; ** addresses marked as QS_IS_DEAD() aren't copied ** ** Parameters: ** addr -- list of address structures to copy. ** rpool -- resource pool from which to allocate storage ** ** Returns: ** a copy of 'addr'. */ ADDRESS * copyqueue(addr, rpool) ADDRESS *addr; SM_RPOOL_T *rpool; { register ADDRESS *newaddr; ADDRESS *ret; register ADDRESS **tail = &ret; while (addr != NULL) { if (!QS_IS_DEAD(addr->q_state)) { newaddr = (ADDRESS *) sm_rpool_malloc_x(rpool, sizeof(*newaddr)); STRUCTCOPY(*addr, *newaddr); *tail = newaddr; tail = &newaddr->q_next; } addr = addr->q_next; } *tail = NULL; return ret; } /* ** LOG_SENDMAIL_PID -- record sendmail pid and command line. ** ** Parameters: ** e -- the current envelope. ** ** Returns: ** none. ** ** Side Effects: ** writes pidfile, logs command line. ** keeps file open and locked to prevent overwrite of active file */ static SM_FILE_T *Pidf = NULL; void log_sendmail_pid(e) ENVELOPE *e; { long sff; char pidpath[MAXPATHLEN]; extern char *CommandLineArgs; /* write the pid to the log file for posterity */ sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY|SFF_CREAT|SFF_NBLOCK; if (TrustedUid != 0 && RealUid == TrustedUid) sff |= SFF_OPENASROOT; expand(PidFile, pidpath, sizeof(pidpath), e); Pidf = safefopen(pidpath, O_WRONLY|O_TRUNC, FileMode, sff); if (Pidf == NULL) { if (errno == EWOULDBLOCK) sm_syslog(LOG_ERR, NOQID, "unable to write pid to %s: file in use by another process", pidpath); else sm_syslog(LOG_ERR, NOQID, "unable to write pid to %s: %s", pidpath, sm_errstring(errno)); } else { PidFilePid = getpid(); /* write the process id on line 1 */ (void) sm_io_fprintf(Pidf, SM_TIME_DEFAULT, "%ld\n", (long) PidFilePid); /* line 2 contains all command line flags */ (void) sm_io_fprintf(Pidf, SM_TIME_DEFAULT, "%s\n", CommandLineArgs); /* flush */ (void) sm_io_flush(Pidf, SM_TIME_DEFAULT); /* ** Leave pid file open until process ends ** so it's not overwritten by another ** process. */ } if (LogLevel > 9) sm_syslog(LOG_INFO, NOQID, "started as: %s", CommandLineArgs); } /* ** CLOSE_SENDMAIL_PID -- close sendmail pid file ** ** Parameters: ** none. ** ** Returns: ** none. */ void close_sendmail_pid() { if (Pidf == NULL) return; (void) sm_io_close(Pidf, SM_TIME_DEFAULT); Pidf = NULL; } /* ** SET_DELIVERY_MODE -- set and record the delivery mode ** ** Parameters: ** mode -- delivery mode ** e -- the current envelope. ** ** Returns: ** none. ** ** Side Effects: ** sets {deliveryMode} macro */ void set_delivery_mode(mode, e) int mode; ENVELOPE *e; { char buf[2]; e->e_sendmode = (char) mode; buf[0] = (char) mode; buf[1] = '\0'; macdefine(&e->e_macro, A_TEMP, macid("{deliveryMode}"), buf); } /* ** SET_OP_MODE -- set and record the op mode ** ** Parameters: ** mode -- op mode ** e -- the current envelope. ** ** Returns: ** none. ** ** Side Effects: ** sets {opMode} macro */ void set_op_mode(mode) int mode; { char buf[2]; extern ENVELOPE BlankEnvelope; OpMode = (char) mode; buf[0] = (char) mode; buf[1] = '\0'; macdefine(&BlankEnvelope.e_macro, A_TEMP, MID_OPMODE, buf); } /* ** PRINTAV -- print argument vector. ** ** Parameters: ** fp -- output file pointer. ** av -- argument vector. ** ** Returns: ** none. ** ** Side Effects: ** prints av. */ void printav(fp, av) SM_FILE_T *fp; char **av; { while (*av != NULL) { if (tTd(0, 44)) sm_dprintf("\n\t%08lx=", (unsigned long) *av); else (void) sm_io_putc(fp, SM_TIME_DEFAULT, ' '); if (tTd(0, 99)) sm_dprintf("%s", str2prt(*av++)); else xputs(fp, *av++); } (void) sm_io_putc(fp, SM_TIME_DEFAULT, '\n'); } /* ** XPUTS -- put string doing control escapes. ** ** Parameters: ** fp -- output file pointer. ** s -- string to put. ** ** Returns: ** none. ** ** Side Effects: ** output to stdout */ void xputs(fp, s) SM_FILE_T *fp; const char *s; { int c; struct metamac *mp; bool shiftout = false; extern struct metamac MetaMacros[]; static SM_DEBUG_T DebugANSI = SM_DEBUG_INITIALIZER("ANSI", "@(#)$Debug: ANSI - enable reverse video in debug output $"); /* ** TermEscape is set here, rather than in main(), ** because ANSI mode can be turned on or off at any time ** if we are in -bt rule testing mode. */ if (sm_debug_unknown(&DebugANSI)) { if (sm_debug_active(&DebugANSI, 1)) { TermEscape.te_rv_on = "\033[7m"; TermEscape.te_normal = "\033[0m"; } else { TermEscape.te_rv_on = ""; TermEscape.te_normal = ""; } } if (s == NULL) { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s%s", TermEscape.te_rv_on, TermEscape.te_normal); return; } while ((c = (*s++ & 0377)) != '\0') { if (shiftout) { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s", TermEscape.te_normal); shiftout = false; } if (!isascii(c) && !tTd(84, 1)) { if (c == MATCHREPL) { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s$", TermEscape.te_rv_on); shiftout = true; if (*s == '\0') continue; c = *s++ & 0377; goto printchar; } if (c == MACROEXPAND || c == MACRODEXPAND) { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s$", TermEscape.te_rv_on); if (c == MACRODEXPAND) (void) sm_io_putc(fp, SM_TIME_DEFAULT, '&'); shiftout = true; if (*s == '\0') continue; if (strchr("=~&?", *s) != NULL) (void) sm_io_putc(fp, SM_TIME_DEFAULT, *s++); if (bitset(0200, *s)) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "{%s}", macname(bitidx(*s++))); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%c", *s++); continue; } for (mp = MetaMacros; mp->metaname != '\0'; mp++) { if (bitidx(mp->metaval) == c) { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s$%c", TermEscape.te_rv_on, mp->metaname); shiftout = true; break; } } if (c == MATCHCLASS || c == MATCHNCLASS) { if (bitset(0200, *s)) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "{%s}", macname(bitidx(*s++))); else if (*s != '\0') (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%c", *s++); } if (mp->metaname != '\0') continue; /* unrecognized meta character */ (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%sM-", TermEscape.te_rv_on); shiftout = true; c &= 0177; } printchar: if (isascii(c) && isprint(c)) { (void) sm_io_putc(fp, SM_TIME_DEFAULT, c); continue; } /* wasn't a meta-macro -- find another way to print it */ switch (c) { case '\n': c = 'n'; break; case '\r': c = 'r'; break; case '\t': c = 't'; break; } if (!shiftout) { (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s", TermEscape.te_rv_on); shiftout = true; } if (isascii(c) && isprint(c)) { (void) sm_io_putc(fp, SM_TIME_DEFAULT, '\\'); (void) sm_io_putc(fp, SM_TIME_DEFAULT, c); } else if (tTd(84, 2)) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " %o ", c); else if (tTd(84, 1)) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " %#x ", c); else if (!isascii(c) && !tTd(84, 1)) { (void) sm_io_putc(fp, SM_TIME_DEFAULT, '^'); (void) sm_io_putc(fp, SM_TIME_DEFAULT, c ^ 0100); } } if (shiftout) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s", TermEscape.te_normal); (void) sm_io_flush(fp, SM_TIME_DEFAULT); } /* ** MAKELOWER -- Translate a line into lower case ** ** Parameters: ** p -- the string to translate. If NULL, return is ** immediate. ** ** Returns: ** none. ** ** Side Effects: ** String pointed to by p is translated to lower case. */ void makelower(p) register char *p; { register char c; if (p == NULL) return; for (; (c = *p) != '\0'; p++) if (isascii(c) && isupper(c)) *p = tolower(c); } /* ** FIXCRLF -- fix in line. ** ** Looks for the combination and turns it into the ** UNIX canonical character. It only takes one line, ** i.e., it is assumed that the first found is the end ** of the line. ** ** Parameters: ** line -- the line to fix. ** stripnl -- if true, strip the newline also. ** ** Returns: ** none. ** ** Side Effects: ** line is changed in place. */ void fixcrlf(line, stripnl) char *line; bool stripnl; { register char *p; p = strchr(line, '\n'); if (p == NULL) return; if (p > line && p[-1] == '\r') p--; if (!stripnl) *p++ = '\n'; *p = '\0'; } /* ** PUTLINE -- put a line like fputs obeying SMTP conventions ** ** This routine always guarantees outputing a newline (or CRLF, ** as appropriate) at the end of the string. ** ** Parameters: ** l -- line to put. ** mci -- the mailer connection information. ** ** Returns: ** true iff line was written successfully ** ** Side Effects: ** output of l to mci->mci_out. */ bool putline(l, mci) register char *l; register MCI *mci; { return putxline(l, strlen(l), mci, PXLF_MAPFROM); } /* ** PUTXLINE -- putline with flags bits. ** ** This routine always guarantees outputing a newline (or CRLF, ** as appropriate) at the end of the string. ** ** Parameters: ** l -- line to put. ** len -- the length of the line. ** mci -- the mailer connection information. ** pxflags -- flag bits: ** PXLF_MAPFROM -- map From_ to >From_. ** PXLF_STRIP8BIT -- strip 8th bit. ** PXLF_HEADER -- map bare newline in header to newline space. ** PXLF_NOADDEOL -- don't add an EOL if one wasn't present. ** PXLF_STRIPMQUOTE -- strip METAQUOTE bytes. ** ** Returns: ** true iff line was written successfully ** ** Side Effects: ** output of l to mci->mci_out. */ #define PUTX(limit) \ do \ { \ quotenext = false; \ while (l < limit) \ { \ unsigned char c = (unsigned char) *l++; \ \ if (bitset(PXLF_STRIPMQUOTE, pxflags) && \ !quotenext && c == METAQUOTE) \ { \ quotenext = true; \ continue; \ } \ quotenext = false; \ if (strip8bit) \ c &= 0177; \ if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, \ c) == SM_IO_EOF) \ { \ dead = true; \ break; \ } \ if (TrafficLogFile != NULL) \ (void) sm_io_putc(TrafficLogFile, \ SM_TIME_DEFAULT, \ c); \ } \ } while (0) bool putxline(l, len, mci, pxflags) register char *l; size_t len; register MCI *mci; int pxflags; { register char *p, *end; int slop; bool dead, quotenext, strip8bit; /* strip out 0200 bits -- these can look like TELNET protocol */ strip8bit = bitset(MCIF_7BIT, mci->mci_flags) || bitset(PXLF_STRIP8BIT, pxflags); dead = false; slop = 0; end = l + len; do { bool noeol = false; /* find the end of the line */ p = memchr(l, '\n', end - l); if (p == NULL) { p = end; noeol = true; } if (TrafficLogFile != NULL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d >>> ", (int) CurrentPid); /* check for line overflow */ while (mci->mci_mailer->m_linelimit > 0 && (p - l + slop) > mci->mci_mailer->m_linelimit) { register char *q = &l[mci->mci_mailer->m_linelimit - slop - 1]; if (l[0] == '.' && slop == 0 && bitnset(M_XDOT, mci->mci_mailer->m_flags)) { if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, '.') == SM_IO_EOF) dead = true; if (TrafficLogFile != NULL) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, '.'); } else if (l[0] == 'F' && slop == 0 && bitset(PXLF_MAPFROM, pxflags) && strncmp(l, "From ", 5) == 0 && bitnset(M_ESCFROM, mci->mci_mailer->m_flags)) { if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, '>') == SM_IO_EOF) dead = true; if (TrafficLogFile != NULL) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, '>'); } if (dead) break; PUTX(q); if (dead) break; if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, '!') == SM_IO_EOF || sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT, mci->mci_mailer->m_eol) == SM_IO_EOF || sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, ' ') == SM_IO_EOF) { dead = true; break; } if (TrafficLogFile != NULL) { (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "!\n%05d >>> ", (int) CurrentPid); } slop = 1; } if (dead) break; /* output last part */ if (l[0] == '.' && slop == 0 && bitnset(M_XDOT, mci->mci_mailer->m_flags) && !bitset(MCIF_INLONGLINE, mci->mci_flags)) { if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, '.') == SM_IO_EOF) { dead = true; break; } if (TrafficLogFile != NULL) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, '.'); } else if (l[0] == 'F' && slop == 0 && bitset(PXLF_MAPFROM, pxflags) && strncmp(l, "From ", 5) == 0 && bitnset(M_ESCFROM, mci->mci_mailer->m_flags) && !bitset(MCIF_INLONGLINE, mci->mci_flags)) { if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, '>') == SM_IO_EOF) { dead = true; break; } if (TrafficLogFile != NULL) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, '>'); } PUTX(p); if (dead) break; if (TrafficLogFile != NULL) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, '\n'); if ((!bitset(PXLF_NOADDEOL, pxflags) || !noeol)) { mci->mci_flags &= ~MCIF_INLONGLINE; if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT, mci->mci_mailer->m_eol) == SM_IO_EOF) { dead = true; break; } } else mci->mci_flags |= MCIF_INLONGLINE; if (l < end && *l == '\n') { if (*++l != ' ' && *l != '\t' && *l != '\0' && bitset(PXLF_HEADER, pxflags)) { if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT, ' ') == SM_IO_EOF) { dead = true; break; } if (TrafficLogFile != NULL) (void) sm_io_putc(TrafficLogFile, SM_TIME_DEFAULT, ' '); } } } while (l < end); return !dead; } /* ** XUNLINK -- unlink a file, doing logging as appropriate. ** ** Parameters: ** f -- name of file to unlink. ** ** Returns: ** return value of unlink() ** ** Side Effects: ** f is unlinked. */ int xunlink(f) char *f; { register int i; int save_errno; if (LogLevel > 98) sm_syslog(LOG_DEBUG, CurEnv->e_id, "unlink %s", f); i = unlink(f); save_errno = errno; if (i < 0 && LogLevel > 97) sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s: unlink-fail %d", f, errno); if (i >= 0) SYNC_DIR(f, false); errno = save_errno; return i; } /* ** SFGETS -- "safe" fgets -- times out and ignores random interrupts. ** ** Parameters: ** buf -- place to put the input line. ** siz -- size of buf. ** fp -- file to read from. ** timeout -- the timeout before error occurs. ** during -- what we are trying to read (for error messages). ** ** Returns: ** NULL on error (including timeout). This may also leave ** buf containing a null string. ** buf otherwise. */ char * sfgets(buf, siz, fp, timeout, during) char *buf; int siz; SM_FILE_T *fp; time_t timeout; char *during; { register char *p; - int save_errno; - int io_timeout; + int save_errno, io_timeout, l; SM_REQUIRE(siz > 0); SM_REQUIRE(buf != NULL); if (fp == NULL) { buf[0] = '\0'; errno = EBADF; return NULL; } /* try to read */ - p = NULL; + l = -1; errno = 0; /* convert the timeout to sm_io notation */ io_timeout = (timeout <= 0) ? SM_TIME_DEFAULT : timeout * 1000; while (!sm_io_eof(fp) && !sm_io_error(fp)) { errno = 0; - p = sm_io_fgets(fp, io_timeout, buf, siz); - if (p == NULL && errno == EAGAIN) + l = sm_io_fgets(fp, io_timeout, buf, siz); + if (l < 0 && errno == EAGAIN) { /* The sm_io_fgets() call timedout */ if (LogLevel > 1) sm_syslog(LOG_NOTICE, CurEnv->e_id, "timeout waiting for input from %.100s during %s", CURHOSTNAME, during); buf[0] = '\0'; #if XDEBUG checkfd012(during); #endif /* XDEBUG */ if (TrafficLogFile != NULL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d <<< [TIMEOUT]\n", (int) CurrentPid); errno = ETIMEDOUT; return NULL; } - if (p != NULL || errno != EINTR) + if (l >= 0 || errno != EINTR) break; (void) sm_io_clearerr(fp); } save_errno = errno; /* clean up the books and exit */ LineNumber++; - if (p == NULL) + if (l < 0) { buf[0] = '\0'; if (TrafficLogFile != NULL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d <<< [EOF]\n", (int) CurrentPid); errno = save_errno; return NULL; } if (TrafficLogFile != NULL) (void) sm_io_fprintf(TrafficLogFile, SM_TIME_DEFAULT, "%05d <<< %s", (int) CurrentPid, buf); if (SevenBitInput) { for (p = buf; *p != '\0'; p++) *p &= ~0200; } else if (!HasEightBits) { for (p = buf; *p != '\0'; p++) { if (bitset(0200, *p)) { HasEightBits = true; break; } } } return buf; } /* ** FGETFOLDED -- like fgets, but knows about folded lines. ** ** Parameters: ** buf -- place to put result. ** np -- pointer to bytes available; will be updated with ** the actual buffer size (not number of bytes filled) ** on return. ** f -- file to read from. ** ** Returns: ** input line(s) on success, NULL on error or SM_IO_EOF. ** This will normally be buf -- unless the line is too ** long, when it will be sm_malloc_x()ed. ** ** Side Effects: ** buf gets lines from f, with continuation lines (lines ** with leading white space) appended. CRLF's are mapped ** into single newlines. Any trailing NL is stripped. */ char * fgetfolded(buf, np, f) char *buf; int *np; SM_FILE_T *f; { register char *p = buf; char *bp = buf; register int i; int n; SM_REQUIRE(np != NULL); n = *np; SM_REQUIRE(n > 0); SM_REQUIRE(buf != NULL); if (f == NULL) { buf[0] = '\0'; errno = EBADF; return NULL; } n--; while ((i = sm_io_getc(f, SM_TIME_DEFAULT)) != SM_IO_EOF) { if (i == '\r') { i = sm_io_getc(f, SM_TIME_DEFAULT); if (i != '\n') { if (i != SM_IO_EOF) (void) sm_io_ungetc(f, SM_TIME_DEFAULT, i); i = '\r'; } } if (--n <= 0) { /* allocate new space */ char *nbp; int nn; nn = (p - bp); if (nn < MEMCHUNKSIZE) nn *= 2; else nn += MEMCHUNKSIZE; nbp = sm_malloc_x(nn); memmove(nbp, bp, p - bp); p = &nbp[p - bp]; if (bp != buf) sm_free(bp); bp = nbp; n = nn - (p - bp); *np = nn; } *p++ = i; if (i == '\n') { LineNumber++; i = sm_io_getc(f, SM_TIME_DEFAULT); if (i != SM_IO_EOF) (void) sm_io_ungetc(f, SM_TIME_DEFAULT, i); if (i != ' ' && i != '\t') break; } } if (p == bp) return NULL; if (p[-1] == '\n') p--; *p = '\0'; return bp; } /* ** CURTIME -- return current time. ** ** Parameters: ** none. ** ** Returns: ** the current time. */ time_t curtime() { auto time_t t; (void) time(&t); return t; } /* ** ATOBOOL -- convert a string representation to boolean. ** ** Defaults to false ** ** Parameters: ** s -- string to convert. Takes "tTyY", empty, and NULL as true, ** others as false. ** ** Returns: ** A boolean representation of the string. */ bool atobool(s) register char *s; { if (s == NULL || *s == '\0' || strchr("tTyY", *s) != NULL) return true; return false; } /* ** ATOOCT -- convert a string representation to octal. ** ** Parameters: ** s -- string to convert. ** ** Returns: ** An integer representing the string interpreted as an ** octal number. */ int atooct(s) register char *s; { register int i = 0; while (*s >= '0' && *s <= '7') i = (i << 3) | (*s++ - '0'); return i; } /* ** BITINTERSECT -- tell if two bitmaps intersect ** ** Parameters: ** a, b -- the bitmaps in question ** ** Returns: ** true if they have a non-null intersection ** false otherwise */ bool bitintersect(a, b) BITMAP256 a; BITMAP256 b; { int i; for (i = BITMAPBYTES / sizeof(int); --i >= 0; ) { if ((a[i] & b[i]) != 0) return true; } return false; } /* ** BITZEROP -- tell if a bitmap is all zero ** ** Parameters: ** map -- the bit map to check ** ** Returns: ** true if map is all zero. ** false if there are any bits set in map. */ bool bitzerop(map) BITMAP256 map; { int i; for (i = BITMAPBYTES / sizeof(int); --i >= 0; ) { if (map[i] != 0) return false; } return true; } /* ** STRCONTAINEDIN -- tell if one string is contained in another ** ** Parameters: ** icase -- ignore case? ** a -- possible substring. ** b -- possible superstring. ** ** Returns: ** true if a is contained in b (case insensitive). ** false otherwise. */ bool strcontainedin(icase, a, b) bool icase; register char *a; register char *b; { int la; int lb; int c; la = strlen(a); lb = strlen(b); c = *a; if (icase && isascii(c) && isupper(c)) c = tolower(c); for (; lb-- >= la; b++) { if (icase) { if (*b != c && isascii(*b) && isupper(*b) && tolower(*b) != c) continue; if (sm_strncasecmp(a, b, la) == 0) return true; } else { if (*b != c) continue; if (strncmp(a, b, la) == 0) return true; } } return false; } /* ** CHECKFD012 -- check low numbered file descriptors ** ** File descriptors 0, 1, and 2 should be open at all times. ** This routine verifies that, and fixes it if not true. ** ** Parameters: ** where -- a tag printed if the assertion failed ** ** Returns: ** none */ void checkfd012(where) char *where; { #if XDEBUG register int i; for (i = 0; i < 3; i++) fill_fd(i, where); #endif /* XDEBUG */ } /* ** CHECKFDOPEN -- make sure file descriptor is open -- for extended debugging ** ** Parameters: ** fd -- file descriptor to check. ** where -- tag to print on failure. ** ** Returns: ** none. */ void checkfdopen(fd, where) int fd; char *where; { #if XDEBUG struct stat st; if (fstat(fd, &st) < 0 && errno == EBADF) { syserr("checkfdopen(%d): %s not open as expected!", fd, where); printopenfds(true); } #endif /* XDEBUG */ } /* ** CHECKFDS -- check for new or missing file descriptors ** ** Parameters: ** where -- tag for printing. If null, take a base line. ** ** Returns: ** none ** ** Side Effects: ** If where is set, shows changes since the last call. */ void checkfds(where) char *where; { int maxfd; register int fd; bool printhdr = true; int save_errno = errno; static BITMAP256 baseline; extern int DtableSize; if (DtableSize > BITMAPBITS) maxfd = BITMAPBITS; else maxfd = DtableSize; if (where == NULL) clrbitmap(baseline); for (fd = 0; fd < maxfd; fd++) { struct stat stbuf; if (fstat(fd, &stbuf) < 0 && errno != EOPNOTSUPP) { if (!bitnset(fd, baseline)) continue; clrbitn(fd, baseline); } else if (!bitnset(fd, baseline)) setbitn(fd, baseline); else continue; /* file state has changed */ if (where == NULL) continue; if (printhdr) { sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s: changed fds:", where); printhdr = false; } dumpfd(fd, true, true); } errno = save_errno; } /* ** PRINTOPENFDS -- print the open file descriptors (for debugging) ** ** Parameters: ** logit -- if set, send output to syslog; otherwise ** print for debugging. ** ** Returns: ** none. */ #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ void printopenfds(logit) bool logit; { register int fd; extern int DtableSize; for (fd = 0; fd < DtableSize; fd++) dumpfd(fd, false, logit); } /* ** DUMPFD -- dump a file descriptor ** ** Parameters: ** fd -- the file descriptor to dump. ** printclosed -- if set, print a notification even if ** it is closed; otherwise print nothing. ** logit -- if set, use sm_syslog instead of sm_dprintf() ** ** Returns: ** none. */ void dumpfd(fd, printclosed, logit) int fd; bool printclosed; bool logit; { register char *p; char *hp; #ifdef S_IFSOCK SOCKADDR sa; #endif /* S_IFSOCK */ auto SOCKADDR_LEN_T slen; int i; #if STAT64 > 0 struct stat64 st; #else /* STAT64 > 0 */ struct stat st; #endif /* STAT64 > 0 */ char buf[200]; p = buf; (void) sm_snprintf(p, SPACELEFT(buf, p), "%3d: ", fd); p += strlen(p); if ( #if STAT64 > 0 fstat64(fd, &st) #else /* STAT64 > 0 */ fstat(fd, &st) #endif /* STAT64 > 0 */ < 0) { if (errno != EBADF) { (void) sm_snprintf(p, SPACELEFT(buf, p), "CANNOT STAT (%s)", sm_errstring(errno)); goto printit; } else if (printclosed) { (void) sm_snprintf(p, SPACELEFT(buf, p), "CLOSED"); goto printit; } return; } i = fcntl(fd, F_GETFL, 0); if (i != -1) { (void) sm_snprintf(p, SPACELEFT(buf, p), "fl=0x%x, ", i); p += strlen(p); } (void) sm_snprintf(p, SPACELEFT(buf, p), "mode=%o: ", (int) st.st_mode); p += strlen(p); switch (st.st_mode & S_IFMT) { #ifdef S_IFSOCK case S_IFSOCK: (void) sm_snprintf(p, SPACELEFT(buf, p), "SOCK "); p += strlen(p); memset(&sa, '\0', sizeof(sa)); slen = sizeof(sa); if (getsockname(fd, &sa.sa, &slen) < 0) (void) sm_snprintf(p, SPACELEFT(buf, p), "(%s)", sm_errstring(errno)); else { hp = hostnamebyanyaddr(&sa); if (hp == NULL) { /* EMPTY */ /* do nothing */ } # if NETINET else if (sa.sa.sa_family == AF_INET) (void) sm_snprintf(p, SPACELEFT(buf, p), "%s/%d", hp, ntohs(sa.sin.sin_port)); # endif /* NETINET */ # if NETINET6 else if (sa.sa.sa_family == AF_INET6) (void) sm_snprintf(p, SPACELEFT(buf, p), "%s/%d", hp, ntohs(sa.sin6.sin6_port)); # endif /* NETINET6 */ else (void) sm_snprintf(p, SPACELEFT(buf, p), "%s", hp); } p += strlen(p); (void) sm_snprintf(p, SPACELEFT(buf, p), "->"); p += strlen(p); slen = sizeof(sa); if (getpeername(fd, &sa.sa, &slen) < 0) (void) sm_snprintf(p, SPACELEFT(buf, p), "(%s)", sm_errstring(errno)); else { hp = hostnamebyanyaddr(&sa); if (hp == NULL) { /* EMPTY */ /* do nothing */ } # if NETINET else if (sa.sa.sa_family == AF_INET) (void) sm_snprintf(p, SPACELEFT(buf, p), "%s/%d", hp, ntohs(sa.sin.sin_port)); # endif /* NETINET */ # if NETINET6 else if (sa.sa.sa_family == AF_INET6) (void) sm_snprintf(p, SPACELEFT(buf, p), "%s/%d", hp, ntohs(sa.sin6.sin6_port)); # endif /* NETINET6 */ else (void) sm_snprintf(p, SPACELEFT(buf, p), "%s", hp); } break; #endif /* S_IFSOCK */ case S_IFCHR: (void) sm_snprintf(p, SPACELEFT(buf, p), "CHR: "); p += strlen(p); goto defprint; #ifdef S_IFBLK case S_IFBLK: (void) sm_snprintf(p, SPACELEFT(buf, p), "BLK: "); p += strlen(p); goto defprint; #endif /* S_IFBLK */ #if defined(S_IFIFO) && (!defined(S_IFSOCK) || S_IFIFO != S_IFSOCK) case S_IFIFO: (void) sm_snprintf(p, SPACELEFT(buf, p), "FIFO: "); p += strlen(p); goto defprint; #endif /* defined(S_IFIFO) && (!defined(S_IFSOCK) || S_IFIFO != S_IFSOCK) */ #ifdef S_IFDIR case S_IFDIR: (void) sm_snprintf(p, SPACELEFT(buf, p), "DIR: "); p += strlen(p); goto defprint; #endif /* S_IFDIR */ #ifdef S_IFLNK case S_IFLNK: (void) sm_snprintf(p, SPACELEFT(buf, p), "LNK: "); p += strlen(p); goto defprint; #endif /* S_IFLNK */ default: defprint: (void) sm_snprintf(p, SPACELEFT(buf, p), "dev=%d/%d, ino=%llu, nlink=%d, u/gid=%d/%d, ", major(st.st_dev), minor(st.st_dev), (ULONGLONG_T) st.st_ino, (int) st.st_nlink, (int) st.st_uid, (int) st.st_gid); p += strlen(p); (void) sm_snprintf(p, SPACELEFT(buf, p), "size=%llu", (ULONGLONG_T) st.st_size); break; } printit: if (logit) sm_syslog(LOG_DEBUG, CurEnv ? CurEnv->e_id : NULL, "%.800s", buf); else sm_dprintf("%s\n", buf); } /* ** SHORTEN_HOSTNAME -- strip local domain information off of hostname. ** ** Parameters: ** host -- the host to shorten (stripped in place). ** ** Returns: ** place where string was truncated, NULL if not truncated. */ char * shorten_hostname(host) char host[]; { register char *p; char *mydom; int i; bool canon = false; /* strip off final dot */ i = strlen(host); p = &host[(i == 0) ? 0 : i - 1]; if (*p == '.') { *p = '\0'; canon = true; } /* see if there is any domain at all -- if not, we are done */ p = strchr(host, '.'); if (p == NULL) return NULL; /* yes, we have a domain -- see if it looks like us */ mydom = macvalue('m', CurEnv); if (mydom == NULL) mydom = ""; i = strlen(++p); if ((canon ? sm_strcasecmp(p, mydom) : sm_strncasecmp(p, mydom, i)) == 0 && (mydom[i] == '.' || mydom[i] == '\0')) { *--p = '\0'; return p; } return NULL; } /* ** PROG_OPEN -- open a program for reading ** ** Parameters: ** argv -- the argument list. ** pfd -- pointer to a place to store the file descriptor. ** e -- the current envelope. ** ** Returns: ** pid of the process -- -1 if it failed. */ pid_t prog_open(argv, pfd, e) char **argv; int *pfd; ENVELOPE *e; { pid_t pid; int save_errno; int sff; int ret; int fdv[2]; char *p, *q; char buf[MAXPATHLEN]; extern int DtableSize; if (pipe(fdv) < 0) { syserr("%s: cannot create pipe for stdout", argv[0]); return -1; } pid = fork(); if (pid < 0) { syserr("%s: cannot fork", argv[0]); (void) close(fdv[0]); (void) close(fdv[1]); return -1; } if (pid > 0) { /* parent */ (void) close(fdv[1]); *pfd = fdv[0]; return pid; } /* Reset global flags */ RestartRequest = NULL; RestartWorkGroup = false; ShutdownRequest = NULL; PendingSignal = 0; CurrentPid = getpid(); /* ** Initialize exception stack and default exception ** handler for child process. */ sm_exc_newthread(fatal_error); /* child -- close stdin */ (void) close(0); /* stdout goes back to parent */ (void) close(fdv[0]); if (dup2(fdv[1], 1) < 0) { syserr("%s: cannot dup2 for stdout", argv[0]); _exit(EX_OSERR); } (void) close(fdv[1]); /* stderr goes to transcript if available */ if (e->e_xfp != NULL) { int xfd; xfd = sm_io_getinfo(e->e_xfp, SM_IO_WHAT_FD, NULL); if (xfd >= 0 && dup2(xfd, 2) < 0) { syserr("%s: cannot dup2 for stderr", argv[0]); _exit(EX_OSERR); } } /* this process has no right to the queue file */ if (e->e_lockfp != NULL) { int fd; fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL); if (fd >= 0) (void) close(fd); else syserr("%s: lockfp does not have a fd", argv[0]); } /* chroot to the program mailer directory, if defined */ if (ProgMailer != NULL && ProgMailer->m_rootdir != NULL) { expand(ProgMailer->m_rootdir, buf, sizeof(buf), e); if (chroot(buf) < 0) { syserr("prog_open: cannot chroot(%s)", buf); exit(EX_TEMPFAIL); } if (chdir("/") < 0) { syserr("prog_open: cannot chdir(/)"); exit(EX_TEMPFAIL); } } /* run as default user */ endpwent(); sm_mbdb_terminate(); #if _FFR_MEMSTAT (void) sm_memstat_close(); #endif /* _FFR_MEMSTAT */ if (setgid(DefGid) < 0 && geteuid() == 0) { syserr("prog_open: setgid(%ld) failed", (long) DefGid); exit(EX_TEMPFAIL); } if (setuid(DefUid) < 0 && geteuid() == 0) { syserr("prog_open: setuid(%ld) failed", (long) DefUid); exit(EX_TEMPFAIL); } /* run in some directory */ if (ProgMailer != NULL) p = ProgMailer->m_execdir; else p = NULL; for (; p != NULL; p = q) { q = strchr(p, ':'); if (q != NULL) *q = '\0'; expand(p, buf, sizeof(buf), e); if (q != NULL) *q++ = ':'; if (buf[0] != '\0' && chdir(buf) >= 0) break; } if (p == NULL) { /* backup directories */ if (chdir("/tmp") < 0) (void) chdir("/"); } /* Check safety of program to be run */ sff = SFF_ROOTOK|SFF_EXECOK; if (!bitnset(DBS_RUNWRITABLEPROGRAM, DontBlameSendmail)) sff |= SFF_NOGWFILES|SFF_NOWWFILES; if (bitnset(DBS_RUNPROGRAMINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_NOPATHCHECK; else sff |= SFF_SAFEDIRPATH; ret = safefile(argv[0], DefUid, DefGid, DefUser, sff, 0, NULL); if (ret != 0) sm_syslog(LOG_INFO, e->e_id, "Warning: prog_open: program %s unsafe: %s", argv[0], sm_errstring(ret)); /* arrange for all the files to be closed */ sm_close_on_exec(STDERR_FILENO + 1, DtableSize); /* now exec the process */ (void) execve(argv[0], (ARGV_T) argv, (ARGV_T) UserEnviron); /* woops! failed */ save_errno = errno; syserr("%s: cannot exec", argv[0]); if (transienterror(save_errno)) _exit(EX_OSERR); _exit(EX_CONFIG); return -1; /* avoid compiler warning on IRIX */ } /* ** GET_COLUMN -- look up a Column in a line buffer ** ** Parameters: ** line -- the raw text line to search. ** col -- the column number to fetch. ** delim -- the delimiter between columns. If null, ** use white space. ** buf -- the output buffer. ** buflen -- the length of buf. ** ** Returns: ** buf if successful. ** NULL otherwise. */ char * get_column(line, col, delim, buf, buflen) char line[]; int col; int delim; char buf[]; int buflen; { char *p; char *begin, *end; int i; char delimbuf[4]; if ((char) delim == '\0') (void) sm_strlcpy(delimbuf, "\n\t ", sizeof(delimbuf)); else { delimbuf[0] = (char) delim; delimbuf[1] = '\0'; } p = line; if (*p == '\0') return NULL; /* line empty */ if (*p == (char) delim && col == 0) return NULL; /* first column empty */ begin = line; if (col == 0 && (char) delim == '\0') { while (*begin != '\0' && isascii(*begin) && isspace(*begin)) begin++; } for (i = 0; i < col; i++) { if ((begin = strpbrk(begin, delimbuf)) == NULL) return NULL; /* no such column */ begin++; if ((char) delim == '\0') { while (*begin != '\0' && isascii(*begin) && isspace(*begin)) begin++; } } end = strpbrk(begin, delimbuf); if (end == NULL) i = strlen(begin); else i = end - begin; if (i >= buflen) i = buflen - 1; (void) sm_strlcpy(buf, begin, i + 1); return buf; } /* ** CLEANSTRCPY -- copy string keeping out bogus characters ** ** Parameters: ** t -- "to" string. ** f -- "from" string. ** l -- length of space available in "to" string. ** ** Returns: ** none. */ void cleanstrcpy(t, f, l) register char *t; register char *f; int l; { /* check for newlines and log if necessary */ (void) denlstring(f, true, true); if (l <= 0) syserr("!cleanstrcpy: length == 0"); l--; while (l > 0 && *f != '\0') { if (isascii(*f) && (isalnum(*f) || strchr("!#$%&'*+-./^_`{|}~", *f) != NULL)) { l--; *t++ = *f; } f++; } *t = '\0'; } /* ** DENLSTRING -- convert newlines in a string to spaces ** ** Parameters: ** s -- the input string ** strict -- if set, don't permit continuation lines. ** logattacks -- if set, log attempted attacks. ** ** Returns: ** A pointer to a version of the string with newlines ** mapped to spaces. This should be copied. */ char * denlstring(s, strict, logattacks) char *s; bool strict; bool logattacks; { register char *p; int l; static char *bp = NULL; static int bl = 0; p = s; while ((p = strchr(p, '\n')) != NULL) if (strict || (*++p != ' ' && *p != '\t')) break; if (p == NULL) return s; l = strlen(s) + 1; if (bl < l) { /* allocate more space */ char *nbp = sm_pmalloc_x(l); if (bp != NULL) sm_free(bp); bp = nbp; bl = l; } (void) sm_strlcpy(bp, s, l); for (p = bp; (p = strchr(p, '\n')) != NULL; ) *p++ = ' '; if (logattacks) { sm_syslog(LOG_NOTICE, CurEnv ? CurEnv->e_id : NULL, "POSSIBLE ATTACK from %.100s: newline in string \"%s\"", RealHostName == NULL ? "[UNKNOWN]" : RealHostName, shortenstring(bp, MAXSHORTSTR)); } return bp; } /* ** STRREPLNONPRT -- replace "unprintable" characters in a string with subst ** ** Parameters: ** s -- string to manipulate (in place) ** subst -- character to use as replacement ** ** Returns: ** true iff string did not contain "unprintable" characters */ bool strreplnonprt(s, c) char *s; int c; { bool ok; ok = true; if (s == NULL) return ok; while (*s != '\0') { if (!(isascii(*s) && isprint(*s))) { *s = c; ok = false; } ++s; } return ok; } /* ** PATH_IS_DIR -- check to see if file exists and is a directory. ** ** There are some additional checks for security violations in ** here. This routine is intended to be used for the host status ** support. ** ** Parameters: ** pathname -- pathname to check for directory-ness. ** createflag -- if set, create directory if needed. ** ** Returns: ** true -- if the indicated pathname is a directory ** false -- otherwise */ bool path_is_dir(pathname, createflag) char *pathname; bool createflag; { struct stat statbuf; #if HASLSTAT if (lstat(pathname, &statbuf) < 0) #else /* HASLSTAT */ if (stat(pathname, &statbuf) < 0) #endif /* HASLSTAT */ { if (errno != ENOENT || !createflag) return false; if (mkdir(pathname, 0755) < 0) return false; return true; } if (!S_ISDIR(statbuf.st_mode)) { errno = ENOTDIR; return false; } /* security: don't allow writable directories */ if (bitset(S_IWGRP|S_IWOTH, statbuf.st_mode)) { errno = EACCES; return false; } return true; } /* ** PROC_LIST_ADD -- add process id to list of our children ** ** Parameters: ** pid -- pid to add to list. ** task -- task of pid. ** type -- type of process. ** count -- number of processes. ** other -- other information for this type. ** ** Returns: ** none ** ** Side Effects: ** May increase CurChildren. May grow ProcList. */ typedef struct procs PROCS_T; struct procs { pid_t proc_pid; char *proc_task; int proc_type; int proc_count; int proc_other; SOCKADDR proc_hostaddr; }; static PROCS_T *volatile ProcListVec = NULL; static int ProcListSize = 0; void proc_list_add(pid, task, type, count, other, hostaddr) pid_t pid; char *task; int type; int count; int other; SOCKADDR *hostaddr; { int i; for (i = 0; i < ProcListSize; i++) { if (ProcListVec[i].proc_pid == NO_PID) break; } if (i >= ProcListSize) { /* probe the existing vector to avoid growing infinitely */ proc_list_probe(); /* now scan again */ for (i = 0; i < ProcListSize; i++) { if (ProcListVec[i].proc_pid == NO_PID) break; } } if (i >= ProcListSize) { /* grow process list */ int chldwasblocked; PROCS_T *npv; SM_ASSERT(ProcListSize < INT_MAX - PROC_LIST_SEG); npv = (PROCS_T *) sm_pmalloc_x((sizeof(*npv)) * (ProcListSize + PROC_LIST_SEG)); /* Block SIGCHLD so reapchild() doesn't mess with us */ chldwasblocked = sm_blocksignal(SIGCHLD); if (ProcListSize > 0) { memmove(npv, ProcListVec, ProcListSize * sizeof(PROCS_T)); sm_free(ProcListVec); } /* XXX just use memset() to initialize this part? */ for (i = ProcListSize; i < ProcListSize + PROC_LIST_SEG; i++) { npv[i].proc_pid = NO_PID; npv[i].proc_task = NULL; npv[i].proc_type = PROC_NONE; } i = ProcListSize; ProcListSize += PROC_LIST_SEG; ProcListVec = npv; if (chldwasblocked == 0) (void) sm_releasesignal(SIGCHLD); } ProcListVec[i].proc_pid = pid; PSTRSET(ProcListVec[i].proc_task, task); ProcListVec[i].proc_type = type; ProcListVec[i].proc_count = count; ProcListVec[i].proc_other = other; if (hostaddr != NULL) ProcListVec[i].proc_hostaddr = *hostaddr; else memset(&ProcListVec[i].proc_hostaddr, 0, sizeof(ProcListVec[i].proc_hostaddr)); /* if process adding itself, it's not a child */ if (pid != CurrentPid) { SM_ASSERT(CurChildren < INT_MAX); CurChildren++; } } /* ** PROC_LIST_SET -- set pid task in process list ** ** Parameters: ** pid -- pid to set ** task -- task of pid ** ** Returns: ** none. */ void proc_list_set(pid, task) pid_t pid; char *task; { int i; for (i = 0; i < ProcListSize; i++) { if (ProcListVec[i].proc_pid == pid) { PSTRSET(ProcListVec[i].proc_task, task); break; } } } /* ** PROC_LIST_DROP -- drop pid from process list ** ** Parameters: ** pid -- pid to drop ** st -- process status ** other -- storage for proc_other (return). ** ** Returns: ** none. ** ** Side Effects: ** May decrease CurChildren, CurRunners, or ** set RestartRequest or ShutdownRequest. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ void proc_list_drop(pid, st, other) pid_t pid; int st; int *other; { int i; int type = PROC_NONE; for (i = 0; i < ProcListSize; i++) { if (ProcListVec[i].proc_pid == pid) { ProcListVec[i].proc_pid = NO_PID; type = ProcListVec[i].proc_type; if (other != NULL) *other = ProcListVec[i].proc_other; if (CurChildren > 0) CurChildren--; break; } } if (type == PROC_CONTROL && WIFEXITED(st)) { /* if so, see if we need to restart or shutdown */ if (WEXITSTATUS(st) == EX_RESTART) RestartRequest = "control socket"; else if (WEXITSTATUS(st) == EX_SHUTDOWN) ShutdownRequest = "control socket"; } else if (type == PROC_QUEUE_CHILD && !WIFSTOPPED(st) && ProcListVec[i].proc_other > -1) { /* restart this persistent runner */ mark_work_group_restart(ProcListVec[i].proc_other, st); } else if (type == PROC_QUEUE) { CurRunners -= ProcListVec[i].proc_count; /* CHK_CUR_RUNNERS() can't be used here: uses syslog() */ if (CurRunners < 0) CurRunners = 0; } } /* ** PROC_LIST_CLEAR -- clear the process list ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** Sets CurChildren to zero. */ void proc_list_clear() { int i; /* start from 1 since 0 is the daemon itself */ for (i = 1; i < ProcListSize; i++) ProcListVec[i].proc_pid = NO_PID; CurChildren = 0; } /* ** PROC_LIST_PROBE -- probe processes in the list to see if they still exist ** ** Parameters: ** none ** ** Returns: ** none ** ** Side Effects: ** May decrease CurChildren. */ void proc_list_probe() { int i, children; int chldwasblocked; pid_t pid; children = 0; chldwasblocked = sm_blocksignal(SIGCHLD); /* start from 1 since 0 is the daemon itself */ for (i = 1; i < ProcListSize; i++) { pid = ProcListVec[i].proc_pid; if (pid == NO_PID || pid == CurrentPid) continue; if (kill(pid, 0) < 0) { if (LogLevel > 3) sm_syslog(LOG_DEBUG, CurEnv->e_id, "proc_list_probe: lost pid %d", (int) ProcListVec[i].proc_pid); ProcListVec[i].proc_pid = NO_PID; SM_FREE_CLR(ProcListVec[i].proc_task); if (ProcListVec[i].proc_type == PROC_QUEUE) { CurRunners -= ProcListVec[i].proc_count; CHK_CUR_RUNNERS("proc_list_probe", i, ProcListVec[i].proc_count); } CurChildren--; } else { ++children; } } if (CurChildren < 0) CurChildren = 0; if (chldwasblocked == 0) (void) sm_releasesignal(SIGCHLD); if (LogLevel > 10 && children != CurChildren && CurrentPid == DaemonPid) { sm_syslog(LOG_ERR, NOQID, "proc_list_probe: found %d children, expected %d", children, CurChildren); } } /* ** PROC_LIST_DISPLAY -- display the process list ** ** Parameters: ** out -- output file pointer ** prefix -- string to output in front of each line. ** ** Returns: ** none. */ void proc_list_display(out, prefix) SM_FILE_T *out; char *prefix; { int i; for (i = 0; i < ProcListSize; i++) { if (ProcListVec[i].proc_pid == NO_PID) continue; (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "%s%d %s%s\n", prefix, (int) ProcListVec[i].proc_pid, ProcListVec[i].proc_task != NULL ? ProcListVec[i].proc_task : "(unknown)", (OpMode == MD_SMTP || OpMode == MD_DAEMON || OpMode == MD_ARPAFTP) ? "\r" : ""); } } /* ** PROC_LIST_SIGNAL -- send a signal to a type of process in the list ** ** Parameters: ** type -- type of process to signal ** signal -- the type of signal to send ** ** Results: ** none. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ void proc_list_signal(type, signal) int type; int signal; { int chldwasblocked; int alrmwasblocked; int i; pid_t mypid = getpid(); /* block these signals so that we may signal cleanly */ chldwasblocked = sm_blocksignal(SIGCHLD); alrmwasblocked = sm_blocksignal(SIGALRM); /* Find all processes of type and send signal */ for (i = 0; i < ProcListSize; i++) { if (ProcListVec[i].proc_pid == NO_PID || ProcListVec[i].proc_pid == mypid) continue; if (ProcListVec[i].proc_type != type) continue; (void) kill(ProcListVec[i].proc_pid, signal); } /* restore the signals */ if (alrmwasblocked == 0) (void) sm_releasesignal(SIGALRM); if (chldwasblocked == 0) (void) sm_releasesignal(SIGCHLD); } /* ** COUNT_OPEN_CONNECTIONS ** ** Parameters: ** hostaddr - ClientAddress ** ** Returns: ** the number of open connections for this client ** */ int count_open_connections(hostaddr) SOCKADDR *hostaddr; { int i, n; if (hostaddr == NULL) return 0; /* ** This code gets called before proc_list_add() gets called, ** so we (the daemon child for this connection) have not yet ** counted ourselves. Hence initialize the counter to 1 ** instead of 0 to compensate. */ n = 1; for (i = 0; i < ProcListSize; i++) { if (ProcListVec[i].proc_pid == NO_PID) continue; if (hostaddr->sa.sa_family != ProcListVec[i].proc_hostaddr.sa.sa_family) continue; #if NETINET if (hostaddr->sa.sa_family == AF_INET && (hostaddr->sin.sin_addr.s_addr == ProcListVec[i].proc_hostaddr.sin.sin_addr.s_addr)) n++; #endif /* NETINET */ #if NETINET6 if (hostaddr->sa.sa_family == AF_INET6 && IN6_ARE_ADDR_EQUAL(&(hostaddr->sin6.sin6_addr), &(ProcListVec[i].proc_hostaddr.sin6.sin6_addr))) n++; #endif /* NETINET6 */ } return n; } Index: head/contrib/sendmail/src/version.c =================================================================== --- head/contrib/sendmail/src/version.c (revision 249728) +++ head/contrib/sendmail/src/version.c (revision 249729) @@ -1,18 +1,18 @@ /* - * Copyright (c) 1998-2012 Sendmail, Inc. and its suppliers. + * Copyright (c) 1998-2013 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983 Eric P. Allman. All rights reserved. * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include -SM_RCSID("@(#)$Id: version.c,v 8.235 2012/12/19 05:11:44 ca Exp $") +SM_RCSID("@(#)$Id: version.c,v 8.243 2013/04/18 15:07:17 ca Exp $") -char Version[] = "8.14.6"; +char Version[] = "8.14.7"; Index: head/contrib/sendmail/test/Makefile.m4 =================================================================== --- head/contrib/sendmail/test/Makefile.m4 (revision 249728) +++ head/contrib/sendmail/test/Makefile.m4 (revision 249729) @@ -1,19 +1,19 @@ -dnl $Id: Makefile.m4,v 1.4 2002/06/21 22:01:54 ca Exp $ +dnl $Id: Makefile.m4,v 1.6 2013/04/01 21:04:29 ca Exp $ include(confBUILDTOOLSDIR`/M4/switch.m4') bldPRODUCT_START(`executable', `test') define(`bldSOURCES', `t_dropgid.c ') bldPRODUCT_END include(confBUILDTOOLSDIR`/M4/'bldM4_TYPE_DIR`/sm-test.m4') dnl smtest(`getipnode') smtest(`t_dropgid') smtest(`t_exclopen') smtest(`t_pathconf') smtest(`t_seteuid') smtest(`t_setgid') smtest(`t_setreuid') smtest(`t_setuid') dnl smtest(`t_snprintf') bldFINISH Index: head/contrib/sendmail/vacation/vacation.c =================================================================== --- head/contrib/sendmail/vacation/vacation.c (revision 249728) +++ head/contrib/sendmail/vacation/vacation.c (revision 249729) @@ -1,1197 +1,1197 @@ /* * Copyright (c) 1999-2002, 2009 Sendmail, Inc. and its suppliers. * All rights reserved. * Copyright (c) 1983, 1987, 1993 * The Regents of the University of California. All rights reserved. * Copyright (c) 1983 Eric P. Allman. All rights reserved. * * By using this file, you agree to the terms and conditions set * forth in the LICENSE file which can be found at the top level of * the sendmail distribution. * */ #include SM_IDSTR(copyright, "@(#) Copyright (c) 1999-2002, 2009 Sendmail, Inc. and its suppliers.\n\ All rights reserved.\n\ Copyright (c) 1983, 1987, 1993\n\ The Regents of the University of California. All rights reserved.\n\ Copyright (c) 1983 Eric P. Allman. All rights reserved.\n") -SM_IDSTR(id, "@(#)$Id: vacation.c,v 8.146 2009/08/07 21:28:39 ca Exp $") +SM_IDSTR(id, "@(#)$Id: vacation.c,v 8.147 2013/03/12 15:24:56 ca Exp $") #include #include #include #include #include #ifdef EX_OK # undef EX_OK /* unistd.h may have another use for this */ #endif /* EX_OK */ #include #include #include #include "sendmail/sendmail.h" #include #include "libsmdb/smdb.h" #define ONLY_ONCE ((time_t) 0) /* send at most one reply */ #define INTERVAL_UNDEF ((time_t) (-1)) /* no value given */ uid_t RealUid; gid_t RealGid; char *RealUserName; uid_t RunAsUid; gid_t RunAsGid; char *RunAsUserName; int Verbose = 2; bool DontInitGroups = false; uid_t TrustedUid = 0; BITMAP256 DontBlameSendmail; static int readheaders __P((bool)); static bool junkmail __P((char *)); static bool nsearch __P((char *, char *)); static void usage __P((void)); static void setinterval __P((time_t)); static bool recent __P((void)); static void setreply __P((char *, time_t)); static void sendmessage __P((char *, char *, char *)); static void xclude __P((SM_FILE_T *)); /* ** VACATION -- return a message to the sender when on vacation. ** ** This program is invoked as a message receiver. It returns a ** message specified by the user to whomever sent the mail, taking ** care not to return a message too often to prevent "I am on ** vacation" loops. */ #define VDB ".vacation" /* vacation database */ #define VMSG ".vacation.msg" /* vacation message */ #define SECSPERDAY (60 * 60 * 24) #define DAYSPERWEEK 7 typedef struct alias { char *name; struct alias *next; } ALIAS; ALIAS *Names = NULL; SMDB_DATABASE *Db; char From[MAXLINE]; bool CloseMBDB = false; #if defined(__hpux) || defined(__osf__) # ifndef SM_CONF_SYSLOG_INT # define SM_CONF_SYSLOG_INT 1 # endif /* SM_CONF_SYSLOG_INT */ #endif /* defined(__hpux) || defined(__osf__) */ #if SM_CONF_SYSLOG_INT # define SYSLOG_RET_T int # define SYSLOG_RET return 0 #else /* SM_CONF_SYSLOG_INT */ # define SYSLOG_RET_T void # define SYSLOG_RET #endif /* SM_CONF_SYSLOG_INT */ typedef SYSLOG_RET_T SYSLOG_T __P((int, const char *, ...)); SYSLOG_T *msglog = syslog; static SYSLOG_RET_T debuglog __P((int, const char *, ...)); static void eatmsg __P((void)); static void listdb __P((void)); /* exit after reading input */ #define EXITIT(excode) \ { \ eatmsg(); \ if (CloseMBDB) \ { \ sm_mbdb_terminate(); \ CloseMBDB = false; \ } \ return excode; \ } #define EXITM(excode) \ { \ if (!initdb && !list) \ eatmsg(); \ if (CloseMBDB) \ { \ sm_mbdb_terminate(); \ CloseMBDB = false; \ } \ exit(excode); \ } int main(argc, argv) int argc; char **argv; { bool alwaysrespond = false; bool initdb, exclude; bool runasuser = false; bool list = false; int mfail = 0, ufail = 0; int ch; int result; long sff; time_t interval; struct passwd *pw; ALIAS *cur; char *dbfilename = NULL; char *msgfilename = NULL; char *cfpath = NULL; char *name = NULL; char *returnaddr = NULL; SMDB_USER_INFO user_info; static char rnamebuf[MAXNAME]; extern int optind, opterr; extern char *optarg; /* Vars needed to link with smutil */ clrbitmap(DontBlameSendmail); RunAsUid = RealUid = getuid(); RunAsGid = RealGid = getgid(); pw = getpwuid(RealUid); if (pw != NULL) { if (strlen(pw->pw_name) > MAXNAME - 1) pw->pw_name[MAXNAME] = '\0'; sm_snprintf(rnamebuf, sizeof rnamebuf, "%s", pw->pw_name); } else sm_snprintf(rnamebuf, sizeof rnamebuf, "Unknown UID %d", (int) RealUid); RunAsUserName = RealUserName = rnamebuf; # ifdef LOG_MAIL openlog("vacation", LOG_PID, LOG_MAIL); # else /* LOG_MAIL */ openlog("vacation", LOG_PID); # endif /* LOG_MAIL */ opterr = 0; initdb = false; exclude = false; interval = INTERVAL_UNDEF; *From = '\0'; #define OPTIONS "a:C:df:Iijlm:R:r:s:t:Uxz" while (mfail == 0 && ufail == 0 && (ch = getopt(argc, argv, OPTIONS)) != -1) { switch((char)ch) { case 'a': /* alias */ cur = (ALIAS *) malloc((unsigned int) sizeof(ALIAS)); if (cur == NULL) { mfail++; break; } cur->name = optarg; cur->next = Names; Names = cur; break; case 'C': cfpath = optarg; break; case 'd': /* debug mode */ msglog = debuglog; break; case 'f': /* alternate database */ dbfilename = optarg; break; case 'I': /* backward compatible */ case 'i': /* init the database */ initdb = true; break; case 'j': alwaysrespond = true; break; case 'l': list = true; /* list the database */ break; case 'm': /* alternate message file */ msgfilename = optarg; break; case 'R': returnaddr = optarg; break; case 'r': if (isascii(*optarg) && isdigit(*optarg)) { interval = atol(optarg) * SECSPERDAY; if (interval < 0) ufail++; } else interval = ONLY_ONCE; break; case 's': /* alternate sender name */ (void) sm_strlcpy(From, optarg, sizeof From); break; case 't': /* SunOS: -t1d (default expire) */ break; case 'U': /* run as single user mode */ runasuser = true; break; case 'x': exclude = true; break; case 'z': returnaddr = "<>"; break; case '?': default: ufail++; break; } } argc -= optind; argv += optind; if (mfail != 0) { msglog(LOG_NOTICE, "vacation: can't allocate memory for alias.\n"); EXITM(EX_TEMPFAIL); } if (ufail != 0) usage(); if (argc != 1) { if (!initdb && !list && !exclude) usage(); if ((pw = getpwuid(getuid())) == NULL) { msglog(LOG_ERR, "vacation: no such user uid %u.\n", getuid()); EXITM(EX_NOUSER); } name = strdup(pw->pw_name); user_info.smdbu_id = pw->pw_uid; user_info.smdbu_group_id = pw->pw_gid; (void) sm_strlcpy(user_info.smdbu_name, pw->pw_name, SMDB_MAX_USER_NAME_LEN); if (chdir(pw->pw_dir) != 0) { msglog(LOG_NOTICE, "vacation: no such directory %s.\n", pw->pw_dir); EXITM(EX_NOINPUT); } } else if (runasuser) { name = strdup(*argv); if (dbfilename == NULL || msgfilename == NULL) { msglog(LOG_NOTICE, "vacation: -U requires setting both -f and -m\n"); EXITM(EX_NOINPUT); } user_info.smdbu_id = pw->pw_uid; user_info.smdbu_group_id = pw->pw_gid; (void) sm_strlcpy(user_info.smdbu_name, pw->pw_name, SMDB_MAX_USER_NAME_LEN); } else { int err; SM_CF_OPT_T mbdbname; SM_MBDB_T user; cfpath = getcfname(0, 0, SM_GET_SENDMAIL_CF, cfpath); mbdbname.opt_name = "MailboxDatabase"; mbdbname.opt_val = "pw"; (void) sm_cf_getopt(cfpath, 1, &mbdbname); err = sm_mbdb_initialize(mbdbname.opt_val); if (err != EX_OK) { msglog(LOG_ERR, "vacation: can't open mailbox database: %s.\n", sm_strexit(err)); EXITM(err); } CloseMBDB = true; err = sm_mbdb_lookup(*argv, &user); if (err == EX_NOUSER) { msglog(LOG_ERR, "vacation: no such user %s.\n", *argv); EXITM(EX_NOUSER); } if (err != EX_OK) { msglog(LOG_ERR, "vacation: can't read mailbox database: %s.\n", sm_strexit(err)); EXITM(err); } name = strdup(user.mbdb_name); if (chdir(user.mbdb_homedir) != 0) { msglog(LOG_NOTICE, "vacation: no such directory %s.\n", user.mbdb_homedir); EXITM(EX_NOINPUT); } user_info.smdbu_id = user.mbdb_uid; user_info.smdbu_group_id = user.mbdb_gid; (void) sm_strlcpy(user_info.smdbu_name, user.mbdb_name, SMDB_MAX_USER_NAME_LEN); } if (name == NULL) { msglog(LOG_ERR, "vacation: can't allocate memory for username.\n"); EXITM(EX_OSERR); } if (dbfilename == NULL) dbfilename = VDB; if (msgfilename == NULL) msgfilename = VMSG; sff = SFF_CREAT; if (getegid() != getgid()) { /* Allow a set-group-ID vacation binary */ RunAsGid = user_info.smdbu_group_id = getegid(); sff |= SFF_OPENASROOT; } if (getuid() == 0) { /* Allow root to initialize user's vacation databases */ sff |= SFF_OPENASROOT|SFF_ROOTOK; /* ... safely */ sff |= SFF_NOSLINK|SFF_NOHLINK|SFF_REGONLY; } result = smdb_open_database(&Db, dbfilename, O_CREAT|O_RDWR | (initdb ? O_TRUNC : 0), S_IRUSR|S_IWUSR, sff, SMDB_TYPE_DEFAULT, &user_info, NULL); if (result != SMDBE_OK) { msglog(LOG_NOTICE, "vacation: %s: %s\n", dbfilename, sm_errstring(result)); EXITM(EX_DATAERR); } if (list) { listdb(); (void) Db->smdb_close(Db); exit(EX_OK); } if (interval != INTERVAL_UNDEF) setinterval(interval); if (initdb && !exclude) { (void) Db->smdb_close(Db); exit(EX_OK); } if (exclude) { xclude(smioin); (void) Db->smdb_close(Db); EXITM(EX_OK); } if ((cur = (ALIAS *) malloc((unsigned int) sizeof(ALIAS))) == NULL) { msglog(LOG_NOTICE, "vacation: can't allocate memory for username.\n"); (void) Db->smdb_close(Db); EXITM(EX_OSERR); } cur->name = name; cur->next = Names; Names = cur; result = readheaders(alwaysrespond); if (result == EX_OK && !recent()) { time_t now; (void) time(&now); setreply(From, now); (void) Db->smdb_close(Db); sendmessage(name, msgfilename, returnaddr); } else (void) Db->smdb_close(Db); if (result == EX_NOUSER) result = EX_OK; exit(result); } /* ** EATMSG -- read stdin till EOF ** ** Parameters: ** none. ** ** Returns: ** nothing. ** */ static void eatmsg() { /* ** read the rest of the e-mail and ignore it to avoid problems ** with EPIPE in sendmail */ while (getc(stdin) != EOF) continue; } /* ** READHEADERS -- read mail headers ** ** Parameters: ** alwaysrespond -- respond regardless of whether msg is to me ** ** Returns: ** a exit code: NOUSER if no reply, OK if reply, * if error ** ** Side Effects: ** may exit(). ** */ static int readheaders(alwaysrespond) bool alwaysrespond; { bool tome, cont; register char *p; register ALIAS *cur; char buf[MAXLINE]; cont = false; tome = alwaysrespond; - while (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf, sizeof(buf)) && + while (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0 && *buf != '\n') { switch(*buf) { case 'F': /* "From " */ cont = false; if (strncmp(buf, "From ", 5) == 0) { bool quoted = false; p = buf + 5; while (*p != '\0') { /* escaped character */ if (*p == '\\') { p++; if (*p == '\0') { msglog(LOG_NOTICE, "vacation: badly formatted \"From \" line.\n"); EXITIT(EX_DATAERR); } } else if (*p == '"') quoted = !quoted; else if (*p == '\r' || *p == '\n') break; else if (*p == ' ' && !quoted) break; p++; } if (quoted) { msglog(LOG_NOTICE, "vacation: badly formatted \"From \" line.\n"); EXITIT(EX_DATAERR); } *p = '\0'; /* ok since both strings have MAXLINE length */ if (*From == '\0') (void) sm_strlcpy(From, buf + 5, sizeof From); if ((p = strchr(buf + 5, '\n')) != NULL) *p = '\0'; if (junkmail(buf + 5)) EXITIT(EX_NOUSER); } break; case 'P': /* "Precedence:" */ case 'p': cont = false; if (strlen(buf) <= 10 || strncasecmp(buf, "Precedence", 10) != 0 || (buf[10] != ':' && buf[10] != ' ' && buf[10] != '\t')) break; if ((p = strchr(buf, ':')) == NULL) break; while (*++p != '\0' && isascii(*p) && isspace(*p)); if (*p == '\0') break; if (strncasecmp(p, "junk", 4) == 0 || strncasecmp(p, "bulk", 4) == 0 || strncasecmp(p, "list", 4) == 0) EXITIT(EX_NOUSER); break; case 'C': /* "Cc:" */ case 'c': if (strncasecmp(buf, "Cc:", 3) != 0) break; cont = true; goto findme; case 'T': /* "To:" */ case 't': if (strncasecmp(buf, "To:", 3) != 0) break; cont = true; goto findme; default: if (!isascii(*buf) || !isspace(*buf) || !cont || tome) { cont = false; break; } findme: for (cur = Names; !tome && cur != NULL; cur = cur->next) tome = nsearch(cur->name, buf); } } if (!tome) EXITIT(EX_NOUSER); if (*From == '\0') { msglog(LOG_NOTICE, "vacation: no initial \"From \" line.\n"); EXITIT(EX_DATAERR); } EXITIT(EX_OK); } /* ** NSEARCH -- ** do a nice, slow, search of a string for a substring. ** ** Parameters: ** name -- name to search. ** str -- string in which to search. ** ** Returns: ** is name a substring of str? ** */ static bool nsearch(name, str) register char *name, *str; { register size_t len; register char *s; len = strlen(name); for (s = str; *s != '\0'; ++s) { /* ** Check to make sure that the string matches and ** the previous character is not an alphanumeric and ** the next character after the match is not an alphanumeric. ** ** This prevents matching "eric" to "derick" while still ** matching "eric" to "". */ if (tolower(*s) == tolower(*name) && strncasecmp(name, s, len) == 0 && (s == str || !isascii(*(s - 1)) || !isalnum(*(s - 1))) && (!isascii(*(s + len)) || !isalnum(*(s + len)))) return true; } return false; } /* ** JUNKMAIL -- ** read the header and return if automagic/junk/bulk/list mail ** ** Parameters: ** from -- sender address. ** ** Returns: ** is this some automated/junk/bulk/list mail? ** */ struct ignore { char *name; size_t len; }; typedef struct ignore IGNORE_T; #define MAX_USER_LEN 256 /* maximum length of local part (sender) */ /* delimiters for the local part of an address */ #define isdelim(c) ((c) == '%' || (c) == '@' || (c) == '+') static bool junkmail(from) char *from; { bool quot; char *e; size_t len; IGNORE_T *cur; char sender[MAX_USER_LEN]; static IGNORE_T ignore[] = { { "postmaster", 10 }, { "uucp", 4 }, { "mailer-daemon", 13 }, { "mailer", 6 }, { NULL, 0 } }; static IGNORE_T ignorepost[] = { { "-request", 8 }, { "-relay", 6 }, { "-owner", 6 }, { NULL, 0 } }; static IGNORE_T ignorepre[] = { { "owner-", 6 }, { NULL, 0 } }; /* ** This is mildly amusing, and I'm not positive it's right; trying ** to find the "real" name of the sender, assuming that addresses ** will be some variant of: ** ** From site!site!SENDER%site.domain%site.domain@site.domain */ quot = false; e = from; len = 0; while (*e != '\0' && (quot || !isdelim(*e))) { if (*e == '"') { quot = !quot; ++e; continue; } if (*e == '\\') { if (*(++e) == '\0') { /* '\\' at end of string? */ break; } if (len < MAX_USER_LEN) sender[len++] = *e; ++e; continue; } if (*e == '!' && !quot) { len = 0; sender[len] = '\0'; } else if (len < MAX_USER_LEN) sender[len++] = *e; ++e; } if (len < MAX_USER_LEN) sender[len] = '\0'; else sender[MAX_USER_LEN - 1] = '\0'; if (len <= 0) return false; #if 0 if (quot) return false; /* syntax error... */ #endif /* 0 */ /* test prefixes */ for (cur = ignorepre; cur->name != NULL; ++cur) { if (len >= cur->len && strncasecmp(cur->name, sender, cur->len) == 0) return true; } /* ** If the name is truncated, don't test the rest. ** We could extract the "tail" of the sender address and ** compare it it ignorepost, however, it seems not worth ** the effort. ** The address surely can't match any entry in ignore[] ** (as long as all of them are shorter than MAX_USER_LEN). */ if (len > MAX_USER_LEN) return false; /* test full local parts */ for (cur = ignore; cur->name != NULL; ++cur) { if (len == cur->len && strncasecmp(cur->name, sender, cur->len) == 0) return true; } /* test postfixes */ for (cur = ignorepost; cur->name != NULL; ++cur) { if (len >= cur->len && strncasecmp(cur->name, e - cur->len - 1, cur->len) == 0) return true; } return false; } #define VIT "__VACATION__INTERVAL__TIMER__" /* ** RECENT -- ** find out if user has gotten a vacation message recently. ** ** Parameters: ** none. ** ** Returns: ** true iff user has gotten a vacation message recently. ** */ static bool recent() { SMDB_DBENT key, data; time_t then, next; bool trydomain = false; int st; char *domain; memset(&key, '\0', sizeof key); memset(&data, '\0', sizeof data); /* get interval time */ key.data = VIT; key.size = sizeof(VIT); st = Db->smdb_get(Db, &key, &data, 0); if (st != SMDBE_OK) next = SECSPERDAY * DAYSPERWEEK; else memmove(&next, data.data, sizeof(next)); memset(&data, '\0', sizeof data); /* get record for this address */ key.data = From; key.size = strlen(From); do { st = Db->smdb_get(Db, &key, &data, 0); if (st == SMDBE_OK) { memmove(&then, data.data, sizeof(then)); if (next == ONLY_ONCE || then == ONLY_ONCE || then + next > time(NULL)) return true; } if ((trydomain = !trydomain) && (domain = strchr(From, '@')) != NULL) { key.data = domain; key.size = strlen(domain); } } while (trydomain); return false; } /* ** SETINTERVAL -- ** store the reply interval ** ** Parameters: ** interval -- time interval for replies. ** ** Returns: ** nothing. ** ** Side Effects: ** stores the reply interval in database. */ static void setinterval(interval) time_t interval; { SMDB_DBENT key, data; memset(&key, '\0', sizeof key); memset(&data, '\0', sizeof data); key.data = VIT; key.size = sizeof(VIT); data.data = (char*) &interval; data.size = sizeof(interval); (void) (Db->smdb_put)(Db, &key, &data, 0); } /* ** SETREPLY -- ** store that this user knows about the vacation. ** ** Parameters: ** from -- sender address. ** when -- last reply time. ** ** Returns: ** nothing. ** ** Side Effects: ** stores user/time in database. */ static void setreply(from, when) char *from; time_t when; { SMDB_DBENT key, data; memset(&key, '\0', sizeof key); memset(&data, '\0', sizeof data); key.data = from; key.size = strlen(from); data.data = (char*) &when; data.size = sizeof(when); (void) (Db->smdb_put)(Db, &key, &data, 0); } /* ** XCLUDE -- ** add users to vacation db so they don't get a reply. ** ** Parameters: ** f -- file pointer with list of address to exclude ** ** Returns: ** nothing. ** ** Side Effects: ** stores users in database. */ static void xclude(f) SM_FILE_T *f; { char buf[MAXLINE], *p; if (f == NULL) return; - while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof buf)) + while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof buf) >= 0) { if ((p = strchr(buf, '\n')) != NULL) *p = '\0'; setreply(buf, ONLY_ONCE); } } /* ** SENDMESSAGE -- ** exec sendmail to send the vacation file to sender ** ** Parameters: ** myname -- user name. ** msgfn -- name of file with vacation message. ** sender -- use as sender address ** ** Returns: ** nothing. ** ** Side Effects: ** sends vacation reply. */ static void sendmessage(myname, msgfn, sender) char *myname; char *msgfn; char *sender; { SM_FILE_T *mfp, *sfp; int i; int pvect[2]; char *pv[8]; char buf[MAXLINE]; mfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, msgfn, SM_IO_RDONLY, NULL); if (mfp == NULL) { if (msgfn[0] == '/') msglog(LOG_NOTICE, "vacation: no %s file.\n", msgfn); else msglog(LOG_NOTICE, "vacation: no ~%s/%s file.\n", myname, msgfn); exit(EX_NOINPUT); } if (pipe(pvect) < 0) { msglog(LOG_ERR, "vacation: pipe: %s", sm_errstring(errno)); exit(EX_OSERR); } pv[0] = "sendmail"; pv[1] = "-oi"; pv[2] = "-f"; if (sender != NULL) pv[3] = sender; else pv[3] = myname; pv[4] = "--"; pv[5] = From; pv[6] = NULL; i = fork(); if (i < 0) { msglog(LOG_ERR, "vacation: fork: %s", sm_errstring(errno)); exit(EX_OSERR); } if (i == 0) { (void) dup2(pvect[0], 0); (void) close(pvect[0]); (void) close(pvect[1]); (void) sm_io_close(mfp, SM_TIME_DEFAULT); (void) execv(_PATH_SENDMAIL, pv); msglog(LOG_ERR, "vacation: can't exec %s: %s", _PATH_SENDMAIL, sm_errstring(errno)); exit(EX_UNAVAILABLE); } /* check return status of the following calls? XXX */ (void) close(pvect[0]); if ((sfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &(pvect[1]), SM_IO_WRONLY, NULL)) != NULL) { #if _FFR_VAC_WAIT4SM # ifdef WAITUNION union wait st; # else /* WAITUNION */ auto int st; # endif /* WAITUNION */ #endif /* _FFR_VAC_WAIT4SM */ (void) sm_io_fprintf(sfp, SM_TIME_DEFAULT, "To: %s\n", From); (void) sm_io_fprintf(sfp, SM_TIME_DEFAULT, "Auto-Submitted: auto-replied\n"); - while (sm_io_fgets(mfp, SM_TIME_DEFAULT, buf, sizeof buf)) + while (sm_io_fgets(mfp, SM_TIME_DEFAULT, buf, sizeof buf) >= 0) (void) sm_io_fputs(sfp, SM_TIME_DEFAULT, buf); (void) sm_io_close(mfp, SM_TIME_DEFAULT); (void) sm_io_close(sfp, SM_TIME_DEFAULT); #if _FFR_VAC_WAIT4SM (void) wait(&st); #endif /* _FFR_VAC_WAIT4SM */ } else { (void) sm_io_close(mfp, SM_TIME_DEFAULT); msglog(LOG_ERR, "vacation: can't open pipe to sendmail"); exit(EX_UNAVAILABLE); } } static void usage() { msglog(LOG_NOTICE, "uid %u: usage: vacation [-a alias] [-C cfpath] [-d] [-f db] [-i] [-j] [-l] [-m msg] [-R returnaddr] [-r interval] [-s sender] [-t time] [-U] [-x] [-z] login\n", getuid()); exit(EX_USAGE); } /* ** LISTDB -- list the contents of the vacation database ** ** Parameters: ** none. ** ** Returns: ** nothing. */ static void listdb() { int result; time_t t; SMDB_CURSOR *cursor = NULL; SMDB_DBENT db_key, db_value; memset(&db_key, '\0', sizeof db_key); memset(&db_value, '\0', sizeof db_value); result = Db->smdb_cursor(Db, &cursor, 0); if (result != SMDBE_OK) { sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "vacation: set cursor: %s\n", sm_errstring(result)); return; } while ((result = cursor->smdbc_get(cursor, &db_key, &db_value, SMDB_CURSOR_GET_NEXT)) == SMDBE_OK) { char *timestamp; /* skip magic VIT entry */ if (db_key.size == strlen(VIT) + 1 && strncmp((char *)db_key.data, VIT, (int)db_key.size - 1) == 0) continue; /* skip bogus values */ if (db_value.size != sizeof t) { sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "vacation: %.*s invalid time stamp\n", (int) db_key.size, (char *) db_key.data); continue; } memcpy(&t, db_value.data, sizeof t); if (db_key.size > 40) db_key.size = 40; if (t <= 0) { /* must be an exclude */ timestamp = "(exclusion)\n"; } else { timestamp = ctime(&t); } sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%-40.*s %-10s", (int) db_key.size, (char *) db_key.data, timestamp); memset(&db_key, '\0', sizeof db_key); memset(&db_value, '\0', sizeof db_value); } if (result != SMDBE_OK && result != SMDBE_LAST_ENTRY) { sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "vacation: get value at cursor: %s\n", sm_errstring(result)); if (cursor != NULL) { (void) cursor->smdbc_close(cursor); cursor = NULL; } return; } (void) cursor->smdbc_close(cursor); cursor = NULL; } /* ** DEBUGLOG -- write message to standard error ** ** Append a message to the standard error for the convenience of ** end-users debugging without access to the syslog messages. ** ** Parameters: ** i -- syslog log level ** fmt -- string format ** ** Returns: ** nothing. */ /*VARARGS2*/ static SYSLOG_RET_T #ifdef __STDC__ debuglog(int i, const char *fmt, ...) #else /* __STDC__ */ debuglog(i, fmt, va_alist) int i; const char *fmt; va_dcl #endif /* __STDC__ */ { SM_VA_LOCAL_DECL SM_VA_START(ap, fmt); sm_io_vfprintf(smioerr, SM_TIME_DEFAULT, fmt, ap); SM_VA_END(ap); SYSLOG_RET; } Index: head/contrib/sendmail =================================================================== --- head/contrib/sendmail (revision 249728) +++ head/contrib/sendmail (revision 249729) Property changes on: head/contrib/sendmail ___________________________________________________________________ Modified: svn:mergeinfo ## -0,0 +0,1 ## Merged /vendor/sendmail/dist:r244833-246945,246947-249728