From 550b32e1e7eda89855cefdb0a4b0b9ad1f38a2a5 Mon Sep 17 00:00:00 2001 From: Chris Boden Date: Sun, 29 Apr 2012 13:20:26 -0400 Subject: [PATCH] IpBlackList Fixed bug where onClose was propagated if onOpen wasn't Filter out ports from IP4 addresses --- .../Component/Server/IpBlackListComponent.php | 28 +++++++++++++++++-- .../Server/IpBlackListComponentTest.php | 16 +++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/Ratchet/Component/Server/IpBlackListComponent.php b/src/Ratchet/Component/Server/IpBlackListComponent.php index 551d204..1989480 100644 --- a/src/Ratchet/Component/Server/IpBlackListComponent.php +++ b/src/Ratchet/Component/Server/IpBlackListComponent.php @@ -34,11 +34,19 @@ class IpBlackListComponent implements MessageComponentInterface { * @return IpBlackList */ public function unblockAddress($ip) { - unset($this->_blacklist[$ip]); + unset($this->_blacklist[$this->filterAddress($ip)]); return $this; } + /** + * @param string + * @return bool + */ + public function isBlocked($address) { + return (isset($this->_blacklist[$this->filterAddress($address)])); + } + /** * Get an array of all the addresses blocked * @return array @@ -47,11 +55,23 @@ class IpBlackListComponent implements MessageComponentInterface { return array_keys($this->_blacklist); } + /** + * @param string + * @return string + */ + public function filterAddress($address) { + if (strstr($address, ':') && substr_count($address, '.') == 3) { + list($address, $port) = explode(':', $address); + } + + return $address; + } + /** * {@inheritdoc} */ function onOpen(ConnectionInterface $conn) { - if (isset($this->_blacklist[$conn->remoteAddress])) { + if ($this->isBlocked($conn->remoteAddress)) { return new CloseConnection($conn); } @@ -69,6 +89,10 @@ class IpBlackListComponent implements MessageComponentInterface { * {@inheritdoc} */ function onClose(ConnectionInterface $conn) { + if ($this->isBlocked($conn->remoteAddress)) { + return null; + } + return $this->_decorating->onClose($conn); } diff --git a/tests/Ratchet/Tests/Component/Server/IpBlackListComponentTest.php b/tests/Ratchet/Tests/Component/Server/IpBlackListComponentTest.php index 88f4dc4..874bc5b 100644 --- a/tests/Ratchet/Tests/Component/Server/IpBlackListComponentTest.php +++ b/tests/Ratchet/Tests/Component/Server/IpBlackListComponentTest.php @@ -68,4 +68,20 @@ class IpBlackListComponentTest extends \PHPUnit_Framework_TestCase { $this->assertEquals($conn2, $this->_mock->last['onError'][0]); $this->assertEquals($e, $this->_mock->last['onError'][1]); } + + public function addressProvider() { + return array( + array('127.0.0.1', '127.0.0.1') + , array('localhost', 'localhost') + , array('fe80::1%lo0', 'fe80::1%lo0') + , array('127.0.0.1', '127.0.0.1:6392') + ); + } + + /** + * @dataProvider addressProvider + */ + public function testFilterAddress($expected, $input) { + $this->assertEquals($expected, $this->_comp->filterAddress($input)); + } } \ No newline at end of file