Cleanup Exception logging

This commit is contained in:
the-djmaze 2022-12-18 23:56:38 +01:00
parent d126380282
commit a21c859aba
11 changed files with 134 additions and 308 deletions

View file

@ -34,7 +34,7 @@ trait Messages
{ {
if (!\strlen(\trim($sIndexRange))) if (!\strlen(\trim($sIndexRange)))
{ {
$this->writeLogException(new \InvalidArgumentException, \LOG_ERR, true); $this->writeLogException(new \InvalidArgumentException, \LOG_ERR);
} }
$aReturn = array(); $aReturn = array();
@ -199,7 +199,7 @@ trait Messages
public function MessageCopy(string $sToFolder, SequenceSet $oRange) : ResponseCollection public function MessageCopy(string $sToFolder, SequenceSet $oRange) : ResponseCollection
{ {
if (!\count($oRange)) { if (!\count($oRange)) {
$this->writeLogException(new \InvalidArgumentException, \LOG_ERR, true); $this->writeLogException(new \InvalidArgumentException, \LOG_ERR);
} }
return $this->SendRequestGetResponse( return $this->SendRequestGetResponse(
@ -217,13 +217,11 @@ trait Messages
public function MessageMove(string $sToFolder, SequenceSet $oRange) : ResponseCollection public function MessageMove(string $sToFolder, SequenceSet $oRange) : ResponseCollection
{ {
if (!\count($oRange)) { if (!\count($oRange)) {
$this->writeLogException(new \InvalidArgumentException, \LOG_ERR, true); $this->writeLogException(new \InvalidArgumentException, \LOG_ERR);
} }
if (!$this->hasCapability('MOVE')) { if (!$this->hasCapability('MOVE')) {
$this->writeLogException( $this->writeLogException(new \MailSo\RuntimeException('Move is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('Move is not supported'),
\LOG_ERR, true);
} }
return $this->SendRequestGetResponse( return $this->SendRequestGetResponse(

View file

@ -88,7 +88,7 @@ class ImapClient extends \MailSo\Net\NetClient
} else { } else {
$this->writeLogException( $this->writeLogException(
new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('STARTTLS is not supported'), new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('STARTTLS is not supported'),
\LOG_ERR, true); \LOG_ERR);
} }
} }
@ -112,9 +112,7 @@ class ImapClient extends \MailSo\Net\NetClient
if (!\strlen($sLogin) || !\strlen($sPassword)) if (!\strlen($sLogin) || !\strlen($sPassword))
{ {
$this->writeLogException( $this->writeLogException(new \InvalidArgumentException, \LOG_ERR);
new \InvalidArgumentException,
\LOG_ERR, true);
} }
$this->sLogginedUser = $sLogin; $this->sLogginedUser = $sLogin;
@ -233,10 +231,7 @@ class ImapClient extends \MailSo\Net\NetClient
} }
catch (Exceptions\NegativeResponseException $oException) catch (Exceptions\NegativeResponseException $oException)
{ {
$this->writeLogException( $this->writeLogException(new Exceptions\LoginBadCredentialsException($oException->GetResponses(), '', 0, $oException));
new Exceptions\LoginBadCredentialsException(
$oException->GetResponses(), '', 0, $oException),
\LOG_NOTICE, true);
} }
$this->bIsLoggined = true; $this->bIsLoggined = true;
@ -381,7 +376,6 @@ class ImapClient extends \MailSo\Net\NetClient
throw new Exceptions\ResponseException; throw new Exceptions\ResponseException;
} catch (\Throwable $e) { } catch (\Throwable $e) {
$this->writeLogException($e, \LOG_ERR); $this->writeLogException($e, \LOG_ERR);
throw $e;
} }
} }
@ -419,7 +413,7 @@ class ImapClient extends \MailSo\Net\NetClient
{ {
$sCommand = \trim($sCommand); $sCommand = \trim($sCommand);
if (!\strlen($sCommand)) { if (!\strlen($sCommand)) {
$this->writeLogException(new \InvalidArgumentException, \LOG_ERR, true); $this->writeLogException(new \InvalidArgumentException, \LOG_ERR);
} }
$this->IsConnected(true); $this->IsConnected(true);
@ -462,13 +456,9 @@ class ImapClient extends \MailSo\Net\NetClient
if ($sResult) { if ($sResult) {
return $sResult; return $sResult;
} }
$this->writeLogException( $this->writeLogException(new Exceptions\LoginException);
new Exceptions\LoginException,
\LOG_NOTICE, true);
} }
$this->writeLogException( $this->writeLogException(new Exceptions\LoginException);
new Exceptions\LoginException,
\LOG_NOTICE, true);
} }
/** /**
@ -499,7 +489,6 @@ class ImapClient extends \MailSo\Net\NetClient
} }
} catch (\Throwable $e) { } catch (\Throwable $e) {
$this->writeLogException($e, \LOG_WARNING); $this->writeLogException($e, \LOG_WARNING);
throw $e;
} }
} }
@ -537,7 +526,6 @@ class ImapClient extends \MailSo\Net\NetClient
} catch (\Throwable $e) { } catch (\Throwable $e) {
$this->writeLogException($e, \LOG_WARNING); $this->writeLogException($e, \LOG_WARNING);
throw $e;
} }
return $oResult; return $oResult;
@ -582,7 +570,6 @@ class ImapClient extends \MailSo\Net\NetClient
} catch (\Throwable $e) { } catch (\Throwable $e) {
$this->writeLogException($e, \LOG_WARNING); $this->writeLogException($e, \LOG_WARNING);
throw $e;
} }
} }

View file

@ -53,9 +53,7 @@ class ESEARCH extends Request
function __construct(\MailSo\Imap\ImapClient $oImapClient) function __construct(\MailSo\Imap\ImapClient $oImapClient)
{ {
if (!$oImapClient->hasCapability('ESEARCH')) { if (!$oImapClient->hasCapability('ESEARCH')) {
$oImapClient->writeLogException( $oImapClient->writeLogException(new \MailSo\RuntimeException('ESEARCH is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('ESEARCH is not supported'),
\LOG_ERR, true);
} }
parent::__construct($oImapClient); parent::__construct($oImapClient);
} }
@ -67,9 +65,7 @@ class ESEARCH extends Request
/* // RFC 6203 /* // RFC 6203
if (false !== \stripos($this->sCriterias, 'FUZZY') && !$this->oImapClient->hasCapability('SEARCH=FUZZY')) { if (false !== \stripos($this->sCriterias, 'FUZZY') && !$this->oImapClient->hasCapability('SEARCH=FUZZY')) {
$this->oImapClient->writeLogException( $this->oImapClient->writeLogException(new \MailSo\RuntimeException('SEARCH=FUZZY is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('SEARCH=FUZZY is not supported'),
\LOG_ERR, true);
} }
*/ */
@ -88,9 +84,7 @@ class ESEARCH extends Request
} }
if ($aFolders) { if ($aFolders) {
if (!$this->oImapClient->hasCapability('MULTISEARCH')) { if (!$this->oImapClient->hasCapability('MULTISEARCH')) {
$this->oImapClient->writeLogException( $this->oImapClient->writeLogException(new \MailSo\RuntimeException('MULTISEARCH is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('MULTISEARCH is not supported'),
\LOG_ERR, true);
} }
$sCmd = 'ESEARCH'; $sCmd = 'ESEARCH';
$aReques[] = 'IN'; $aReques[] = 'IN';
@ -108,9 +102,7 @@ class ESEARCH extends Request
if (!$this->oImapClient->hasCapability('CONTEXT=SEARCH')) { if (!$this->oImapClient->hasCapability('CONTEXT=SEARCH')) {
foreach ($this->aReturn as $sReturn) { foreach ($this->aReturn as $sReturn) {
if (\preg_match('/PARTIAL|UPDATE|CONTEXT/i', $sReturn)) { if (\preg_match('/PARTIAL|UPDATE|CONTEXT/i', $sReturn)) {
$this->oImapClient->writeLogException( $this->oImapClient->writeLogException(new \MailSo\RuntimeException('CONTEXT=SEARCH is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('CONTEXT=SEARCH is not supported'),
\LOG_ERR, true);
} }
} }
} }

View file

@ -54,9 +54,7 @@ class SORT extends Request
function __construct(\MailSo\Imap\ImapClient $oImapClient) function __construct(\MailSo\Imap\ImapClient $oImapClient)
{ {
if (!$oImapClient->hasCapability('SORT')) { if (!$oImapClient->hasCapability('SORT')) {
$oImapClient->writeLogException( $oImapClient->writeLogException(new \MailSo\RuntimeException('SORT is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('SORT is not supported'),
\LOG_ERR, true);
} }
parent::__construct($oImapClient); parent::__construct($oImapClient);
} }
@ -64,9 +62,7 @@ class SORT extends Request
public function SendRequest() : string public function SendRequest() : string
{ {
if (!$this->aSortTypes) { if (!$this->aSortTypes) {
$this->oImapClient->writeLogException( $this->oImapClient->writeLogException(new \MailSo\RuntimeException('SortTypes are missing'), \LOG_ERR);
new \MailSo\RuntimeException('SortTypes are missing'),
\LOG_ERR, true);
} }
$aRequest = array(); $aRequest = array();
@ -74,16 +70,12 @@ class SORT extends Request
if ($this->aReturn) { if ($this->aReturn) {
// RFC 5267 checks // RFC 5267 checks
if (!$this->oImapClient->hasCapability('ESORT')) { if (!$this->oImapClient->hasCapability('ESORT')) {
$this->oImapClient->writeLogException( $this->oImapClient->writeLogException(new \MailSo\RuntimeException('ESORT is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('ESORT is not supported'),
\LOG_ERR, true);
} }
if (!$this->oImapClient->hasCapability('CONTEXT=SORT')) { if (!$this->oImapClient->hasCapability('CONTEXT=SORT')) {
foreach ($this->aReturn as $sReturn) { foreach ($this->aReturn as $sReturn) {
if (\preg_match('/PARTIAL|UPDATE|CONTEXT/i', $sReturn)) { if (\preg_match('/PARTIAL|UPDATE|CONTEXT/i', $sReturn)) {
$this->oImapClient->writeLogException( $this->oImapClient->writeLogException(new \MailSo\RuntimeException('CONTEXT=SORT is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('CONTEXT=SORT is not supported'),
\LOG_ERR, true);
} }
} }
} }

View file

@ -34,9 +34,7 @@ class THREAD extends Request
} else if ($oImapClient->hasCapability('THREAD=ORDEREDSUBJECT')) { } else if ($oImapClient->hasCapability('THREAD=ORDEREDSUBJECT')) {
$this->sAlgorithm = 'ORDEREDSUBJECT'; $this->sAlgorithm = 'ORDEREDSUBJECT';
} else { } else {
$oImapClient->writeLogException( $oImapClient->writeLogException(new \MailSo\RuntimeException('THREAD is not supported'), \LOG_ERR);
new \MailSo\RuntimeException('THREAD is not supported'),
\LOG_ERR, true);
} }
parent::__construct($oImapClient); parent::__construct($oImapClient);
} }
@ -44,9 +42,7 @@ class THREAD extends Request
public function SendRequestIterateResponse() : iterable public function SendRequestIterateResponse() : iterable
{ {
if (!$this->oImapClient->hasCapability(\strtoupper("THREAD={$this->sAlgorithm}"))) { if (!$this->oImapClient->hasCapability(\strtoupper("THREAD={$this->sAlgorithm}"))) {
$this->oImapClient->writeLogException( $this->oImapClient->writeLogException(new \MailSo\RuntimeException("THREAD={$this->sAlgorithm} is not supported"), \LOG_ERR);
new \MailSo\RuntimeException("THREAD={$this->sAlgorithm} is not supported"),
\LOG_ERR, true);
} }
$this->oImapClient->SendRequest( $this->oImapClient->SendRequest(

View file

@ -412,7 +412,7 @@ trait ResponseParser
} }
catch (\Throwable $oException) catch (\Throwable $oException)
{ {
$this->writeLogException($oException); $this->writeLogException($oException, \LOG_NOTICE, false);
} }
if ($rImapLiteralStream) { if ($rImapLiteralStream) {

View file

@ -189,13 +189,21 @@ class Logger extends \SplFixedArray
return $this->Write(\print_r($mValue, true), $iType, $sName); return $this->Write(\print_r($mValue, true), $iType, $sName);
} }
private $aExceptions = [];
public function WriteException(\Throwable $oException, int $iType = \LOG_NOTICE, string $sName = '') : void public function WriteException(\Throwable $oException, int $iType = \LOG_NOTICE, string $sName = '') : void
{ {
if (!\in_array($oException, $this->aExceptions)) {
$this->Write((string) $oException, $iType, $sName); $this->Write((string) $oException, $iType, $sName);
$this->aExceptions[] = $oException;
}
} }
public function WriteExceptionShort(\Throwable $oException, int $iType = \LOG_NOTICE, string $sName = '') : void public function WriteExceptionShort(\Throwable $oException, int $iType = \LOG_NOTICE, string $sName = '') : void
{ {
if (!\in_array($oException, $this->aExceptions)) {
$this->Write($oException->getMessage(), $iType, $sName); $this->Write($oException->getMessage(), $iType, $sName);
$this->aExceptions[] = $oException;
}
} }
} }

View file

@ -31,6 +31,7 @@ class ConnectSettings implements \JsonSerializable
// public int $type = Enumerations\ConnectionSecurityType::NONE; // public int $type = Enumerations\ConnectionSecurityType::NONE;
public SSLContext $ssl; public SSLContext $ssl;
// public bool $tls_weak = false;
// Authentication settings use by all child classes // Authentication settings use by all child classes
public bool $useAuth = true; public bool $useAuth = true;
@ -74,6 +75,7 @@ class ConnectSettings implements \JsonSerializable
if (isset($aSettings['sasl'])) { if (isset($aSettings['sasl'])) {
$object->SASLMechanisms = $aSettings['sasl']; $object->SASLMechanisms = $aSettings['sasl'];
} }
// $object->tls_weak = !empty($aSettings['tls_weak']);
return $object; return $object;
} }
@ -89,6 +91,7 @@ class ConnectSettings implements \JsonSerializable
'shortLogin' => $this->shortLogin, 'shortLogin' => $this->shortLogin,
'sasl' => $this->SASLMechanisms, 'sasl' => $this->SASLMechanisms,
'ssl' => $this->ssl 'ssl' => $this->ssl
// 'tls_weak' => $this->tls_weak
); );
} }

View file

@ -90,15 +90,11 @@ abstract class NetClient
{ {
$oSettings->host = \trim($oSettings->host); $oSettings->host = \trim($oSettings->host);
if (!\strlen($oSettings->host) || !\MailSo\Base\Validator::RangeInt($oSettings->port, 0, 65535)) { if (!\strlen($oSettings->host) || !\MailSo\Base\Validator::RangeInt($oSettings->port, 0, 65535)) {
$this->writeLogException( $this->writeLogException(new \MailSo\Base\Exceptions\InvalidArgumentException, \LOG_ERR);
new \MailSo\Base\Exceptions\InvalidArgumentException,
\LOG_ERR, true);
} }
if ($this->IsConnected()) { if ($this->IsConnected()) {
$this->writeLogException( $this->writeLogException(new Exceptions\SocketAlreadyConnectedException, \LOG_ERR);
new Exceptions\SocketAlreadyConnectedException,
\LOG_ERR, true);
} }
$this->Settings = $oSettings; $this->Settings = $oSettings;
@ -118,7 +114,7 @@ abstract class NetClient
if (!$this->ssl && \MailSo\Net\Enumerations\ConnectionSecurityType::SSL === $this->Settings->type) { if (!$this->ssl && \MailSo\Net\Enumerations\ConnectionSecurityType::SSL === $this->Settings->type) {
$this->writeLogException( $this->writeLogException(
new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('SSL isn\'t supported: ('.\implode(', ', \stream_get_transports()).')'), new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('SSL isn\'t supported: ('.\implode(', ', \stream_get_transports()).')'),
\LOG_ERR, true); \LOG_ERR);
} }
$this->iStartConnectTime = \microtime(true); $this->iStartConnectTime = \microtime(true);
@ -150,44 +146,37 @@ abstract class NetClient
new Exceptions\SocketCanNotConnectToHostException( new Exceptions\SocketCanNotConnectToHostException(
\MailSo\Base\Locale::ConvertSystemString($sErrorStr), (int) $iErrorNo, \MailSo\Base\Locale::ConvertSystemString($sErrorStr), (int) $iErrorNo,
'Can\'t connect to host "'.$this->sConnectedHost.':'.$this->Settings->port.'"' 'Can\'t connect to host "'.$this->sConnectedHost.':'.$this->Settings->port.'"'
), \LOG_NOTICE, true); )
);
} }
$this->writeLog((\microtime(true) - $this->iStartConnectTime).' (raw connection)', \LOG_DEBUG); $this->writeLog((\microtime(true) - $this->iStartConnectTime).' (raw connection)', \LOG_DEBUG);
if ($this->rConnect) { if ($this->rConnect && \MailSo\Base\Utils::FunctionCallable('stream_set_timeout')) {
if (\MailSo\Base\Utils::FunctionCallable('stream_set_timeout')) {
\stream_set_timeout($this->rConnect, \max(5, $oSettings->timeout)); \stream_set_timeout($this->rConnect, \max(5, $oSettings->timeout));
} }
} }
}
public function Encrypted() : bool public function Encrypted() : bool
{ {
return $this->rConnect && !empty(\stream_get_meta_data($this->rConnect)['crypto']); return $this->rConnect && !empty(\stream_get_meta_data($this->rConnect)['crypto']);
} }
public function EnableCrypto(bool $insecure = false) public function EnableCrypto() : void
{ {
$bError = true; $bSuccess = false;
if ($this->rConnect && \MailSo\Base\Utils::FunctionCallable('stream_socket_enable_crypto')) { if ($this->rConnect && \MailSo\Base\Utils::FunctionCallable('stream_socket_enable_crypto')) {
$crypto_method = STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; $crypto_method = STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && OPENSSL_VERSION_NUMBER >= 0x10101000) { if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && OPENSSL_VERSION_NUMBER >= 0x10101000) {
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT; $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT;
} }
if ($insecure) { // if ($this->Settings->tls_weak) {
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; // $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
} // }
if (\stream_socket_enable_crypto($this->rConnect, true, $crypto_method)) { $bSuccess = \stream_socket_enable_crypto($this->rConnect, true, $crypto_method);
$bError = false;
}
} }
if ($bError) { $bSuccess || $this->writeLogException(new \MailSo\RuntimeException('Cannot enable STARTTLS.'), \LOG_ERR);
$this->writeLogException(
new \MailSo\RuntimeException('Cannot enable STARTTLS.'),
\LOG_ERR, true);
}
} }
/** /**
@ -196,10 +185,8 @@ abstract class NetClient
*/ */
public function Disconnect() : void public function Disconnect() : void
{ {
if ($this->rConnect) if ($this->rConnect) {
{ if (!$this->bUnreadBuffer && !$this->bRunningCallback) {
if (!$this->bUnreadBuffer && !$this->bRunningCallback)
{
$this->Logout(); $this->Logout();
} }
@ -208,13 +195,10 @@ abstract class NetClient
$this->writeLog('Disconnected from "'.$this->sConnectedHost.':'.$this->Settings->port.'" ('. $this->writeLog('Disconnected from "'.$this->sConnectedHost.':'.$this->Settings->port.'" ('.
(($bResult) ? 'success' : 'unsuccess').')'); (($bResult) ? 'success' : 'unsuccess').')');
if ($this->iStartConnectTime) if ($this->iStartConnectTime) {
{
$this->writeLog((\microtime(true) - $this->iStartConnectTime).' (net session)', \LOG_DEBUG); $this->writeLog((\microtime(true) - $this->iStartConnectTime).' (net session)', \LOG_DEBUG);
$this->iStartConnectTime = 0; $this->iStartConnectTime = 0;
} }
$this->rConnect = null; $this->rConnect = null;
} }
} }
@ -227,9 +211,7 @@ abstract class NetClient
return true; return true;
} }
if ($bThrowExceptionOnFalse) { if ($bThrowExceptionOnFalse) {
$this->writeLogException( $this->writeLogException(new Exceptions\SocketConnectionDoesNotAvailableException, \LOG_ERR);
new Exceptions\SocketConnectionDoesNotAvailableException,
\LOG_ERR, true);
} }
return false; return false;
} }
@ -255,7 +237,7 @@ abstract class NetClient
protected function sendRaw(string $sRaw, bool $bWriteToLog = true, string $sFakeRaw = '') : void protected function sendRaw(string $sRaw, bool $bWriteToLog = true, string $sFakeRaw = '') : void
{ {
if ($this->bUnreadBuffer) { if ($this->bUnreadBuffer) {
$this->writeLogException(new Exceptions\SocketUnreadBufferException, \LOG_ERR, true); $this->writeLogException(new Exceptions\SocketUnreadBufferException, \LOG_ERR);
} }
$sRaw .= "\r\n"; $sRaw .= "\r\n";
@ -266,13 +248,10 @@ abstract class NetClient
} }
$mResult = \fwrite($this->rConnect, $sRaw); $mResult = \fwrite($this->rConnect, $sRaw);
if (false === $mResult) if (false === $mResult) {
{
$this->IsConnected(true); $this->IsConnected(true);
$this->writeLogException(new Exceptions\SocketWriteException, \LOG_ERR, true); $this->writeLogException(new Exceptions\SocketWriteException, \LOG_ERR);
} } else if ($bWriteToLog) {
else if ($bWriteToLog)
{
$this->writeLogWithCrlf('> '.($bFake ? $sFakeRaw : $sRaw)); $this->writeLogWithCrlf('> '.($bFake ? $sFakeRaw : $sRaw));
} }
} }
@ -281,72 +260,44 @@ abstract class NetClient
* @throws \MailSo\Net\Exceptions\SocketConnectionDoesNotAvailableException * @throws \MailSo\Net\Exceptions\SocketConnectionDoesNotAvailableException
* @throws \MailSo\Net\Exceptions\SocketReadException * @throws \MailSo\Net\Exceptions\SocketReadException
*/ */
protected function getNextBuffer(?int $iReadLen = null, bool $bForceLogin = false) : void protected function getNextBuffer(?int $iReadLen = null) : void
{
if (null === $iReadLen)
{ {
if (null === $iReadLen) {
$this->sResponseBuffer = \fgets($this->rConnect); $this->sResponseBuffer = \fgets($this->rConnect);
} } else {
else
{
$this->sResponseBuffer = ''; $this->sResponseBuffer = '';
$iRead = $iReadLen; $iRead = $iReadLen;
while (0 < $iRead) while (0 < $iRead) {
{
$sAddRead = \fread($this->rConnect, $iRead); $sAddRead = \fread($this->rConnect, $iRead);
if (false === $sAddRead) if (false === $sAddRead) {
{
$this->sResponseBuffer = false; $this->sResponseBuffer = false;
break; break;
} }
$this->sResponseBuffer .= $sAddRead; $this->sResponseBuffer .= $sAddRead;
$iRead -= \strlen($sAddRead); $iRead -= \strlen($sAddRead);
} }
} }
if (false === $this->sResponseBuffer) if (false === $this->sResponseBuffer) {
{
$this->IsConnected(true); $this->IsConnected(true);
$this->bUnreadBuffer = true; $this->bUnreadBuffer = true;
$aSocketStatus = \stream_get_meta_data($this->rConnect); $aSocketStatus = \stream_get_meta_data($this->rConnect);
if (isset($aSocketStatus['timed_out']) && $aSocketStatus['timed_out']) if (isset($aSocketStatus['timed_out']) && $aSocketStatus['timed_out']) {
{ $this->writeLogException(new Exceptions\SocketReadTimeoutException, \LOG_ERR);
$this->writeLogException( } else {
new Exceptions\SocketReadTimeoutException,
\LOG_ERR, true);
}
else
{
$this->writeLog('Stream Meta: '.\print_r($aSocketStatus, true), \LOG_ERR); $this->writeLog('Stream Meta: '.\print_r($aSocketStatus, true), \LOG_ERR);
$this->writeLogException(new Exceptions\SocketReadException, \LOG_ERR);
$this->writeLogException(
new Exceptions\SocketReadException,
\LOG_ERR, true);
} }
} } else {
else $iReadBytes = \strlen($this->sResponseBuffer);
{ // $iReadLen && $this->writeLog('Received '.$iReadBytes.'/'.$iReadLen.' bytes.');
$iReadedLen = \strlen($this->sResponseBuffer);
if (null === $iReadLen || $bForceLogin)
{
$iLimit = 5000; // 5KB $iLimit = 5000; // 5KB
if ($iLimit < $iReadedLen) if ($iLimit < $iReadBytes) {
{ $this->writeLogWithCrlf('[cutted:'.$iReadBytes.'] < '.\substr($this->sResponseBuffer, 0, $iLimit).'...');
$this->writeLogWithCrlf('[cutted:'.$iReadedLen.'] < '.\substr($this->sResponseBuffer, 0, $iLimit).'...'); } else {
}
else
{
// $this->writeLogWithCrlf('< '.$this->sResponseBuffer, //.' ['.$iReadedLen.']',
$this->writeLogWithCrlf('< '.$this->sResponseBuffer); $this->writeLogWithCrlf('< '.$this->sResponseBuffer);
} }
} }
else
{
$this->writeLog('Received '.$iReadedLen.'/'.$iReadLen.' bytes.');
}
}
} }
abstract function getLogName() : string; abstract function getLogName() : string;
@ -361,21 +312,15 @@ abstract class NetClient
$this->oLogger && $this->oLogger->Write($sDesc, \LOG_INFO, $this->getLogName(), true, true); $this->oLogger && $this->oLogger->Write($sDesc, \LOG_INFO, $this->getLogName(), true, true);
} }
protected function writeLogException(\Throwable $oException, protected function writeLogException(\Throwable $oException, int $iDescType = \LOG_NOTICE, bool $bThrowException = true) : void
int $iDescType = \LOG_NOTICE, bool $bThrowException = false) : void
{
if ($this->oLogger)
{
if ($oException instanceof Exceptions\SocketCanNotConnectToHostException)
{ {
if ($this->oLogger) {
if ($oException instanceof Exceptions\SocketCanNotConnectToHostException) {
$this->oLogger->Write('Socket: ['.$oException->getSocketCode().'] '.$oException->getSocketMessage(), $iDescType, $this->getLogName()); $this->oLogger->Write('Socket: ['.$oException->getSocketCode().'] '.$oException->getSocketMessage(), $iDescType, $this->getLogName());
} }
$this->oLogger->WriteException($oException, $iDescType, $this->getLogName()); $this->oLogger->WriteException($oException, $iDescType, $this->getLogName());
} }
if ($bThrowException) {
if ($bThrowException)
{
throw $oException; throw $oException;
} }
} }

View file

@ -78,7 +78,7 @@ class SieveClient extends \MailSo\Net\NetClient
} else { } else {
$this->writeLogException( $this->writeLogException(
new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('STARTTLS is not supported'), new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('STARTTLS is not supported'),
\LOG_ERR, true); \LOG_ERR);
} }
} }
@ -93,11 +93,8 @@ class SieveClient extends \MailSo\Net\NetClient
$sLogin = $oSettings->Login; $sLogin = $oSettings->Login;
$sPassword = $oSettings->Password; $sPassword = $oSettings->Password;
$sLoginAuthKey = ''; $sLoginAuthKey = '';
if (!\strlen($sLogin) || !\strlen($sPassword)) if (!\strlen($sLogin) || !\strlen($sPassword)) {
{ $this->writeLogException(new \InvalidArgumentException, \LOG_ERR);
$this->writeLogException(
new \InvalidArgumentException,
\LOG_ERR, true);
} }
$type = ''; $type = '';
@ -112,9 +109,7 @@ class SieveClient extends \MailSo\Net\NetClient
$this->StartTLS(); $this->StartTLS();
return $this->Login($oSettings); return $this->Login($oSettings);
} }
$this->writeLogException( $this->writeLogException(new \MailSo\Sieve\Exceptions\LoginException, \LOG_ERR);
new \MailSo\Sieve\Exceptions\LoginException,
\LOG_ERR, true);
} }
$SASL = \SnappyMail\SASL::factory($type); $SASL = \SnappyMail\SASL::factory($type);
@ -173,17 +168,11 @@ class SieveClient extends \MailSo\Net\NetClient
catch (\MailSo\Sieve\Exceptions\NegativeResponseException $oException) catch (\MailSo\Sieve\Exceptions\NegativeResponseException $oException)
{ {
$this->writeLogException( $this->writeLogException(
new \MailSo\Sieve\Exceptions\LoginBadCredentialsException( new \MailSo\Sieve\Exceptions\LoginBadCredentialsException($oException->GetResponses(), '', 0, $oException),
$oException->GetResponses(), '', 0, $oException), \LOG_ERR);
\LOG_ERR, true);
} }
if (!$bAuth) $bAuth || $this->writeLogException(new \MailSo\Sieve\Exceptions\LoginBadMethodException, \LOG_ERR);
{
$this->writeLogException(
new \MailSo\Sieve\Exceptions\LoginBadMethodException,
\LOG_ERR, true);
}
$this->bIsLoggined = true; $this->bIsLoggined = true;
@ -197,8 +186,7 @@ class SieveClient extends \MailSo\Net\NetClient
*/ */
public function Logout() : void public function Logout() : void
{ {
if ($this->bIsLoggined) if ($this->bIsLoggined) {
{
$this->sendRequestWithCheck('LOGOUT'); $this->sendRequestWithCheck('LOGOUT');
$this->bIsLoggined = false; $this->bIsLoggined = false;
} }
@ -214,18 +202,13 @@ class SieveClient extends \MailSo\Net\NetClient
$this->sendRequest('LISTSCRIPTS'); $this->sendRequest('LISTSCRIPTS');
$aResponse = $this->parseResponse(); $aResponse = $this->parseResponse();
$this->validateResponse($aResponse); $this->validateResponse($aResponse);
$aResult = array(); $aResult = array();
foreach ($aResponse as $sLine) foreach ($aResponse as $sLine) {
{
$aTokens = $this->parseLine($sLine); $aTokens = $this->parseLine($sLine);
if (!$aTokens) if ($aTokens) {
{
continue;
}
$aResult[$aTokens[0]] = 'ACTIVE' === substr($sLine, -6); $aResult[$aTokens[0]] = 'ACTIVE' === substr($sLine, -6);
} }
}
return $aResult; return $aResult;
} }
@ -269,15 +252,12 @@ class SieveClient extends \MailSo\Net\NetClient
$this->validateResponse($aResponse); $this->validateResponse($aResponse);
$sScript = ''; $sScript = '';
if (\count($aResponse)) if (\count($aResponse)) {
{ if ('{' === $aResponse[0][0]) {
if ('{' === $aResponse[0][0])
{
\array_shift($aResponse); \array_shift($aResponse);
} }
if (\in_array(\substr($aResponse[\count($aResponse) - 1], 0, 2), array('OK', 'NO'))) if (\in_array(\substr($aResponse[\count($aResponse) - 1], 0, 2), array('OK', 'NO'))) {
{
\array_pop($aResponse); \array_pop($aResponse);
} }
@ -351,39 +331,9 @@ class SieveClient extends \MailSo\Net\NetClient
return $this; return $this;
} }
/**
* @throws \MailSo\RuntimeException
* @throws \MailSo\Net\Exceptions\*
* @throws \MailSo\Sieve\Exceptions\*
*/
public function GetActiveScriptName() : string
{
$aList = $this->ListScripts();
foreach ($aList as $sName => $bIsActive)
{
if ($bIsActive)
{
return $sName;
}
}
return '';
}
/**
* @throws \MailSo\RuntimeException
* @throws \MailSo\Net\Exceptions\*
* @throws \MailSo\Sieve\Exceptions\*
*/
public function IsActiveScript(string $sScriptName) : bool
{
return $sScriptName === $this->GetActiveScriptName();
}
private function parseLine(string $sLine) : ?array private function parseLine(string $sLine) : ?array
{ {
if (false === $sLine || null === $sLine || \in_array(\substr($sLine, 0, 2), array('OK', 'NO'))) if (false === $sLine || null === $sLine || \in_array(\substr($sLine, 0, 2), array('OK', 'NO'))) {
{
return null; return null;
} }
@ -391,16 +341,11 @@ class SieveClient extends \MailSo\Net\NetClient
$iIndex = 0; $iIndex = 0;
$aResult = array(); $aResult = array();
for ($iPos = 0; $iPos < \strlen($sLine); $iPos++) for ($iPos = 0; $iPos < \strlen($sLine); ++$iPos) {
{ if ('"' === $sLine[$iPos] && '\\' !== $sLine[$iPos]) {
if ('"' === $sLine[$iPos] && '\\' !== $sLine[$iPos]) if (-1 === $iStart) {
{
if (-1 === $iStart)
{
$iStart = $iPos; $iStart = $iPos;
} } else {
else
{
$aResult[$iIndex++] = \substr($sLine, $iStart + 1, $iPos - $iStart - 1); $aResult[$iIndex++] = \substr($sLine, $iStart + 1, $iPos - $iStart - 1);
$iStart = -1; $iStart = -1;
} }
@ -417,8 +362,7 @@ class SieveClient extends \MailSo\Net\NetClient
*/ */
private function parseStartupResponse(array $aResponse) : void private function parseStartupResponse(array $aResponse) : void
{ {
foreach ($aResponse as $sLine) foreach ($aResponse as $sLine) {
{
$aTokens = $this->parseLine($sLine); $aTokens = $this->parseLine($sLine);
if (false === $aTokens || !isset($aTokens[0]) || if (false === $aTokens || !isset($aTokens[0]) ||
@ -430,8 +374,7 @@ class SieveClient extends \MailSo\Net\NetClient
$sToken = \strtoupper($aTokens[0]); $sToken = \strtoupper($aTokens[0]);
$this->aCapa[$sToken] = isset($aTokens[1]) ? $aTokens[1] : ''; $this->aCapa[$sToken] = isset($aTokens[1]) ? $aTokens[1] : '';
if (isset($aTokens[1])) if (isset($aTokens[1])) {
{
switch ($sToken) { switch ($sToken) {
case 'SASL': case 'SASL':
$this->aAuth = \explode(' ', \strtoupper($aTokens[1])); $this->aAuth = \explode(' ', \strtoupper($aTokens[1]));
@ -451,11 +394,8 @@ class SieveClient extends \MailSo\Net\NetClient
*/ */
private function sendRequest(string $sRequest) : void private function sendRequest(string $sRequest) : void
{ {
if (!\strlen(\trim($sRequest))) if (!\strlen(\trim($sRequest))) {
{ $this->writeLogException(new \InvalidArgumentException, \LOG_ERR);
$this->writeLogException(
new \InvalidArgumentException,
\LOG_ERR, true);
} }
$this->IsConnected(true); $this->IsConnected(true);
@ -474,52 +414,34 @@ class SieveClient extends \MailSo\Net\NetClient
$this->validateResponse($this->parseResponse()); $this->validateResponse($this->parseResponse());
} }
private function convertEndOfLine(string $sLine) : string
{
$sLine = \trim($sLine);
if ('}' === \substr($sLine, -1))
{
$iPos = \strrpos($sLine, '{');
if (false !== $iPos)
{
$sSunLine = \substr($sLine, $iPos + 1, -1);
if (\is_numeric($sSunLine) && 0 < (int) $sSunLine)
{
$iLen = (int) $sSunLine;
$this->getNextBuffer($iLen, true);
if (\strlen($this->sResponseBuffer) === $iLen)
{
$sLine = \trim(\substr_replace($sLine, $this->sResponseBuffer, $iPos));
}
}
}
}
return $sLine;
}
private function parseResponse() : array private function parseResponse() : array
{ {
$aResult = array(); $aResult = array();
do do
{ {
$this->getNextBuffer(); $this->getNextBuffer();
$sLine = $this->sResponseBuffer; $sLine = $this->sResponseBuffer;
if (false === $sLine) if (false === $sLine) {
{
break; break;
} }
else if (\in_array(\substr($sLine, 0, 2), array('OK', 'NO'))) $bEnd = \in_array(\substr($sLine, 0, 2), array('OK', 'NO'));
{ // convertEndOfLine
$aResult[] = $this->convertEndOfLine($sLine); $sLine = \trim($sLine);
break; if ('}' === \substr($sLine, -1)) {
$iPos = \strrpos($sLine, '{');
if (false !== $iPos) {
$iLen = \intval(\substr($sLine, $iPos + 1, -1));
if (0 < $iLen) {
$this->getNextBuffer($iLen);
if (\strlen($this->sResponseBuffer) === $iLen) {
$sLine = \trim(\substr_replace($sLine, $this->sResponseBuffer, $iPos));
} }
else }
{ }
$aResult[] = $this->convertEndOfLine($sLine); }
$aResult[] = $sLine;
if ($bEnd) {
break;
} }
} }
while (true); while (true);
@ -532,12 +454,8 @@ class SieveClient extends \MailSo\Net\NetClient
*/ */
private function validateResponse(array $aResponse) private function validateResponse(array $aResponse)
{ {
if (!$aResponse || if (!$aResponse || 'OK' !== \substr($aResponse[\count($aResponse) - 1], 0, 2)) {
'OK' !== \substr($aResponse[\count($aResponse) - 1], 0, 2)) $this->writeLogException(new \MailSo\Sieve\Exceptions\NegativeResponseException($aResponse), \LOG_WARNING);
{
$this->writeLogException(
new \MailSo\Sieve\Exceptions\NegativeResponseException($aResponse),
\LOG_WARNING, true);
} }
} }

View file

@ -101,7 +101,7 @@ class SmtpClient extends \MailSo\Net\NetClient
} else { } else {
$this->writeLogException( $this->writeLogException(
new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('STARTTLS is not supported'), new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('STARTTLS is not supported'),
\LOG_ERR, true); \LOG_ERR);
} }
} }
@ -129,9 +129,7 @@ class SmtpClient extends \MailSo\Net\NetClient
return $this->Login($oSettings); return $this->Login($oSettings);
} }
\trigger_error("SMTP {$this->GetConnectedHost()} no supported AUTH options. Disable login"); \trigger_error("SMTP {$this->GetConnectedHost()} no supported AUTH options. Disable login");
$this->writeLogException( $this->writeLogException(new \MailSo\Smtp\Exceptions\LoginBadMethodException);
new \MailSo\Smtp\Exceptions\LoginBadMethodException,
\LOG_NOTICE, true);
} }
$SASL = \SnappyMail\SASL::factory($type); $SASL = \SnappyMail\SASL::factory($type);
@ -145,9 +143,8 @@ class SmtpClient extends \MailSo\Net\NetClient
catch (\MailSo\Smtp\Exceptions\NegativeResponseException $oException) catch (\MailSo\Smtp\Exceptions\NegativeResponseException $oException)
{ {
$this->writeLogException( $this->writeLogException(
new \MailSo\Smtp\Exceptions\LoginBadMethodException( new \MailSo\Smtp\Exceptions\LoginBadMethodException($oException->GetResponses(), $oException->getMessage(), 0, $oException)
$oException->GetResponses(), $oException->getMessage(), 0, $oException), );
\LOG_NOTICE, true);
} }
try try
@ -178,10 +175,7 @@ class SmtpClient extends \MailSo\Net\NetClient
// RFC 2195 // RFC 2195
case 'CRAM-MD5': case 'CRAM-MD5':
if (empty($sResult)) { if (empty($sResult)) {
$this->writeLogException( $this->writeLogException(new \MailSo\Smtp\Exceptions\NegativeResponseException);
new \MailSo\Smtp\Exceptions\NegativeResponseException,
\LOG_NOTICE, true
);
} }
$this->sendRequestWithCheck($SASL->authenticate($sLogin, $sPassword, $sResult), 235, '', true); $this->sendRequestWithCheck($SASL->authenticate($sLogin, $sPassword, $sResult), 235, '', true);
break; break;
@ -190,9 +184,8 @@ class SmtpClient extends \MailSo\Net\NetClient
catch (\MailSo\Smtp\Exceptions\NegativeResponseException $oException) catch (\MailSo\Smtp\Exceptions\NegativeResponseException $oException)
{ {
$this->writeLogException( $this->writeLogException(
new \MailSo\Smtp\Exceptions\LoginBadCredentialsException( new \MailSo\Smtp\Exceptions\LoginBadCredentialsException($oException->GetResponses(), $oException->getMessage(), 0, $oException)
$oException->GetResponses(), $oException->getMessage(), 0, $oException), );
\LOG_NOTICE, true);
} }
return $this; return $this;
@ -233,9 +226,7 @@ class SmtpClient extends \MailSo\Net\NetClient
public function Rcpt(string $sTo, bool $bDsn = false) : self public function Rcpt(string $sTo, bool $bDsn = false) : self
{ {
if (!$this->bMail) { if (!$this->bMail) {
$this->writeLogException( $this->writeLogException(new \MailSo\RuntimeException('No sender reverse path has been supplied'), \LOG_ERR);
new \MailSo\RuntimeException('No sender reverse path has been supplied'),
\LOG_ERR, true);
} }
$sTo = \MailSo\Base\Utils::IdnToAscii(\MailSo\Base\Utils::Trim($sTo), true); $sTo = \MailSo\Base\Utils::IdnToAscii(\MailSo\Base\Utils::Trim($sTo), true);
@ -300,9 +291,7 @@ class SmtpClient extends \MailSo\Net\NetClient
} }
if (!$this->bRcpt) { if (!$this->bRcpt) {
$this->writeLogException( $this->writeLogException(new \MailSo\RuntimeException('No recipient forward path has been supplied'), \LOG_ERR);
new \MailSo\RuntimeException('No recipient forward path has been supplied'),
\LOG_ERR, true);
} }
$this->sendRequestWithCheck('DATA', 354); $this->sendRequestWithCheck('DATA', 354);
@ -315,9 +304,7 @@ class SmtpClient extends \MailSo\Net\NetClient
$sBuffer = \fgets($rDataStream); $sBuffer = \fgets($rDataStream);
if (false === $sBuffer) { if (false === $sBuffer) {
if (!\feof($rDataStream)) { if (!\feof($rDataStream)) {
$this->writeLogException( $this->writeLogException(new \MailSo\RuntimeException('Cannot read input resource'), \LOG_ERR);
new \MailSo\RuntimeException('Cannot read input resource'),
\LOG_ERR, true);
} }
break; break;
} }
@ -397,7 +384,7 @@ class SmtpClient extends \MailSo\Net\NetClient
{ {
$sCommand = \trim($sCommand); $sCommand = \trim($sCommand);
if (!\strlen($sCommand)) { if (!\strlen($sCommand)) {
$this->writeLogException(new \InvalidArgumentException, \LOG_ERR, true); $this->writeLogException(new \InvalidArgumentException, \LOG_ERR);
} }
$this->IsConnected(true); $this->IsConnected(true);
@ -518,14 +505,14 @@ class SmtpClient extends \MailSo\Net\NetClient
new Exceptions\NegativeResponseException($this->aResults, new Exceptions\NegativeResponseException($this->aResults,
('' === $sErrorPrefix ? '' : $sErrorPrefix.': ').\trim( ('' === $sErrorPrefix ? '' : $sErrorPrefix.': ').\trim(
(\count($this->aResults) ? \implode("\r\n", $this->aResults)."\r\n" : ''). (\count($this->aResults) ? \implode("\r\n", $this->aResults)."\r\n" : '').
$this->sResponseBuffer)), \LOG_ERR, true); $this->sResponseBuffer)), \LOG_ERR);
} }
} else { } else {
$this->writeLogException( $this->writeLogException(
new Exceptions\ResponseException($this->aResults, new Exceptions\ResponseException($this->aResults,
('' === $sErrorPrefix ? '' : $sErrorPrefix.': ').\trim( ('' === $sErrorPrefix ? '' : $sErrorPrefix.': ').\trim(
(\count($this->aResults) ? \implode("\r\n", $this->aResults)."\r\n" : ''). (\count($this->aResults) ? \implode("\r\n", $this->aResults)."\r\n" : '').
$this->sResponseBuffer)), \LOG_ERR, true); $this->sResponseBuffer)), \LOG_ERR);
} }
$this->aResults[] = $this->sResponseBuffer; $this->aResults[] = $this->sResponseBuffer;