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