PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/GSoC-config/squirrelmail/class/deliver/Deliver_SMTP.class.php

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