4 * Deliver_SMTP.class.php
6 * SMTP delivery backend for the Deliver class.
8 * @copyright © 1999-2006 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @package squirrelmail
15 if (!defined('SM_PATH')) define('SM_PATH','../../');
17 /** This of course depends upon Deliver */
18 include_once(SM_PATH
. 'class/deliver/Deliver.class.php');
21 * Deliver messages using SMTP
22 * @package squirrelmail
24 class Deliver_SMTP
extends Deliver
{
26 * Array keys are uppercased ehlo keywords
27 * array key values are ehlo params. If ehlo-param contains space, it is splitted into array.
38 * SMTP STARTTLS rfc: "Both the client and the server MUST know if there
39 * is a TLS session active."
40 * Variable should be set to true, when encryption is turned on.
44 var $tls_enabled = false;
48 * @todo don't pass stream resource in class method arguments.
50 //var $stream = false;
51 /** @var string delivery error message */
53 /** @var integer delivery error number from server */
55 /** @var string delivery error message from server */
56 var $dlv_server_msg = '';
58 function preWriteToStream(&$s) {
60 if ($s{0} == '.') $s = '.' . $s;
61 $s = str_replace("\n.","\n..",$s);
65 function initStream($message, $domain, $length=0, $host='', $port='', $user='', $pass='', $authpop=false) {
66 global $use_smtp_tls,$smtp_auth_mech;
69 $this->authPop($host, '', $user, $pass);
72 $rfc822_header = $message->rfc822_header
;
74 $from = $rfc822_header->from
[0];
75 $to = $rfc822_header->to
;
76 $cc = $rfc822_header->cc
;
77 $bcc = $rfc822_header->bcc
;
78 $content_type = $rfc822_header->content_type
;
80 // MAIL FROM: <from address> MUST be empty in cae of MDN (RFC2298)
81 if ($content_type->type0
== 'multipart' &&
82 $content_type->type1
== 'report' &&
83 isset($content_type->properties
['report-type']) &&
84 $content_type->properties
['report-type']=='disposition-notification') {
89 if ($use_smtp_tls == 1) {
90 if ((check_php_version(4,3)) && (extension_loaded('openssl'))) {
91 $stream = @fsockopen
('tls://' . $host, $port, $errorNumber, $errorString);
92 $this->tls_enabled
= true;
95 * don't connect to server when user asks for smtps and
96 * PHP does not support it.
99 $errorString = _("Secure SMTP (TLS) is enabled in SquirrelMail configuration, but used PHP version does not support it.");
102 $stream = @fsockopen
($host, $port, $errorNumber, $errorString);
106 // reset tls state var to default value, if connection fails
107 $this->tls_enabled
= false;
108 // set error messages
109 $this->dlv_msg
= $errorString;
110 $this->dlv_ret_nr
= $errorNumber;
111 $this->dlv_server_msg
= _("Can't open SMTP stream.");
114 // get server greeting
115 $tmp = fgets($stream, 1024);
116 if ($this->errorCheck($tmp, $stream)) {
121 * If $_SERVER['HTTP_HOST'] is set, use that in our HELO to the SMTP
122 * server. This should fix the DNS issues some people have had
124 if (sqgetGlobalVar('HTTP_HOST', $HTTP_HOST, SQ_SERVER
)) { // HTTP_HOST is set
125 // optionally trim off port number
126 if($p = strrpos($HTTP_HOST, ':')) {
127 $HTTP_HOST = substr($HTTP_HOST, 0, $p);
129 $helohost = $HTTP_HOST;
130 } else { // For some reason, HTTP_HOST is not set - revert to old behavior
134 /* Lets introduce ourselves */
135 fputs($stream, "EHLO $helohost\r\n");
136 // Read ehlo response
137 $tmp = $this->parse_ehlo_response($stream);
138 if ($this->errorCheck($tmp,$stream)) {
139 // fall back to HELO if EHLO is not supported
140 if ($this->dlv_ret_nr
== '500') {
141 fputs($stream, "HELO $helohost\r\n");
142 $tmp = fgets($stream,1024);
143 if ($this->errorCheck($tmp,$stream)) {
152 * Implementing SMTP STARTTLS (rfc2487) in php 5.1.0+
153 * http://www.php.net/stream-socket-enable-crypto
155 if ($use_smtp_tls === 2) {
156 if (function_exists('stream_socket_enable_crypto')) {
157 // don't try starting tls, when client thinks that it is already active
158 if ($this->tls_enabled
) {
159 $this->dlv_msg
= _("TLS session is already activated.");
161 } elseif (!array_key_exists('STARTTLS',$this->ehlo
)) {
162 // check for starttls in ehlo response
163 $this->dlv_msg
= _("SMTP STARTTLS is enabled in SquirrelMail configuration, but used SMTP server does not support it");
167 // issue starttls command
168 fputs($stream, "STARTTLS\r\n");
170 $tmp = fgets($stream,1024);
171 if ($this->errorCheck($tmp,$stream)) {
175 // start crypto on connection. suppress function errors.
176 if (@stream_socket_enable_crypto
($stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT
)) {
177 // starttls was successful (rfc2487 5.2 Result of the STARTTLS Command)
178 // get new EHLO response
179 fputs($stream, "EHLO $helohost\r\n");
180 // Read ehlo response
181 $tmp = $this->parse_ehlo_response($stream);
182 if ($this->errorCheck($tmp,$stream)) {
183 // don't revert to helo here. server must support ESMTP
186 // set information about started tls
187 $this->tls_enabled
= true;
190 * stream_socket_enable_crypto() call failed.
192 $this->dlv_msg
= _("Unable to start TLS.");
194 // Bug: can't get error message. See comments in sqimap_create_stream().
197 // php install does not support stream_socket_enable_crypto() function
198 $this->dlv_msg
= _("SMTP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket.");
203 // FIXME: check ehlo response before using authentication
204 if (( $smtp_auth_mech == 'cram-md5') or ( $smtp_auth_mech == 'digest-md5' )) {
205 // Doing some form of non-plain auth
206 if ($smtp_auth_mech == 'cram-md5') {
207 fputs($stream, "AUTH CRAM-MD5\r\n");
208 } elseif ($smtp_auth_mech == 'digest-md5') {
209 fputs($stream, "AUTH DIGEST-MD5\r\n");
212 $tmp = fgets($stream,1024);
214 if ($this->errorCheck($tmp,$stream)) {
218 // At this point, $tmp should hold "334 <challenge string>"
219 $chall = substr($tmp,4);
220 // Depending on mechanism, generate response string
221 if ($smtp_auth_mech == 'cram-md5') {
222 $response = cram_md5_response($user,$pass,$chall);
223 } elseif ($smtp_auth_mech == 'digest-md5') {
224 $response = digest_md5_response($user,$pass,$chall,'smtp',$host);
226 fputs($stream, $response);
228 // Let's see what the server had to say about that
229 $tmp = fgets($stream,1024);
230 if ($this->errorCheck($tmp,$stream)) {
234 // CRAM-MD5 is done at this point. If DIGEST-MD5, there's a bit more to go
235 if ($smtp_auth_mech == 'digest-md5') {
236 // $tmp contains rspauth, but I don't store that yet. (No need yet)
237 fputs($stream,"\r\n");
238 $tmp = fgets($stream,1024);
240 if ($this->errorCheck($tmp,$stream)) {
244 // CRAM-MD5 and DIGEST-MD5 code ends here
245 } elseif ($smtp_auth_mech == 'none') {
246 // No auth at all, just send helo and then send the mail
247 // We already said hi earlier, nothing more is needed.
248 } elseif ($smtp_auth_mech == 'login') {
250 fputs($stream, "AUTH LOGIN\r\n");
251 $tmp = fgets($stream, 1024);
253 if ($this->errorCheck($tmp, $stream)) {
256 fputs($stream, base64_encode ($user) . "\r\n");
257 $tmp = fgets($stream, 1024);
258 if ($this->errorCheck($tmp, $stream)) {
262 fputs($stream, base64_encode($pass) . "\r\n");
263 $tmp = fgets($stream, 1024);
264 if ($this->errorCheck($tmp, $stream)) {
267 } elseif ($smtp_auth_mech == "plain") {
269 $auth = base64_encode("$user\0$user\0$pass");
271 $query = "AUTH PLAIN\r\n";
272 fputs($stream, $query);
273 $read=fgets($stream, 1024);
275 if (substr($read,0,3) == '334') { // OK so far..
276 fputs($stream, "$auth\r\n");
277 $read = fgets($stream, 1024);
280 $results=explode(" ",$read,3);
281 $response=$results[1];
282 $message=$results[2];
284 /* Right here, they've reached an unsupported auth mechanism.
285 This is the ugliest hack I've ever done, but it'll do till I can fix
286 things up better tomorrow. So tired... */
287 if ($this->errorCheck("535 Unable to use this auth type",$stream)) {
292 /* Ok, who is sending the message? */
293 $fromaddress = ($from->mailbox
&& $from->host
) ?
294 $from->mailbox
.'@'.$from->host
: '';
295 fputs($stream, 'MAIL FROM:<'.$fromaddress.">\r\n");
296 $tmp = fgets($stream, 1024);
297 if ($this->errorCheck($tmp, $stream)) {
301 /* send who the recipients are */
302 for ($i = 0, $cnt = count($to); $i < $cnt; $i++
) {
303 if (!$to[$i]->host
) $to[$i]->host
= $domain;
304 if ($to[$i]->mailbox
) {
305 fputs($stream, 'RCPT TO:<'.$to[$i]->mailbox
.'@'.$to[$i]->host
.">\r\n");
306 $tmp = fgets($stream, 1024);
307 if ($this->errorCheck($tmp, $stream)) {
313 for ($i = 0, $cnt = count($cc); $i < $cnt; $i++
) {
314 if (!$cc[$i]->host
) $cc[$i]->host
= $domain;
315 if ($cc[$i]->mailbox
) {
316 fputs($stream, 'RCPT TO:<'.$cc[$i]->mailbox
.'@'.$cc[$i]->host
.">\r\n");
317 $tmp = fgets($stream, 1024);
318 if ($this->errorCheck($tmp, $stream)) {
324 for ($i = 0, $cnt = count($bcc); $i < $cnt; $i++
) {
325 if (!$bcc[$i]->host
) $bcc[$i]->host
= $domain;
326 if ($bcc[$i]->mailbox
) {
327 fputs($stream, 'RCPT TO:<'.$bcc[$i]->mailbox
.'@'.$bcc[$i]->host
.">\r\n");
328 $tmp = fgets($stream, 1024);
329 if ($this->errorCheck($tmp, $stream)) {
334 /* Lets start sending the actual message */
335 fputs($stream, "DATA\r\n");
336 $tmp = fgets($stream, 1024);
337 if ($this->errorCheck($tmp, $stream)) {
343 function finalizeStream($stream) {
344 fputs($stream, "\r\n.\r\n"); /* end the DATA part */
345 $tmp = fgets($stream, 1024);
346 $this->errorCheck($tmp, $stream);
347 if ($this->dlv_ret_nr
!= 250) {
350 fputs($stream, "QUIT\r\n"); /* log off */
355 /* check if an SMTP reply is an error and set an error message) */
356 function errorCheck($line, $smtpConnection) {
358 $err_num = substr($line, 0, 3);
359 $this->dlv_ret_nr
= $err_num;
360 $server_msg = substr($line, 4);
362 while(substr($line, 0, 4) == ($err_num.'-')) {
363 $line = fgets($smtpConnection, 1024);
364 $server_msg .= substr($line, 4);
367 if ( ((int) $err_num{0}) < 4) {
372 case '421': $message = _("Service not available, closing channel");
374 case '432': $message = _("A password transition is needed");
376 case '450': $message = _("Requested mail action not taken: mailbox unavailable");
378 case '451': $message = _("Requested action aborted: error in processing");
380 case '452': $message = _("Requested action not taken: insufficient system storage");
382 case '454': $message = _("Temporary authentication failure");
384 case '500': $message = _("Syntax error; command not recognized");
386 case '501': $message = _("Syntax error in parameters or arguments");
388 case '502': $message = _("Command not implemented");
390 case '503': $message = _("Bad sequence of commands");
392 case '504': $message = _("Command parameter not implemented");
394 case '530': $message = _("Authentication required");
396 case '534': $message = _("Authentication mechanism is too weak");
398 case '535': $message = _("Authentication failed");
400 case '538': $message = _("Encryption required for requested authentication mechanism");
402 case '550': $message = _("Requested action not taken: mailbox unavailable");
404 case '551': $message = _("User not local; please try forwarding");
406 case '552': $message = _("Requested mail action aborted: exceeding storage allocation");
408 case '553': $message = _("Requested action not taken: mailbox name not allowed");
410 case '554': $message = _("Transaction failed");
412 default: $message = _("Unknown response");
416 $this->dlv_msg
= $message;
417 $this->dlv_server_msg
= $server_msg;
422 function authPop($pop_server='', $pop_port='', $user, $pass) {
427 $pop_server = 'localhost';
429 $popConnection = fsockopen($pop_server, $pop_port, $err_no, $err_str);
430 if (!$popConnection) {
431 error_log("Error connecting to POP Server ($pop_server:$pop_port)"
432 . " $err_no : $err_str");
434 $tmp = fgets($popConnection, 1024); /* banner */
435 if (substr($tmp, 0, 3) != '+OK') {
438 fputs($popConnection, "USER $user\r\n");
439 $tmp = fgets($popConnection, 1024);
440 if (substr($tmp, 0, 3) != '+OK') {
443 fputs($popConnection, 'PASS ' . $pass . "\r\n");
444 $tmp = fgets($popConnection, 1024);
445 if (substr($tmp, 0, 3) != '+OK') {
448 fputs($popConnection, "QUIT\r\n"); /* log off */
449 fclose($popConnection);
454 * Parses ESMTP EHLO response (rfc1869)
456 * Reads SMTP response to EHLO command and fills class variables
457 * (ehlo array and domain string). Returns last line.
458 * @param stream $stream smtp connection stream.
459 * @return string last ehlo line
462 function parse_ehlo_response($stream) {
463 // don't cache ehlo information
468 * ehlo mailclient.example.org
469 * 250-mail.example.org
474 * 250-AUTH LOGIN PLAIN
477 while ($line=fgets($stream, 1024)){
478 // match[1] = first symbol after 250
479 // match[2] = domain or ehlo-keyword
480 // match[3] = greeting or ehlo-param
481 // match space after keyword in ehlo-keyword CR LF
482 if (preg_match("/^250(-|\s)(\S*)\s+(\S.*)\r\n/",$line,$match)||
483 preg_match("/^250(-|\s)(\S*)\s*\r\n/",$line,$match)) {
485 // first ehlo line (250[-\ ]domain SP greeting)
486 $this->domain
= $match[2];
488 } elseif (!isset($match[3])) {
489 // simple one word extension
490 $this->ehlo
[strtoupper($match[2])]='';
491 } elseif (!preg_match("/\s/",trim($match[3]))) {
492 // extension with one option
493 // yes, I know about ctype extension. no, i don't want to depend on it
494 $this->ehlo
[strtoupper($match[2])]=trim($match[3]);
496 // ehlo-param with spaces
497 $this->ehlo
[strtoupper($match[2])]=explode(' ',trim($match[3]));
499 if ($match[1]==' ') {
500 // stop while cycle, if we reach last 250 line
505 // this is not 250 response