Aleksander Machniak
2016-02-01 8dc756f319858bf8a6bbe228b8e7ef62d5d77aac
commit | author | age
2c3d81 1 <?php
A 2
a95874 3 /**
2c3d81 4  +-----------------------------------------------------------------------+
e019f2 5  | This file is part of the Roundcube Webmail client                     |
9945f2 6  | Copyright (C) 2005-2012, The Roundcube Dev Team                       |
7fe381 7  |                                                                       |
T 8  | Licensed under the GNU General Public License version 3 or            |
9  | any later version with exceptions for skins & plugins.                |
10  | See the README file for a full license statement.                     |
2c3d81 11  |                                                                       |
A 12  | PURPOSE:                                                              |
13  |   Provide SMTP functionality using socket connections                 |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17 */
18
d062db 19 /**
T 20  * Class to provide SMTP functionality using PEAR Net_SMTP
21  *
9ab346 22  * @package    Framework
AM 23  * @subpackage Mail
d062db 24  * @author     Thomas Bruederli <roundcube@gmail.com>
T 25  * @author     Aleksander Machniak <alec@alec.pl>
26  */
27 class rcube_smtp
28 {
a95874 29     private $conn;
9945f2 30     private $response;
AM 31     private $error;
774dea 32     private $anonymize_log = 0;
2c3d81 33
9945f2 34     // define headers delimiter
AM 35     const SMTP_MIME_CRLF = "\r\n";
2c3d81 36
43079d 37     const DEBUG_LINE_LENGTH = 4098; // 4KB + 2B for \r\n
9b8d22 38
2c3d81 39
9945f2 40     /**
AM 41      * SMTP Connection and authentication
42      *
43      * @param string Server host
44      * @param string Server port
45      * @param string User name
46      * @param string Password
47      *
48      * @return bool  Returns true on success, or false on error
49      */
4e1aa6 50     public function connect($host = null, $port = null, $user = null, $pass = null)
2c3d81 51     {
9945f2 52         $rcube = rcube::get_instance();
2c3d81 53
9945f2 54         // disconnect/destroy $this->conn
d062db 55         $this->disconnect();
2c3d81 56
9945f2 57         // reset error/response var
AM 58         $this->error = $this->response = null;
2c3d81 59
9945f2 60         // let plugins alter smtp connection config
AM 61         $CONFIG = $rcube->plugins->exec_hook('smtp_connect', array(
7e3298 62             'smtp_server'    => $host ?: $rcube->config->get('smtp_server'),
AM 63             'smtp_port'      => $port ?: $rcube->config->get('smtp_port', 25),
4e1aa6 64             'smtp_user'      => $user !== null ? $user : $rcube->config->get('smtp_user'),
AM 65             'smtp_pass'      => $pass !== null ? $pass : $rcube->config->get('smtp_pass'),
9945f2 66             'smtp_auth_cid'  => $rcube->config->get('smtp_auth_cid'),
AM 67             'smtp_auth_pw'   => $rcube->config->get('smtp_auth_pw'),
68             'smtp_auth_type' => $rcube->config->get('smtp_auth_type'),
69             'smtp_helo_host' => $rcube->config->get('smtp_helo_host'),
70             'smtp_timeout'   => $rcube->config->get('smtp_timeout'),
357f9c 71             'smtp_conn_options'   => $rcube->config->get('smtp_conn_options'),
9945f2 72             'smtp_auth_callbacks' => array(),
AM 73         ));
2c3d81 74
9945f2 75         $smtp_host = rcube_utils::parse_host($CONFIG['smtp_server']);
AM 76         // when called from Installer it's possible to have empty $smtp_host here
77         if (!$smtp_host) $smtp_host = 'localhost';
78         $smtp_port     = is_numeric($CONFIG['smtp_port']) ? $CONFIG['smtp_port'] : 25;
79         $smtp_host_url = parse_url($smtp_host);
2c3d81 80
9945f2 81         // overwrite port
AM 82         if (isset($smtp_host_url['host']) && isset($smtp_host_url['port'])) {
83             $smtp_host = $smtp_host_url['host'];
84             $smtp_port = $smtp_host_url['port'];
2c3d81 85         }
A 86
9945f2 87         // re-write smtp host
AM 88         if (isset($smtp_host_url['host']) && isset($smtp_host_url['scheme'])) {
89             $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
2c3d81 90         }
9945f2 91
AM 92         // remove TLS prefix and set flag for use in Net_SMTP::auth()
93         if (preg_match('#^tls://#i', $smtp_host)) {
94             $smtp_host = preg_replace('#^tls://#i', '', $smtp_host);
95             $use_tls   = true;
96         }
97
98         if (!empty($CONFIG['smtp_helo_host'])) {
99             $helo_host = $CONFIG['smtp_helo_host'];
100         }
101         else if (!empty($_SERVER['SERVER_NAME'])) {
102             $helo_host = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
103         }
104         else {
105             $helo_host = 'localhost';
106         }
107
108         // IDNA Support
109         $smtp_host = rcube_utils::idn_to_ascii($smtp_host);
110
357f9c 111         $this->conn = new Net_SMTP($smtp_host, $smtp_port, $helo_host, false, 0, $CONFIG['smtp_conn_options']);
9945f2 112
AM 113         if ($rcube->config->get('smtp_debug')) {
114             $this->conn->setDebug(true, array($this, 'debug_handler'));
774dea 115             $this->anonymize_log = 0;
9945f2 116         }
AM 117
118         // register authentication methods
119         if (!empty($CONFIG['smtp_auth_callbacks']) && method_exists($this->conn, 'setAuthMethod')) {
120             foreach ($CONFIG['smtp_auth_callbacks'] as $callback) {
121                 $this->conn->setAuthMethod($callback['name'], $callback['function'],
122                     isset($callback['prepend']) ? $callback['prepend'] : true);
123             }
124         }
125
126         // try to connect to server and exit on failure
ce89ec 127         $result = $this->conn->connect($CONFIG['smtp_timeout']);
9945f2 128
b59b72 129         if (is_a($result, 'PEAR_Error')) {
b71eef 130             $this->response[] = "Connection failed: " . $result->getMessage();
AM 131
132             list($code,) = $this->conn->getResponse();
133             $this->error = array('label' => 'smtpconnerror', 'vars' => array('code' => $code));
9945f2 134             $this->conn  = null;
b71eef 135
9945f2 136             return false;
AM 137         }
138
139         // workaround for timeout bug in Net_SMTP 1.5.[0-1] (#1487843)
140         if (method_exists($this->conn, 'setTimeout')
141             && ($timeout = ini_get('default_socket_timeout'))
142         ) {
143             $this->conn->setTimeout($timeout);
144         }
145
146         $smtp_user = str_replace('%u', $rcube->get_user_name(), $CONFIG['smtp_user']);
147         $smtp_pass = str_replace('%p', $rcube->get_user_password(), $CONFIG['smtp_pass']);
7e3298 148         $smtp_auth_type = $CONFIG['smtp_auth_type'] ?: null;
9945f2 149
AM 150         if (!empty($CONFIG['smtp_auth_cid'])) {
151             $smtp_authz = $smtp_user;
152             $smtp_user  = $CONFIG['smtp_auth_cid'];
153             $smtp_pass  = $CONFIG['smtp_auth_pw'];
154         }
155
156         // attempt to authenticate to the SMTP server
157         if ($smtp_user && $smtp_pass) {
158             // IDNA Support
159             if (strpos($smtp_user, '@')) {
160                 $smtp_user = rcube_utils::idn_to_ascii($smtp_user);
161             }
162
163             $result = $this->conn->auth($smtp_user, $smtp_pass, $smtp_auth_type, $use_tls, $smtp_authz);
164
b59b72 165             if (is_a($result, 'PEAR_Error')) {
b71eef 166                 list($code,) = $this->conn->getResponse();
AM 167                 $this->error = array('label' => 'smtpautherror', 'vars' => array('code' => $code));
168                 $this->response[] = 'Authentication failure: ' . $result->getMessage()
169                     . ' (Code: ' . $result->getCode() . ')';
170
9945f2 171                 $this->reset();
AM 172                 $this->disconnect();
b71eef 173
9945f2 174                 return false;
AM 175             }
176         }
177
178         return true;
2c3d81 179     }
6d0ada 180
9945f2 181     /**
AM 182      * Function for sending mail
183      *
184      * @param string Sender e-Mail address
185      *
186      * @param mixed  Either a comma-seperated list of recipients
187      *               (RFC822 compliant), or an array of recipients,
188      *               each RFC822 valid. This may contain recipients not
189      *               specified in the headers, for Bcc:, resending
190      *               messages, etc.
191      * @param mixed  The message headers to send with the mail
192      *               Either as an associative array or a finally
193      *               formatted string
194      * @param mixed  The full text of the message body, including any Mime parts
195      *               or file handle
196      * @param array  Delivery options (e.g. DSN request)
197      *
198      * @return bool  Returns true on success, or false on error
199      */
200     public function send_mail($from, $recipients, &$headers, &$body, $opts=null)
201     {
202         if (!is_object($this->conn)) {
203             return false;
204         }
2c3d81 205
9945f2 206         // prepare message headers as string
AM 207         if (is_array($headers)) {
208             if (!($headerElements = $this->_prepare_headers($headers))) {
209                 $this->reset();
210                 return false;
211             }
212
213             list($from, $text_headers) = $headerElements;
214         }
215         else if (is_string($headers)) {
216             $text_headers = $headers;
217         }
218
219         // exit if no from address is given
220         if (!isset($from)) {
221             $this->reset();
222             $this->response[] = "No From address has been provided";
223             return false;
224         }
225
226         // RFC3461: Delivery Status Notification
227         if ($opts['dsn']) {
228             $exts = $this->conn->getServiceExtensions();
229
230             if (isset($exts['DSN'])) {
231                 $from_params      = 'RET=HDRS';
232                 $recipient_params = 'NOTIFY=SUCCESS,FAILURE';
233             }
234         }
235
236         // RFC2298.3: remove envelope sender address
232535 237         if (empty($opts['mdn_use_from'])
AM 238             && preg_match('/Content-Type: multipart\/report/', $text_headers)
9945f2 239             && preg_match('/report-type=disposition-notification/', $text_headers)
AM 240         ) {
241             $from = '';
242         }
243
244         // set From: address
b59b72 245         $result = $this->conn->mailFrom($from, $from_params);
AM 246         if (is_a($result, 'PEAR_Error')) {
9945f2 247             $err = $this->conn->getResponse();
AM 248             $this->error = array('label' => 'smtpfromerror', 'vars' => array(
a3fa84 249                 'from' => $from, 'code' => $err[0], 'msg' => $err[1]));
AM 250             $this->response[] = "Failed to set sender '$from'. "
251                 . $err[1] . ' (Code: ' . $err[0] . ')';
9945f2 252             $this->reset();
AM 253             return false;
254         }
255
256         // prepare list of recipients
257         $recipients = $this->_parse_rfc822($recipients);
b59b72 258         if (is_a($recipients, 'PEAR_Error')) {
9945f2 259             $this->error = array('label' => 'smtprecipientserror');
AM 260             $this->reset();
261             return false;
262         }
263
264         // set mail recipients
265         foreach ($recipients as $recipient) {
b59b72 266             $result = $this->conn->rcptTo($recipient, $recipient_params);
AM 267             if (is_a($result, 'PEAR_Error')) {
9945f2 268                 $err = $this->conn->getResponse();
AM 269                 $this->error = array('label' => 'smtptoerror', 'vars' => array(
a3fa84 270                     'to' => $recipient, 'code' => $err[0], 'msg' => $err[1]));
AM 271                 $this->response[] = "Failed to add recipient '$recipient'. "
272                     . $err[1] . ' (Code: ' . $err[0] . ')';
9945f2 273                 $this->reset();
AM 274                 return false;
275             }
276         }
277
278         if (is_resource($body)) {
279             // file handle
36a7f5 280             $data = $body;
AM 281
282             if ($text_headers) {
283                 $text_headers = preg_replace('/[\r\n]+$/', '', $text_headers);
284             }
9945f2 285         }
AM 286         else {
287             // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
288             // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy.
289             // We are still forced to make another copy here for a couple ticks so we don't really
290             // get to save a copy in the method call.
291             $data = $text_headers . "\r\n" . $body;
292
293             // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
294             unset($text_headers, $body);
295         }
296
297         // Send the message's headers and the body as SMTP data.
62b847 298         $result = $this->conn->data($data, $text_headers);
b59b72 299         if (is_a($result, 'PEAR_Error')) {
9945f2 300             $err = $this->conn->getResponse();
AM 301             if (!in_array($err[0], array(354, 250, 221))) {
302                 $msg = sprintf('[%d] %s', $err[0], $err[1]);
303             }
304             else {
305                 $msg = $result->getMessage();
306             }
307
308             $this->error = array('label' => 'smtperror', 'vars' => array('msg' => $msg));
a3fa84 309             $this->response[] = "Failed to send data. " . $msg;
9945f2 310             $this->reset();
AM 311             return false;
312         }
313
314         $this->response[] = join(': ', $this->conn->getResponse());
315         return true;
316     }
317
318     /**
319      * Reset the global SMTP connection
320      */
321     public function reset()
322     {
323         if (is_object($this->conn)) {
324             $this->conn->rset();
325         }
326     }
327
328     /**
329      * Disconnect the global SMTP connection
330      */
331     public function disconnect()
332     {
333         if (is_object($this->conn)) {
334             $this->conn->disconnect();
335             $this->conn = null;
336         }
337     }
338
339     /**
340      * This is our own debug handler for the SMTP connection
341      */
342     public function debug_handler(&$smtp, $message)
343     {
774dea 344         // catch AUTH commands and set anonymization flag for subsequent sends
TB 345         if (preg_match('/^Send: AUTH ([A-Z]+)/', $message, $m)) {
346             $this->anonymize_log = $m[1] == 'LOGIN' ? 2 : 1;
347         }
348         // anonymize this log entry
349         else if ($this->anonymize_log > 0 && strpos($message, 'Send:') === 0 && --$this->anonymize_log == 0) {
350             $message = sprintf('Send: ****** [%d]', strlen($message) - 8);
351         }
352
9b8d22 353         if (($len = strlen($message)) > self::DEBUG_LINE_LENGTH) {
43079d 354             $diff    = $len - self::DEBUG_LINE_LENGTH;
AM 355             $message = substr($message, 0, self::DEBUG_LINE_LENGTH)
356                 . "... [truncated $diff bytes]";
9b8d22 357         }
AM 358
9945f2 359         rcube::write_log('smtp', preg_replace('/\r\n$/', '', $message));
AM 360     }
361
362     /**
363      * Get error message
364      */
365     public function get_error()
366     {
367         return $this->error;
368     }
369
370     /**
371      * Get server response messages array
372      */
373     public function get_response()
374     {
375          return $this->response;
376     }
377
378     /**
379      * Take an array of mail headers and return a string containing
380      * text usable in sending a message.
381      *
382      * @param array $headers The array of headers to prepare, in an associative
383      *              array, where the array key is the header name (ie,
384      *              'Subject'), and the array value is the header
385      *              value (ie, 'test'). The header produced from those
386      *              values would be 'Subject: test'.
387      *
388      * @return mixed Returns false if it encounters a bad address,
389      *               otherwise returns an array containing two
390      *               elements: Any From: address found in the headers,
391      *               and the plain text version of the headers.
392      */
393     private function _prepare_headers($headers)
394     {
395         $lines = array();
396         $from  = null;
397
398         foreach ($headers as $key => $value) {
399             if (strcasecmp($key, 'From') === 0) {
400                 $addresses = $this->_parse_rfc822($value);
401
402                 if (is_array($addresses)) {
403                     $from = $addresses[0];
404                 }
405
406                 // Reject envelope From: addresses with spaces.
407                 if (strpos($from, ' ') !== false) {
408                     return false;
409                 }
410
411                 $lines[] = $key . ': ' . $value;
412             }
413             else if (strcasecmp($key, 'Received') === 0) {
414                 $received = array();
415                 if (is_array($value)) {
416                     foreach ($value as $line) {
417                         $received[] = $key . ': ' . $line;
418                     }
419                 }
420                 else {
421                     $received[] = $key . ': ' . $value;
422                 }
423
424                 // Put Received: headers at the top.  Spam detectors often
425                 // flag messages with Received: headers after the Subject:
426                 // as spam.
427                 $lines = array_merge($received, $lines);
428             }
429             else {
430                 // If $value is an array (i.e., a list of addresses), convert
431                 // it to a comma-delimited string of its elements (addresses).
432                 if (is_array($value)) {
433                     $value = implode(', ', $value);
434                 }
435
436                 $lines[] = $key . ': ' . $value;
437             }
438         }
439
440         return array($from, join(self::SMTP_MIME_CRLF, $lines) . self::SMTP_MIME_CRLF);
441     }
442
443     /**
444      * Take a set of recipients and parse them, returning an array of
445      * bare addresses (forward paths) that can be passed to sendmail
446      * or an smtp server with the rcpt to: command.
447      *
448      * @param mixed Either a comma-seperated list of recipients
449      *              (RFC822 compliant), or an array of recipients,
450      *              each RFC822 valid.
451      *
452      * @return array An array of forward paths (bare addresses).
453      */
454     private function _parse_rfc822($recipients)
455     {
456         // if we're passed an array, assume addresses are valid and implode them before parsing.
457         if (is_array($recipients)) {
458             $recipients = implode(', ', $recipients);
459         }
460
461         $addresses  = array();
8dc756 462         $recipients = preg_replace('/[\s\t]*\r?\n/', '', $recipients);
9945f2 463         $recipients = rcube_utils::explode_quoted_string(',', $recipients);
AM 464
465         reset($recipients);
3725cf 466         foreach ($recipients as $recipient) {
9945f2 467             $a = rcube_utils::explode_quoted_string(' ', $recipient);
3725cf 468             foreach ($a as $word) {
8dc756 469                 $word = trim($word);
AM 470                 $len  = strlen($word);
471
472                 if ($len && strpos($word, "@") > 0 && $word[$len-1] != '"') {
473                     $word = preg_replace('/^<|>$/', '', $word);
474                     if (!in_array($word, $addresses)) {
9945f2 475                         array_push($addresses, $word);
AM 476                     }
477                 }
478             }
479         }
480
481         return $addresses;
482     }
2c3d81 483 }