Skip to content

Commit

Permalink
Merge pull request #36 from ipfs/filter-ip6
Browse files Browse the repository at this point in the history
Fix address filtering for /ip6, add tests
  • Loading branch information
whyrusleeping committed Apr 13, 2016
2 parents 37bff87 + 2b226b9 commit bd60092
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 6 deletions.
15 changes: 10 additions & 5 deletions p2p/net/filter/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package filter

import (
"net"
"strings"
"sync"

manet "gx/ipfs/QmYVqhVfbK4BKvbW88Lhm26b3ud14sTBvcm1H7uWUx1Fkp/go-multiaddr-net"
Expand All @@ -27,18 +26,24 @@ func (fs *Filters) AddDialFilter(f *net.IPNet) {
}

func (f *Filters) AddrBlocked(a ma.Multiaddr) bool {
_, addr, err := manet.DialArgs(a)
maddr := ma.Split(a)
if len(maddr) == 0 {
return false
}
netaddr, err := manet.ToNetAddr(maddr[0])
if err != nil {
// if we cant parse it, its probably not blocked
return false
}
netip := net.ParseIP(netaddr.String())
if netip == nil {
return false
}

ipstr := strings.Split(addr, ":")[0]
ip := net.ParseIP(ipstr)
f.mu.RLock()
defer f.mu.RUnlock()
for _, ft := range f.filters {
if ft.Contains(ip) {
if ft.Contains(netip) {
return true
}
}
Expand Down
51 changes: 51 additions & 0 deletions p2p/net/filter/filter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package filter

import (
"net"
"testing"

ma "gx/ipfs/QmcobAGsCjYt5DXoq9et9L8yR8er7o7Cu3DTvpaq12jYSz/go-multiaddr"
)

func TestFilter(t *testing.T) {
f := NewFilters()
for _, cidr := range []string{
"1.2.3.0/24",
"4.3.2.1/32",
"fd00::/8",
"fc00::1/128",
} {
_, ipnet, _ := net.ParseCIDR(cidr)
f.AddDialFilter(ipnet)
}

for _, blocked := range []string{
"/ip4/1.2.3.4/tcp/123",
"/ip4/4.3.2.1/udp/123",
"/ip6/fd00::2/tcp/321",
"/ip6/fc00::1/udp/321",
} {
maddr, err := ma.NewMultiaddr(blocked)
if err != nil {
t.Error(err)
}
if !f.AddrBlocked(maddr) {
t.Fatalf("expected %s to be blocked", blocked)
}
}

for _, notBlocked := range []string{
"/ip4/1.2.4.1/tcp/123",
"/ip4/4.3.2.2/udp/123",
"/ip6/fe00::1/tcp/321",
"/ip6/fc00::2/udp/321",
} {
maddr, err := ma.NewMultiaddr(notBlocked)
if err != nil {
t.Error(err)
}
if f.AddrBlocked(maddr) {
t.Fatalf("expected %s to not be blocked", notBlocked)
}
}
}
2 changes: 1 addition & 1 deletion p2p/net/swarm/swarm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ func TestAddrBlocking(t *testing.T) {
swarms := makeSwarms(ctx, t, 2)

swarms[0].SetConnHandler(func(conn *Conn) {
t.Fatal("no connections should happen!")
t.Fatalf("no connections should happen! -- %s", conn)
})

_, block, err := net.ParseCIDR("127.0.0.1/8")
Expand Down

0 comments on commit bd60092

Please sign in to comment.