641fbe79b3ac11e294497e48d355579462190b44
[squirrelmail.git] / class / deliver / Deliver_SMTP.class.php
1 <?php
2
3 /**
4 * Deliver_SMTP.class.php
5 *
6 * SMTP delivery backend for the Deliver class.
7 *
8 * @copyright 1999-2014 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
10 * @version $Id$
11 * @package squirrelmail
12 */
13
14 /** @ignore */
15 if (!defined('SM_PATH')) define('SM_PATH','../../');
16
17 /** This of course depends upon Deliver */
18 include_once(SM_PATH . 'class/deliver/Deliver.class.php');
19
20 /**
21 * Deliver messages using SMTP
22 * @package squirrelmail
23 */
24 class Deliver_SMTP extends Deliver {
25 /**
26 * Array keys are uppercased ehlo keywords
27 * array key values are ehlo params. If ehlo-param contains space, it is splitted into array.
28 * @var array ehlo
29 * @since 1.5.1
30 */
31 var $ehlo = array();
32 /**
33 * @var string domain
34 * @since 1.5.1
35 */
36 var $domain = '';
37 /**
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.
41 * @var boolean
42 * @since 1.5.1
43 */
44 var $tls_enabled = false;
45 /**
46 * Private var
47 * var stream $stream
48 * @todo don't pass stream resource in class method arguments.
49 */
50 //var $stream = false;
51 /** @var string delivery error message */
52 var $dlv_msg = '';
53 /** @var integer delivery error number from server */
54 var $dlv_ret_nr = '';
55 /** @var string delivery error message from server */
56 var $dlv_server_msg = '';
57
58 function preWriteToStream(&$s) {
59 if ($s) {
60 if ($s{0} == '.') $s = '.' . $s;
61 $s = str_replace("\n.","\n..",$s);
62 }
63 }
64
65 function initStream($message, $domain, $length=0, $host='', $port='', $user='', $pass='', $authpop=false, $pop_host='', $ssl_options=array()) {
66 global $use_smtp_tls,$smtp_auth_mech;
67
68 if ($authpop) {
69 $this->authPop($pop_host, '', $user, $pass);
70 }
71
72 $rfc822_header = $message->rfc822_header;
73
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;
79
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();
89 $from->host = '';
90 $from->mailbox = '';
91 }
92
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)
96 //
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 if (!empty($ssl_options))
102 $ssl_options = array('ssl' => $ssl_options);
103 $ssl_context = @stream_context_create($ssl_options);
104 $connect_timeout = ini_get('default_socket_timeout');
105 // null timeout is broken
106 if ($connect_timeout == 0)
107 $connect_timeout = 30;
108 $stream = @stream_socket_client($server_address, $errorNumber, $errorString, $connect_timeout, STREAM_CLIENT_CONNECT, $ssl_context);
109 } else {
110 $stream = @fsockopen('ssl://' . $host, $port, $errorNumber, $errorString);
111 }
112 $this->tls_enabled = true;
113 } else {
114 /**
115 * don't connect to server when user asks for smtps and
116 * PHP does not support it.
117 */
118 $errorNumber = '';
119 $errorString = _("Secure SMTP (TLS) is enabled in SquirrelMail configuration, but used PHP version does not support it.");
120 }
121 } else {
122 $stream = @fsockopen($host, $port, $errorNumber, $errorString);
123 }
124
125 if (!$stream) {
126 // reset tls state var to default value, if connection fails
127 $this->tls_enabled = false;
128 // set error messages
129 $this->dlv_msg = $errorString;
130 $this->dlv_ret_nr = $errorNumber;
131 $this->dlv_server_msg = _("Can't open SMTP stream.");
132 return(0);
133 }
134 // get server greeting
135 $tmp = fgets($stream, 1024);
136 if ($this->errorCheck($tmp, $stream)) {
137 return(0);
138 }
139
140 /*
141 * If $_SERVER['HTTP_HOST'] is set, use that in our HELO to the SMTP
142 * server. This should fix the DNS issues some people have had
143 */
144 if (sqgetGlobalVar('HTTP_HOST', $HTTP_HOST, SQ_SERVER)) { // HTTP_HOST is set
145 // optionally trim off port number
146 if($p = strrpos($HTTP_HOST, ':')) {
147 $HTTP_HOST = substr($HTTP_HOST, 0, $p);
148 }
149 $helohost = $HTTP_HOST;
150 } else { // For some reason, HTTP_HOST is not set - revert to old behavior
151 $helohost = $domain;
152 }
153
154 // if the host is an IPv4 address, enclose it in brackets
155 //
156 if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $helohost))
157 $helohost = '[' . $helohost . ']';
158
159 /* Lets introduce ourselves */
160 fputs($stream, "EHLO $helohost\r\n");
161 // Read ehlo response
162 $tmp = $this->parse_ehlo_response($stream);
163 if ($this->errorCheck($tmp,$stream)) {
164 // fall back to HELO if EHLO is not supported (error 5xx)
165 if ($this->dlv_ret_nr{0} == '5') {
166 fputs($stream, "HELO $helohost\r\n");
167 $tmp = fgets($stream,1024);
168 if ($this->errorCheck($tmp,$stream)) {
169 return(0);
170 }
171 } else {
172 return(0);
173 }
174 }
175
176 /**
177 * Implementing SMTP STARTTLS (rfc2487) in php 5.1.0+
178 * http://www.php.net/stream-socket-enable-crypto
179 */
180 if ($use_smtp_tls === 2) {
181 if (function_exists('stream_socket_enable_crypto')) {
182 // don't try starting tls, when client thinks that it is already active
183 if ($this->tls_enabled) {
184 $this->dlv_msg = _("TLS session is already activated.");
185 return 0;
186 } elseif (!array_key_exists('STARTTLS',$this->ehlo)) {
187 // check for starttls in ehlo response
188 $this->dlv_msg = _("SMTP STARTTLS is enabled in SquirrelMail configuration, but used SMTP server does not support it");
189 return 0;
190 }
191
192 // issue starttls command
193 fputs($stream, "STARTTLS\r\n");
194 // get response
195 $tmp = fgets($stream,1024);
196 if ($this->errorCheck($tmp,$stream)) {
197 return 0;
198 }
199
200 // start crypto on connection. suppress function errors.
201 if (@stream_socket_enable_crypto($stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
202 // starttls was successful (rfc2487 5.2 Result of the STARTTLS Command)
203 // get new EHLO response
204 fputs($stream, "EHLO $helohost\r\n");
205 // Read ehlo response
206 $tmp = $this->parse_ehlo_response($stream);
207 if ($this->errorCheck($tmp,$stream)) {
208 // don't revert to helo here. server must support ESMTP
209 return 0;
210 }
211 // set information about started tls
212 $this->tls_enabled = true;
213 } else {
214 /**
215 * stream_socket_enable_crypto() call failed.
216 */
217 $this->dlv_msg = _("Unable to start TLS.");
218 return 0;
219 // Bug: can't get error message. See comments in sqimap_create_stream().
220 }
221 } else {
222 // php install does not support stream_socket_enable_crypto() function
223 $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.");
224 return 0;
225 }
226 }
227
228 // FIXME: check ehlo response before using authentication
229
230 // Try authentication by a plugin
231 //
232 // NOTE: there is another hook in functions/auth.php called "smtp_auth"
233 // that allows a plugin to specify a different set of login credentials
234 // (so is slightly mis-named, but is too old to change), so be careful
235 // that you do not confuse your hook names.
236 //
237 $smtp_auth_args = array(
238 'auth_mech' => $smtp_auth_mech,
239 'user' => $user,
240 'pass' => $pass,
241 'host' => $host,
242 'port' => $port,
243 'stream' => $stream,
244 );
245 if (boolean_hook_function('smtp_authenticate', $smtp_auth_args, 1)) {
246 // authentication succeeded
247 } else if (( $smtp_auth_mech == 'cram-md5') or ( $smtp_auth_mech == 'digest-md5' )) {
248 // Doing some form of non-plain auth
249 if ($smtp_auth_mech == 'cram-md5') {
250 fputs($stream, "AUTH CRAM-MD5\r\n");
251 } elseif ($smtp_auth_mech == 'digest-md5') {
252 fputs($stream, "AUTH DIGEST-MD5\r\n");
253 }
254
255 $tmp = fgets($stream,1024);
256
257 if ($this->errorCheck($tmp,$stream)) {
258 return(0);
259 }
260
261 // At this point, $tmp should hold "334 <challenge string>"
262 $chall = substr($tmp,4);
263 // Depending on mechanism, generate response string
264 if ($smtp_auth_mech == 'cram-md5') {
265 $response = cram_md5_response($user,$pass,$chall);
266 } elseif ($smtp_auth_mech == 'digest-md5') {
267 $response = digest_md5_response($user,$pass,$chall,'smtp',$host);
268 }
269 fputs($stream, $response);
270
271 // Let's see what the server had to say about that
272 $tmp = fgets($stream,1024);
273 if ($this->errorCheck($tmp,$stream)) {
274 return(0);
275 }
276
277 // CRAM-MD5 is done at this point. If DIGEST-MD5, there's a bit more to go
278 if ($smtp_auth_mech == 'digest-md5') {
279 // $tmp contains rspauth, but I don't store that yet. (No need yet)
280 fputs($stream,"\r\n");
281 $tmp = fgets($stream,1024);
282
283 if ($this->errorCheck($tmp,$stream)) {
284 return(0);
285 }
286 }
287 // CRAM-MD5 and DIGEST-MD5 code ends here
288 } elseif ($smtp_auth_mech == 'none') {
289 // No auth at all, just send helo and then send the mail
290 // We already said hi earlier, nothing more is needed.
291 } elseif ($smtp_auth_mech == 'login') {
292 // The LOGIN method
293 fputs($stream, "AUTH LOGIN\r\n");
294 $tmp = fgets($stream, 1024);
295
296 if ($this->errorCheck($tmp, $stream)) {
297 return(0);
298 }
299 fputs($stream, base64_encode ($user) . "\r\n");
300 $tmp = fgets($stream, 1024);
301 if ($this->errorCheck($tmp, $stream)) {
302 return(0);
303 }
304
305 fputs($stream, base64_encode($pass) . "\r\n");
306 $tmp = fgets($stream, 1024);
307 if ($this->errorCheck($tmp, $stream)) {
308 return(0);
309 }
310 } elseif ($smtp_auth_mech == "plain") {
311 /* SASL Plain */
312 $auth = base64_encode("$user\0$user\0$pass");
313
314 $query = "AUTH PLAIN\r\n";
315 fputs($stream, $query);
316 $read=fgets($stream, 1024);
317
318 if (substr($read,0,3) == '334') { // OK so far..
319 fputs($stream, "$auth\r\n");
320 $read = fgets($stream, 1024);
321 }
322
323 $results=explode(" ",$read,3);
324 $response=$results[1];
325 $message=$results[2];
326 } else {
327 /* Right here, they've reached an unsupported auth mechanism.
328 This is the ugliest hack I've ever done, but it'll do till I can fix
329 things up better tomorrow. So tired... */
330 if ($this->errorCheck("535 Unable to use this auth type",$stream)) {
331 return(0);
332 }
333 }
334
335 /* Ok, who is sending the message? */
336 $fromaddress = (strlen($from->mailbox) && $from->host) ?
337 $from->mailbox.'@'.$from->host : '';
338 fputs($stream, 'MAIL FROM:<'.$fromaddress.">\r\n");
339 $tmp = fgets($stream, 1024);
340 if ($this->errorCheck($tmp, $stream)) {
341 return(0);
342 }
343
344 /* send who the recipients are */
345 for ($i = 0, $cnt = count($to); $i < $cnt; $i++) {
346 if (!$to[$i]->host) $to[$i]->host = $domain;
347 if (strlen($to[$i]->mailbox)) {
348 fputs($stream, 'RCPT TO:<'.$to[$i]->mailbox.'@'.$to[$i]->host.">\r\n");
349 $tmp = fgets($stream, 1024);
350 if ($this->errorCheck($tmp, $stream)) {
351 return(0);
352 }
353 }
354 }
355
356 for ($i = 0, $cnt = count($cc); $i < $cnt; $i++) {
357 if (!$cc[$i]->host) $cc[$i]->host = $domain;
358 if (strlen($cc[$i]->mailbox)) {
359 fputs($stream, 'RCPT TO:<'.$cc[$i]->mailbox.'@'.$cc[$i]->host.">\r\n");
360 $tmp = fgets($stream, 1024);
361 if ($this->errorCheck($tmp, $stream)) {
362 return(0);
363 }
364 }
365 }
366
367 for ($i = 0, $cnt = count($bcc); $i < $cnt; $i++) {
368 if (!$bcc[$i]->host) $bcc[$i]->host = $domain;
369 if (strlen($bcc[$i]->mailbox)) {
370 fputs($stream, 'RCPT TO:<'.$bcc[$i]->mailbox.'@'.$bcc[$i]->host.">\r\n");
371 $tmp = fgets($stream, 1024);
372 if ($this->errorCheck($tmp, $stream)) {
373 return(0);
374 }
375 }
376 }
377 /* Lets start sending the actual message */
378 fputs($stream, "DATA\r\n");
379 $tmp = fgets($stream, 1024);
380 if ($this->errorCheck($tmp, $stream)) {
381 return(0);
382 }
383 return $stream;
384 }
385
386 function finalizeStream($stream) {
387 fputs($stream, "\r\n.\r\n"); /* end the DATA part */
388 $tmp = fgets($stream, 1024);
389 $this->errorCheck($tmp, $stream);
390 if ($this->dlv_ret_nr != 250) {
391 return(0);
392 }
393 fputs($stream, "QUIT\r\n"); /* log off */
394 fclose($stream);
395 return true;
396 }
397
398 /* check if an SMTP reply is an error and set an error message) */
399 function errorCheck($line, $smtpConnection) {
400
401 $err_num = substr($line, 0, 3);
402 $this->dlv_ret_nr = $err_num;
403 $server_msg = substr($line, 4);
404
405 while(substr($line, 0, 4) == ($err_num.'-')) {
406 $line = fgets($smtpConnection, 1024);
407 $server_msg .= substr($line, 4);
408 }
409
410 if ( ((int) $err_num{0}) < 4) {
411 return false;
412 }
413
414 switch ($err_num) {
415 case '421': $message = _("Service not available, closing channel");
416 break;
417 case '432': $message = _("A password transition is needed");
418 break;
419 case '450': $message = _("Requested mail action not taken: mailbox unavailable");
420 break;
421 case '451': $message = _("Requested action aborted: error in processing");
422 break;
423 case '452': $message = _("Requested action not taken: insufficient system storage");
424 break;
425 case '454': $message = _("Temporary authentication failure");
426 break;
427 case '500': $message = _("Syntax error; command not recognized");
428 break;
429 case '501': $message = _("Syntax error in parameters or arguments");
430 break;
431 case '502': $message = _("Command not implemented");
432 break;
433 case '503': $message = _("Bad sequence of commands");
434 break;
435 case '504': $message = _("Command parameter not implemented");
436 break;
437 case '530': $message = _("Authentication required");
438 break;
439 case '534': $message = _("Authentication mechanism is too weak");
440 break;
441 case '535': $message = _("Authentication failed");
442 break;
443 case '538': $message = _("Encryption required for requested authentication mechanism");
444 break;
445 case '550': $message = _("Requested action not taken: mailbox unavailable");
446 break;
447 case '551': $message = _("User not local; please try forwarding");
448 break;
449 case '552': $message = _("Requested mail action aborted: exceeding storage allocation");
450 break;
451 case '553': $message = _("Requested action not taken: mailbox name not allowed");
452 break;
453 case '554': $message = _("Transaction failed");
454 break;
455 default: $message = _("Unknown response");
456 break;
457 }
458
459 $this->dlv_msg = $message;
460 $this->dlv_server_msg = $server_msg;
461
462 return true;
463 }
464
465 function authPop($pop_server='', $pop_port='', $user, $pass) {
466 if (!$pop_port) {
467 $pop_port = 110;
468 }
469 if (!$pop_server) {
470 $pop_server = 'localhost';
471 }
472 $popConnection = @fsockopen($pop_server, $pop_port, $err_no, $err_str);
473 if (!$popConnection) {
474 error_log("Error connecting to POP Server ($pop_server:$pop_port)"
475 . " $err_no : $err_str");
476 return false;
477 } else {
478 $tmp = fgets($popConnection, 1024); /* banner */
479 if (substr($tmp, 0, 3) != '+OK') {
480 return false;
481 }
482 fputs($popConnection, "USER $user\r\n");
483 $tmp = fgets($popConnection, 1024);
484 if (substr($tmp, 0, 3) != '+OK') {
485 return false;
486 }
487 fputs($popConnection, 'PASS ' . $pass . "\r\n");
488 $tmp = fgets($popConnection, 1024);
489 if (substr($tmp, 0, 3) != '+OK') {
490 return false;
491 }
492 fputs($popConnection, "QUIT\r\n"); /* log off */
493 fclose($popConnection);
494 }
495 return true;
496 }
497
498 /**
499 * Parses ESMTP EHLO response (rfc1869)
500 *
501 * Reads SMTP response to EHLO command and fills class variables
502 * (ehlo array and domain string). Returns last line.
503 * @param stream $stream smtp connection stream.
504 * @return string last ehlo line
505 * @since 1.5.1
506 */
507 function parse_ehlo_response($stream) {
508 // don't cache ehlo information
509 $this->ehlo=array();
510 $ret = '';
511 $firstline = true;
512 /**
513 * ehlo mailclient.example.org
514 * 250-mail.example.org
515 * 250-PIPELINING
516 * 250-SIZE 52428800
517 * 250-DATAZ
518 * 250-STARTTLS
519 * 250-AUTH LOGIN PLAIN
520 * 250 8BITMIME
521 */
522 while ($line=fgets($stream, 1024)){
523 // match[1] = first symbol after 250
524 // match[2] = domain or ehlo-keyword
525 // match[3] = greeting or ehlo-param
526 // match space after keyword in ehlo-keyword CR LF
527 if (preg_match("/^250(-|\s)(\S*)\s+(\S.*)\r\n/",$line,$match)||
528 preg_match("/^250(-|\s)(\S*)\s*\r\n/",$line,$match)) {
529 if ($firstline) {
530 // first ehlo line (250[-\ ]domain SP greeting)
531 $this->domain = $match[2];
532 $firstline=false;
533 } elseif (!isset($match[3])) {
534 // simple one word extension
535 $this->ehlo[strtoupper($match[2])]='';
536 } elseif (!preg_match("/\s/",trim($match[3]))) {
537 // extension with one option
538 // yes, I know about ctype extension. no, i don't want to depend on it
539 $this->ehlo[strtoupper($match[2])]=trim($match[3]);
540 } else {
541 // ehlo-param with spaces
542 $this->ehlo[strtoupper($match[2])]=explode(' ',trim($match[3]));
543 }
544 if ($match[1]==' ') {
545 // stop while cycle, if we reach last 250 line
546 $ret = $line;
547 break;
548 }
549 } else {
550 // this is not 250 response
551 $ret = $line;
552 break;
553 }
554 }
555 return $ret;
556 }
557 }