PageRenderTime 53ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/rel-1_5_1/squirrelmail/class/deliver/Deliver_SMTP.class.php

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