Skip to content

Commit f6b38d7

Browse files
authored
Merge pull request #76 from clue-labs/invalid-hosts
Ignore invalid lines from hosts file
2 parents d52e7e8 + d7b7123 commit f6b38d7

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/Config/HostsFile.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,12 @@ public function getIpsForHost($name)
103103
if ($parts && array_search($name, $parts) !== false) {
104104
// remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`)
105105
if (strpos($ip, ':') !== false && ($pos = strpos($ip, '%')) !== false) {
106-
$ip= substr($ip, 0, $pos);
106+
$ip = substr($ip, 0, $pos);
107107
}
108108

109-
$ips[] = $ip;
109+
if (@inet_pton($ip) !== false) {
110+
$ips[] = $ip;
111+
}
110112
}
111113
}
112114

@@ -123,6 +125,9 @@ public function getHostsForIp($ip)
123125
{
124126
// check binary representation of IP to avoid string case and short notation
125127
$ip = @inet_pton($ip);
128+
if ($ip === false) {
129+
return array();
130+
}
126131

127132
$names = array();
128133
foreach (preg_split('/\r?\n/', $this->contents) as $line) {

tests/Config/HostsFileTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,14 @@ public function testContainsSingleLocalhostEntry()
4141
$this->assertEquals(array(), $hosts->getIpsForHost('example.com'));
4242
}
4343

44+
public function testNonIpReturnsNothingForInvalidHosts()
45+
{
46+
$hosts = new HostsFile('a b');
47+
48+
$this->assertEquals(array(), $hosts->getIpsForHost('a'));
49+
$this->assertEquals(array(), $hosts->getIpsForHost('b'));
50+
}
51+
4452
public function testIgnoresIpv6ZoneId()
4553
{
4654
$hosts = new HostsFile('fe80::1%lo0 localhost');
@@ -108,6 +116,14 @@ public function testReverseNonIpReturnsNothing()
108116
$this->assertEquals(array(), $hosts->getHostsForIp('127.0.0.1.1'));
109117
}
110118

119+
public function testReverseNonIpReturnsNothingForInvalidHosts()
120+
{
121+
$hosts = new HostsFile('a b');
122+
123+
$this->assertEquals(array(), $hosts->getHostsForIp('a'));
124+
$this->assertEquals(array(), $hosts->getHostsForIp('b'));
125+
}
126+
111127
public function testReverseLookupReturnsLowerCaseHost()
112128
{
113129
$hosts = new HostsFile('127.0.0.1 LocalHost');

0 commit comments

Comments
 (0)