4 * Deliver_SMTP.class.php
6 * SMTP delivery backend for the Deliver class.
8 * @copyright 1999-2022 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='', $stream_options=array()) {
66 global $use_smtp_tls,$smtp_auth_mech;
69 $this->authPop($user, $pass, $pop_host, '');
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 // NB: Using "ssl://" ensures the highest possible TLS version
94 // will be negotiated with the server (whereas "tls://" only
95 // uses TLS version 1.0)
97 if ($use_smtp_tls == 1) {
98 if ((check_php_version(4,3)) && (extension_loaded('openssl'))) {
99 if (function_exists('stream_socket_client')) {
100 $server_address = 'ssl://' . $host . ':' . $port;
101 $ssl_context = @stream_context_create
($stream_options);
102 $connect_timeout = ini_get('default_socket_timeout');
103 // null timeout is broken
104 if ($connect_timeout == 0)
105 $connect_timeout = 30;
106 $stream = @stream_socket_client
($server_address, $errorNumber, $errorString, $connect_timeout, STREAM_CLIENT_CONNECT
, $ssl_context);
108 $stream = @fsockopen
('ssl://' . $host, $port, $errorNumber, $errorString);
110 $this->tls_enabled
= true;
113 * don't connect to server when user asks for smtps and
114 * PHP does not support it.
117 $errorString = _("Secure SMTP (TLS) is enabled in SquirrelMail configuration, but used PHP version does not support it.");
120 $stream = @fsockopen
($host, $port, $errorNumber, $errorString);
124 // reset tls state var to default value, if connection fails
125 $this->tls_enabled
= false;
126 // set error messages
127 $this->dlv_msg
= $errorString;
128 $this->dlv_ret_nr
= $errorNumber;
129 $this->dlv_server_msg
= _("Can't open SMTP stream.");
132 // get server greeting
133 $tmp = fgets($stream, 1024);
134 if ($this->errorCheck($tmp, $stream)) {
139 * If $_SERVER['HTTP_HOST'] is set, use that in our HELO to the SMTP
140 * server. This should fix the DNS issues some people have had
142 if (sqgetGlobalVar('HTTP_HOST', $HTTP_HOST, SQ_SERVER
)) { // HTTP_HOST is set
143 // optionally trim off port number
144 if($p = strrpos($HTTP_HOST, ':')) {
145 $HTTP_HOST = substr($HTTP_HOST, 0, $p);
147 $helohost = $HTTP_HOST;
148 } else { // For some reason, HTTP_HOST is not set - revert to old behavior
152 // if the host is an IPv4 address, enclose it in brackets
154 if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $helohost))
155 $helohost = '[' . $helohost . ']';
157 $hook_result = do_hook('smtp_helo_override', $helohost);
158 if (!empty($hook_result)) $helohost = $hook_result;
160 /* Lets introduce ourselves */
161 fputs($stream, "EHLO $helohost\r\n");
162 // Read ehlo response
163 $tmp = $this->parse_ehlo_response($stream);
164 if ($this->errorCheck($tmp,$stream)) {
165 // fall back to HELO if EHLO is not supported (error 5xx)
166 if ($this->dlv_ret_nr
[0] == '5') {
167 fputs($stream, "HELO $helohost\r\n");
168 $tmp = fgets($stream,1024);
169 if ($this->errorCheck($tmp,$stream)) {
178 * Implementing SMTP STARTTLS (rfc2487) in php 5.1.0+
179 * http://www.php.net/stream-socket-enable-crypto
181 if ($use_smtp_tls === 2) {
182 if (function_exists('stream_socket_enable_crypto')) {
183 // don't try starting tls, when client thinks that it is already active
184 if ($this->tls_enabled
) {
185 $this->dlv_msg
= _("TLS session is already activated.");
187 } elseif (!array_key_exists('STARTTLS',$this->ehlo
)) {
188 // check for starttls in ehlo response
189 $this->dlv_msg
= _("SMTP STARTTLS is enabled in SquirrelMail configuration, but used SMTP server does not support it");
193 // issue starttls command
194 fputs($stream, "STARTTLS\r\n");
196 $tmp = fgets($stream,1024);
197 if ($this->errorCheck($tmp,$stream)) {
201 // start crypto on connection. suppress function errors.
202 if (@stream_socket_enable_crypto
($stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT
)) {
203 // starttls was successful (rfc2487 5.2 Result of the STARTTLS Command)
204 // get new EHLO response
205 fputs($stream, "EHLO $helohost\r\n");
206 // Read ehlo response
207 $tmp = $this->parse_ehlo_response($stream);
208 if ($this->errorCheck($tmp,$stream)) {
209 // don't revert to helo here. server must support ESMTP
212 // set information about started tls
213 $this->tls_enabled
= true;
216 * stream_socket_enable_crypto() call failed.
218 $this->dlv_msg
= _("Unable to start TLS.");
220 // Bug: can't get error message. See comments in sqimap_create_stream().
223 // php install does not support stream_socket_enable_crypto() function
224 $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.");
229 // FIXME: check ehlo response before using authentication
231 // Try authentication by a plugin
233 // NOTE: there is another hook in functions/auth.php called "smtp_auth"
234 // that allows a plugin to specify a different set of login credentials
235 // (so is slightly mis-named, but is too old to change), so be careful
236 // that you do not confuse your hook names.
238 $smtp_auth_args = array(
239 'auth_mech' => $smtp_auth_mech,
246 if (boolean_hook_function('smtp_authenticate', $smtp_auth_args, 1)) {
247 // authentication succeeded
248 } else if (( $smtp_auth_mech == 'cram-md5') or ( $smtp_auth_mech == 'digest-md5' )) {
249 // Doing some form of non-plain auth
250 if ($smtp_auth_mech == 'cram-md5') {
251 fputs($stream, "AUTH CRAM-MD5\r\n");
252 } elseif ($smtp_auth_mech == 'digest-md5') {
253 fputs($stream, "AUTH DIGEST-MD5\r\n");
256 $tmp = fgets($stream,1024);
258 if ($this->errorCheck($tmp,$stream)) {
262 // At this point, $tmp should hold "334 <challenge string>"
263 $chall = substr($tmp,4);
264 // Depending on mechanism, generate response string
265 if ($smtp_auth_mech == 'cram-md5') {
266 $response = cram_md5_response($user,$pass,$chall);
267 } elseif ($smtp_auth_mech == 'digest-md5') {
268 $response = digest_md5_response($user,$pass,$chall,'smtp',$host);
270 fputs($stream, $response);
272 // Let's see what the server had to say about that
273 $tmp = fgets($stream,1024);
274 if ($this->errorCheck($tmp,$stream)) {
278 // CRAM-MD5 is done at this point. If DIGEST-MD5, there's a bit more to go
279 if ($smtp_auth_mech == 'digest-md5') {
280 // $tmp contains rspauth, but I don't store that yet. (No need yet)
281 fputs($stream,"\r\n");
282 $tmp = fgets($stream,1024);
284 if ($this->errorCheck($tmp,$stream)) {
288 // CRAM-MD5 and DIGEST-MD5 code ends here
289 } elseif ($smtp_auth_mech == 'none') {
290 // No auth at all, just send helo and then send the mail
291 // We already said hi earlier, nothing more is needed.
292 } elseif ($smtp_auth_mech == 'login') {
294 fputs($stream, "AUTH LOGIN\r\n");
295 $tmp = fgets($stream, 1024);
297 if ($this->errorCheck($tmp, $stream)) {
300 fputs($stream, base64_encode ($user) . "\r\n");
301 $tmp = fgets($stream, 1024);
302 if ($this->errorCheck($tmp, $stream)) {
306 fputs($stream, base64_encode($pass) . "\r\n");
307 $tmp = fgets($stream, 1024);
308 if ($this->errorCheck($tmp, $stream)) {
311 } elseif ($smtp_auth_mech == "plain") {
313 $auth = base64_encode("$user\0$user\0$pass");
315 $query = "AUTH PLAIN\r\n";
316 fputs($stream, $query);
317 $read=fgets($stream, 1024);
319 if (substr($read,0,3) == '334') { // OK so far..
320 fputs($stream, "$auth\r\n");
321 $read = fgets($stream, 1024);
324 $results=explode(" ",$read,3);
325 $response=$results[1];
326 $message=$results[2];
328 /* Right here, they've reached an unsupported auth mechanism.
329 This is the ugliest hack I've ever done, but it'll do till I can fix
330 things up better tomorrow. So tired... */
331 if ($this->errorCheck("535 Unable to use this auth type",$stream)) {
336 /* Ok, who is sending the message? */
337 $fromaddress = (strlen($from->mailbox
) && $from->host
) ?
338 $from->mailbox
.'@'.$from->host
: '';
339 fputs($stream, 'MAIL FROM:<'.$fromaddress.">\r\n");
340 $tmp = fgets($stream, 1024);
341 if ($this->errorCheck($tmp, $stream)) {
345 /* send who the recipients are */
346 for ($i = 0, $cnt = count($to); $i < $cnt; $i++
) {
347 if (!$to[$i]->host
) $to[$i]->host
= $domain;
348 if (strlen($to[$i]->mailbox
)) {
349 // Ask for DSN if user has requested such and remote server supports it
350 if ($rfc822_header->dsn
&& array_key_exists('DSN',$this->ehlo
)) {
351 // TODO: Make the DSN parameters configurable by admin? user?
352 fputs($stream, 'RCPT TO:<'.$to[$i]->mailbox
.'@'.$to[$i]->host
."> NOTIFY=SUCCESS,DELAY,FAILURE\r\n");
353 // Retry without DSN fields for cranky MTAs
354 if ($this->errorCheck($tmp, $stream)) {
355 fputs($stream, 'RCPT TO:<'.$to[$i]->mailbox
.'@'.$to[$i]->host
.">\r\n");
359 fputs($stream, 'RCPT TO:<'.$to[$i]->mailbox
.'@'.$to[$i]->host
.">\r\n");
360 $tmp = fgets($stream, 1024);
361 if ($this->errorCheck($tmp, $stream)) {
367 for ($i = 0, $cnt = count($cc); $i < $cnt; $i++
) {
368 if (!$cc[$i]->host
) $cc[$i]->host
= $domain;
369 if (strlen($cc[$i]->mailbox
)) {
370 // Ask for DSN if user has requested such and remote server supports it
371 if ($rfc822_header->dsn
&& array_key_exists('DSN',$this->ehlo
)) {
372 // TODO: Make the DSN parameters configurable by admin? user?
373 fputs($stream, 'RCPT TO:<'.$cc[$i]->mailbox
.'@'.$cc[$i]->host
."> NOTIFY=SUCCESS,DELAY,FAILURE\r\n");
374 // Retry without DSN fields for cranky MTAs
375 if ($this->errorCheck($tmp, $stream)) {
376 fputs($stream, 'RCPT TO:<'.$cc[$i]->mailbox
.'@'.$cc[$i]->host
.">\r\n");
380 fputs($stream, 'RCPT TO:<'.$cc[$i]->mailbox
.'@'.$cc[$i]->host
.">\r\n");
381 $tmp = fgets($stream, 1024);
382 if ($this->errorCheck($tmp, $stream)) {
388 for ($i = 0, $cnt = count($bcc); $i < $cnt; $i++
) {
389 if (!$bcc[$i]->host
) $bcc[$i]->host
= $domain;
390 if (strlen($bcc[$i]->mailbox
)) {
391 // Ask for DSN if user has requested such and remote server supports it
392 if ($rfc822_header->dsn
&& array_key_exists('DSN',$this->ehlo
)) {
393 // TODO: Make the DSN parameters configurable by admin? user?
394 fputs($stream, 'RCPT TO:<'.$bcc[$i]->mailbox
.'@'.$bcc[$i]->host
."> NOTIFY=SUCCESS,DELAY,FAILURE\r\n");
395 // Retry without DSN fields for cranky MTAs
396 if ($this->errorCheck($tmp, $stream)) {
397 fputs($stream, 'RCPT TO:<'.$bcc[$i]->mailbox
.'@'.$bcc[$i]->host
.">\r\n");
401 fputs($stream, 'RCPT TO:<'.$bcc[$i]->mailbox
.'@'.$bcc[$i]->host
.">\r\n");
402 $tmp = fgets($stream, 1024);
403 if ($this->errorCheck($tmp, $stream)) {
408 /* Lets start sending the actual message */
409 fputs($stream, "DATA\r\n");
410 $tmp = fgets($stream, 1024);
411 if ($this->errorCheck($tmp, $stream)) {
417 function finalizeStream($stream) {
418 fputs($stream, "\r\n.\r\n"); /* end the DATA part */
419 $tmp = fgets($stream, 1024);
420 $this->errorCheck($tmp, $stream);
421 if ($this->dlv_ret_nr
!= 250) {
424 fputs($stream, "QUIT\r\n"); /* log off */
429 /* check if an SMTP reply is an error and set an error message) */
430 function errorCheck($line, $smtpConnection) {
432 $err_num = substr($line, 0, 3);
433 $this->dlv_ret_nr
= $err_num;
434 $server_msg = substr($line, 4);
436 while(substr($line, 0, 4) == ($err_num.'-')) {
437 $line = fgets($smtpConnection, 1024);
438 $server_msg .= substr($line, 4);
441 if ( ((int) $err_num[0]) < 4) {
446 case '421': $message = _("Service not available, closing channel");
448 case '432': $message = _("A password transition is needed");
450 case '450': $message = _("Requested mail action not taken: mailbox unavailable");
452 case '451': $message = _("Requested action aborted: error in processing");
454 case '452': $message = _("Requested action not taken: insufficient system storage");
456 case '454': $message = _("Temporary authentication failure");
458 case '500': $message = _("Syntax error; command not recognized");
460 case '501': $message = _("Syntax error in parameters or arguments");
462 case '502': $message = _("Command not implemented");
464 case '503': $message = _("Bad sequence of commands");
466 case '504': $message = _("Command parameter not implemented");
468 case '530': $message = _("Authentication required");
470 case '534': $message = _("Authentication mechanism is too weak");
472 case '535': $message = _("Authentication failed");
474 case '538': $message = _("Encryption required for requested authentication mechanism");
476 case '550': $message = _("Requested action not taken: mailbox unavailable");
478 case '551': $message = _("User not local; please try forwarding");
480 case '552': $message = _("Requested mail action aborted: exceeding storage allocation");
482 case '553': $message = _("Requested action not taken: mailbox name not allowed");
484 case '554': $message = _("Transaction failed");
486 default: $message = _("Unknown response");
490 $this->dlv_msg
= $message;
491 $this->dlv_server_msg
= $server_msg;
496 function authPop($user, $pass, $pop_server='', $pop_port='') {
501 $pop_server = 'localhost';
503 $popConnection = @fsockopen
($pop_server, $pop_port, $err_no, $err_str);
504 if (!$popConnection) {
505 error_log("Error connecting to POP Server ($pop_server:$pop_port)"
506 . " $err_no : $err_str");
509 $tmp = fgets($popConnection, 1024); /* banner */
510 if (substr($tmp, 0, 3) != '+OK') {
513 fputs($popConnection, "USER $user\r\n");
514 $tmp = fgets($popConnection, 1024);
515 if (substr($tmp, 0, 3) != '+OK') {
518 fputs($popConnection, 'PASS ' . $pass . "\r\n");
519 $tmp = fgets($popConnection, 1024);
520 if (substr($tmp, 0, 3) != '+OK') {
523 fputs($popConnection, "QUIT\r\n"); /* log off */
524 fclose($popConnection);
530 * Parses ESMTP EHLO response (rfc1869)
532 * Reads SMTP response to EHLO command and fills class variables
533 * (ehlo array and domain string). Returns last line.
534 * @param stream $stream smtp connection stream.
535 * @return string last ehlo line
538 function parse_ehlo_response($stream) {
539 // don't cache ehlo information
544 * ehlo mailclient.example.org
545 * 250-mail.example.org
550 * 250-AUTH LOGIN PLAIN
553 while ($line=fgets($stream, 1024)){
554 // match[1] = first symbol after 250
555 // match[2] = domain or ehlo-keyword
556 // match[3] = greeting or ehlo-param
557 // match space after keyword in ehlo-keyword CR LF
558 if (preg_match("/^250(-|\s)(\S*)\s+(\S.*)\r\n/",$line,$match)||
559 preg_match("/^250(-|\s)(\S*)\s*\r\n/",$line,$match)) {
561 // first ehlo line (250[-\ ]domain SP greeting)
562 $this->domain
= $match[2];
564 } elseif (!isset($match[3])) {
565 // simple one word extension
566 $this->ehlo
[strtoupper($match[2])]='';
567 } elseif (!preg_match("/\s/",trim($match[3]))) {
568 // extension with one option
569 // yes, I know about ctype extension. no, i don't want to depend on it
570 $this->ehlo
[strtoupper($match[2])]=trim($match[3]);
572 // ehlo-param with spaces
573 $this->ehlo
[strtoupper($match[2])]=explode(' ',trim($match[3]));
575 if ($match[1]==' ') {
576 // stop while cycle, if we reach last 250 line
581 // this is not 250 response