4 * Deliver_SMTP.class.php
6 * SMTP delivery backend for the Deliver class.
8 * @copyright © 1999-2009 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, $pop_host='') {
66 global $use_smtp_tls,$smtp_auth_mech;
69 $this->authPop($pop_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') {
85 // reinitialize the from object because otherwise the from header somehow
86 // is affected. This $from var is used for smtp command MAIL FROM which
87 // is not the same as what we put in the rfc822 header.
88 $from = new AddressStructure();
93 if ($use_smtp_tls == 1) {
94 if ((check_php_version(4,3)) && (extension_loaded('openssl'))) {
95 $stream = @fsockopen
('tls://' . $host, $port, $errorNumber, $errorString);
96 $this->tls_enabled
= true;
99 * don't connect to server when user asks for smtps and
100 * PHP does not support it.
103 $errorString = _("Secure SMTP (TLS) is enabled in SquirrelMail configuration, but used PHP version does not support it.");
106 $stream = @fsockopen
($host, $port, $errorNumber, $errorString);
110 // reset tls state var to default value, if connection fails
111 $this->tls_enabled
= false;
112 // set error messages
113 $this->dlv_msg
= $errorString;
114 $this->dlv_ret_nr
= $errorNumber;
115 $this->dlv_server_msg
= _("Can't open SMTP stream.");
118 // get server greeting
119 $tmp = fgets($stream, 1024);
120 if ($this->errorCheck($tmp, $stream)) {
125 * If $_SERVER['HTTP_HOST'] is set, use that in our HELO to the SMTP
126 * server. This should fix the DNS issues some people have had
128 if (sqgetGlobalVar('HTTP_HOST', $HTTP_HOST, SQ_SERVER
)) { // HTTP_HOST is set
129 // optionally trim off port number
130 if($p = strrpos($HTTP_HOST, ':')) {
131 $HTTP_HOST = substr($HTTP_HOST, 0, $p);
133 $helohost = $HTTP_HOST;
134 } else { // For some reason, HTTP_HOST is not set - revert to old behavior
138 // if the host is an IPv4 address, enclose it in brackets
140 if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $helohost))
141 $helohost = '[' . $helohost . ']';
143 /* Lets introduce ourselves */
144 fputs($stream, "EHLO $helohost\r\n");
145 // Read ehlo response
146 $tmp = $this->parse_ehlo_response($stream);
147 if ($this->errorCheck($tmp,$stream)) {
148 // fall back to HELO if EHLO is not supported (error 5xx)
149 if ($this->dlv_ret_nr
{0} == '5') {
150 fputs($stream, "HELO $helohost\r\n");
151 $tmp = fgets($stream,1024);
152 if ($this->errorCheck($tmp,$stream)) {
161 * Implementing SMTP STARTTLS (rfc2487) in php 5.1.0+
162 * http://www.php.net/stream-socket-enable-crypto
164 if ($use_smtp_tls === 2) {
165 if (function_exists('stream_socket_enable_crypto')) {
166 // don't try starting tls, when client thinks that it is already active
167 if ($this->tls_enabled
) {
168 $this->dlv_msg
= _("TLS session is already activated.");
170 } elseif (!array_key_exists('STARTTLS',$this->ehlo
)) {
171 // check for starttls in ehlo response
172 $this->dlv_msg
= _("SMTP STARTTLS is enabled in SquirrelMail configuration, but used SMTP server does not support it");
176 // issue starttls command
177 fputs($stream, "STARTTLS\r\n");
179 $tmp = fgets($stream,1024);
180 if ($this->errorCheck($tmp,$stream)) {
184 // start crypto on connection. suppress function errors.
185 if (@stream_socket_enable_crypto
($stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT
)) {
186 // starttls was successful (rfc2487 5.2 Result of the STARTTLS Command)
187 // get new EHLO response
188 fputs($stream, "EHLO $helohost\r\n");
189 // Read ehlo response
190 $tmp = $this->parse_ehlo_response($stream);
191 if ($this->errorCheck($tmp,$stream)) {
192 // don't revert to helo here. server must support ESMTP
195 // set information about started tls
196 $this->tls_enabled
= true;
199 * stream_socket_enable_crypto() call failed.
201 $this->dlv_msg
= _("Unable to start TLS.");
203 // Bug: can't get error message. See comments in sqimap_create_stream().
206 // php install does not support stream_socket_enable_crypto() function
207 $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.");
212 // FIXME: check ehlo response before using authentication
213 if (( $smtp_auth_mech == 'cram-md5') or ( $smtp_auth_mech == 'digest-md5' )) {
214 // Doing some form of non-plain auth
215 if ($smtp_auth_mech == 'cram-md5') {
216 fputs($stream, "AUTH CRAM-MD5\r\n");
217 } elseif ($smtp_auth_mech == 'digest-md5') {
218 fputs($stream, "AUTH DIGEST-MD5\r\n");
221 $tmp = fgets($stream,1024);
223 if ($this->errorCheck($tmp,$stream)) {
227 // At this point, $tmp should hold "334 <challenge string>"
228 $chall = substr($tmp,4);
229 // Depending on mechanism, generate response string
230 if ($smtp_auth_mech == 'cram-md5') {
231 $response = cram_md5_response($user,$pass,$chall);
232 } elseif ($smtp_auth_mech == 'digest-md5') {
233 $response = digest_md5_response($user,$pass,$chall,'smtp',$host);
235 fputs($stream, $response);
237 // Let's see what the server had to say about that
238 $tmp = fgets($stream,1024);
239 if ($this->errorCheck($tmp,$stream)) {
243 // CRAM-MD5 is done at this point. If DIGEST-MD5, there's a bit more to go
244 if ($smtp_auth_mech == 'digest-md5') {
245 // $tmp contains rspauth, but I don't store that yet. (No need yet)
246 fputs($stream,"\r\n");
247 $tmp = fgets($stream,1024);
249 if ($this->errorCheck($tmp,$stream)) {
253 // CRAM-MD5 and DIGEST-MD5 code ends here
254 } elseif ($smtp_auth_mech == 'none') {
255 // No auth at all, just send helo and then send the mail
256 // We already said hi earlier, nothing more is needed.
257 } elseif ($smtp_auth_mech == 'login') {
259 fputs($stream, "AUTH LOGIN\r\n");
260 $tmp = fgets($stream, 1024);
262 if ($this->errorCheck($tmp, $stream)) {
265 fputs($stream, base64_encode ($user) . "\r\n");
266 $tmp = fgets($stream, 1024);
267 if ($this->errorCheck($tmp, $stream)) {
271 fputs($stream, base64_encode($pass) . "\r\n");
272 $tmp = fgets($stream, 1024);
273 if ($this->errorCheck($tmp, $stream)) {
276 } elseif ($smtp_auth_mech == "plain") {
278 $auth = base64_encode("$user\0$user\0$pass");
280 $query = "AUTH PLAIN\r\n";
281 fputs($stream, $query);
282 $read=fgets($stream, 1024);
284 if (substr($read,0,3) == '334') { // OK so far..
285 fputs($stream, "$auth\r\n");
286 $read = fgets($stream, 1024);
289 $results=explode(" ",$read,3);
290 $response=$results[1];
291 $message=$results[2];
293 /* Right here, they've reached an unsupported auth mechanism.
294 This is the ugliest hack I've ever done, but it'll do till I can fix
295 things up better tomorrow. So tired... */
296 if ($this->errorCheck("535 Unable to use this auth type",$stream)) {
301 /* Ok, who is sending the message? */
302 $fromaddress = (strlen($from->mailbox
) && $from->host
) ?
303 $from->mailbox
.'@'.$from->host
: '';
304 fputs($stream, 'MAIL FROM:<'.$fromaddress.">\r\n");
305 $tmp = fgets($stream, 1024);
306 if ($this->errorCheck($tmp, $stream)) {
310 /* send who the recipients are */
311 for ($i = 0, $cnt = count($to); $i < $cnt; $i++
) {
312 if (!$to[$i]->host
) $to[$i]->host
= $domain;
313 if (strlen($to[$i]->mailbox
)) {
314 fputs($stream, 'RCPT TO:<'.$to[$i]->mailbox
.'@'.$to[$i]->host
.">\r\n");
315 $tmp = fgets($stream, 1024);
316 if ($this->errorCheck($tmp, $stream)) {
322 for ($i = 0, $cnt = count($cc); $i < $cnt; $i++
) {
323 if (!$cc[$i]->host
) $cc[$i]->host
= $domain;
324 if (strlen($cc[$i]->mailbox
)) {
325 fputs($stream, 'RCPT TO:<'.$cc[$i]->mailbox
.'@'.$cc[$i]->host
.">\r\n");
326 $tmp = fgets($stream, 1024);
327 if ($this->errorCheck($tmp, $stream)) {
333 for ($i = 0, $cnt = count($bcc); $i < $cnt; $i++
) {
334 if (!$bcc[$i]->host
) $bcc[$i]->host
= $domain;
335 if (strlen($bcc[$i]->mailbox
)) {
336 fputs($stream, 'RCPT TO:<'.$bcc[$i]->mailbox
.'@'.$bcc[$i]->host
.">\r\n");
337 $tmp = fgets($stream, 1024);
338 if ($this->errorCheck($tmp, $stream)) {
343 /* Lets start sending the actual message */
344 fputs($stream, "DATA\r\n");
345 $tmp = fgets($stream, 1024);
346 if ($this->errorCheck($tmp, $stream)) {
352 function finalizeStream($stream) {
353 fputs($stream, "\r\n.\r\n"); /* end the DATA part */
354 $tmp = fgets($stream, 1024);
355 $this->errorCheck($tmp, $stream);
356 if ($this->dlv_ret_nr
!= 250) {
359 fputs($stream, "QUIT\r\n"); /* log off */
364 /* check if an SMTP reply is an error and set an error message) */
365 function errorCheck($line, $smtpConnection) {
367 $err_num = substr($line, 0, 3);
368 $this->dlv_ret_nr
= $err_num;
369 $server_msg = substr($line, 4);
371 while(substr($line, 0, 4) == ($err_num.'-')) {
372 $line = fgets($smtpConnection, 1024);
373 $server_msg .= substr($line, 4);
376 if ( ((int) $err_num{0}) < 4) {
381 case '421': $message = _("Service not available, closing channel");
383 case '432': $message = _("A password transition is needed");
385 case '450': $message = _("Requested mail action not taken: mailbox unavailable");
387 case '451': $message = _("Requested action aborted: error in processing");
389 case '452': $message = _("Requested action not taken: insufficient system storage");
391 case '454': $message = _("Temporary authentication failure");
393 case '500': $message = _("Syntax error; command not recognized");
395 case '501': $message = _("Syntax error in parameters or arguments");
397 case '502': $message = _("Command not implemented");
399 case '503': $message = _("Bad sequence of commands");
401 case '504': $message = _("Command parameter not implemented");
403 case '530': $message = _("Authentication required");
405 case '534': $message = _("Authentication mechanism is too weak");
407 case '535': $message = _("Authentication failed");
409 case '538': $message = _("Encryption required for requested authentication mechanism");
411 case '550': $message = _("Requested action not taken: mailbox unavailable");
413 case '551': $message = _("User not local; please try forwarding");
415 case '552': $message = _("Requested mail action aborted: exceeding storage allocation");
417 case '553': $message = _("Requested action not taken: mailbox name not allowed");
419 case '554': $message = _("Transaction failed");
421 default: $message = _("Unknown response");
425 $this->dlv_msg
= $message;
426 $this->dlv_server_msg
= $server_msg;
431 function authPop($pop_server='', $pop_port='', $user, $pass) {
436 $pop_server = 'localhost';
438 $popConnection = @fsockopen
($pop_server, $pop_port, $err_no, $err_str);
439 if (!$popConnection) {
440 error_log("Error connecting to POP Server ($pop_server:$pop_port)"
441 . " $err_no : $err_str");
444 $tmp = fgets($popConnection, 1024); /* banner */
445 if (substr($tmp, 0, 3) != '+OK') {
448 fputs($popConnection, "USER $user\r\n");
449 $tmp = fgets($popConnection, 1024);
450 if (substr($tmp, 0, 3) != '+OK') {
453 fputs($popConnection, 'PASS ' . $pass . "\r\n");
454 $tmp = fgets($popConnection, 1024);
455 if (substr($tmp, 0, 3) != '+OK') {
458 fputs($popConnection, "QUIT\r\n"); /* log off */
459 fclose($popConnection);
465 * Parses ESMTP EHLO response (rfc1869)
467 * Reads SMTP response to EHLO command and fills class variables
468 * (ehlo array and domain string). Returns last line.
469 * @param stream $stream smtp connection stream.
470 * @return string last ehlo line
473 function parse_ehlo_response($stream) {
474 // don't cache ehlo information
479 * ehlo mailclient.example.org
480 * 250-mail.example.org
485 * 250-AUTH LOGIN PLAIN
488 while ($line=fgets($stream, 1024)){
489 // match[1] = first symbol after 250
490 // match[2] = domain or ehlo-keyword
491 // match[3] = greeting or ehlo-param
492 // match space after keyword in ehlo-keyword CR LF
493 if (preg_match("/^250(-|\s)(\S*)\s+(\S.*)\r\n/",$line,$match)||
494 preg_match("/^250(-|\s)(\S*)\s*\r\n/",$line,$match)) {
496 // first ehlo line (250[-\ ]domain SP greeting)
497 $this->domain
= $match[2];
499 } elseif (!isset($match[3])) {
500 // simple one word extension
501 $this->ehlo
[strtoupper($match[2])]='';
502 } elseif (!preg_match("/\s/",trim($match[3]))) {
503 // extension with one option
504 // yes, I know about ctype extension. no, i don't want to depend on it
505 $this->ehlo
[strtoupper($match[2])]=trim($match[3]);
507 // ehlo-param with spaces
508 $this->ehlo
[strtoupper($match[2])]=explode(' ',trim($match[3]));
510 if ($match[1]==' ') {
511 // stop while cycle, if we reach last 250 line
516 // this is not 250 response