You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_smtp.php 17KB

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