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

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