overflow_discovery/net/zone.go

115 lines
2.0 KiB
Go
Raw Normal View History

2017-10-20 09:09:07 +00:00
package net
2017-10-26 12:55:55 +00:00
import (
"net"
"regexp"
"strings"
2017-10-20 09:09:07 +00:00
2017-10-26 12:55:55 +00:00
"git.loafle.net/overflow/overflow_discovery/net/model"
)
type ZoneScanner interface {
}
type zoneScan struct {
config *DiscoveryZoneConfig
endChan chan bool
zoneChan chan *model.DiscoveryZone
logChan chan error
}
func newZoneScan(dzc *DiscoveryZoneConfig) *zoneScan {
zs := &zoneScan{
config: dzc,
endChan: make(chan bool),
zoneChan: make(chan *model.DiscoveryZone, 4),
logChan: make(chan error, 4),
}
return zs
}
func (zs *zoneScan) Close() {
close(zs.endChan)
close(zs.zoneChan)
close(zs.logChan)
}
func scanZone(zs *zoneScan) {
2017-10-20 09:09:07 +00:00
var err error
var ifaces []net.Interface
var addrs []net.Addr
var ipnet *net.IPNet
var zones []*net.IPNet
2017-10-26 12:55:55 +00:00
// var gwIP net.IP
// var gwIFace string
// if gwIP, gwIFace, err = gateway.DiscoverGateway(); nil != err {
// logChan <- err
// return
// }
2017-10-20 09:09:07 +00:00
if ifaces, err = net.Interfaces(); nil != err {
2017-10-26 12:55:55 +00:00
zs.logChan <- err
2017-10-20 09:09:07 +00:00
return
}
zones = make([]*net.IPNet, 0)
for _, i := range ifaces {
if addrs, err = i.Addrs(); nil != err {
2017-10-26 12:55:55 +00:00
zs.logChan <- err
2017-10-20 09:09:07 +00:00
continue
}
for _, addr := range addrs {
2017-10-20 09:20:13 +00:00
2017-10-20 09:09:07 +00:00
if _, ipnet, err = net.ParseCIDR(addr.String()); nil != err {
2017-10-26 12:55:55 +00:00
zs.logChan <- err
2017-10-20 09:09:07 +00:00
continue
}
2017-10-26 12:55:55 +00:00
if ipnet.IP.IsLoopback() || checkSameZone(zones, ipnet) || checkExclude(zs.config.ExcludePatterns, i.Name) {
2017-10-20 09:09:07 +00:00
continue
}
zones = append(zones, ipnet)
dz := &model.DiscoveryZone{
2017-10-20 09:20:13 +00:00
Network: ipnet.String(),
Iface: i.Name,
Mac: i.HardwareAddr.String(),
IP: strings.Split(addr.String(), "/")[0],
2017-10-20 09:09:07 +00:00
}
2017-10-26 12:55:55 +00:00
zs.zoneChan <- dz
2017-10-20 09:09:07 +00:00
}
}
2017-10-26 12:55:55 +00:00
zs.endChan <- true
}
2017-10-20 09:09:07 +00:00
2017-10-26 12:55:55 +00:00
func checkExclude(ep []string, iface string) bool {
var r *regexp.Regexp
var err error
for _, p := range ep {
if r, err = regexp.Compile(p); nil != err {
return false
}
if r.MatchString(iface) {
return true
}
}
return false
2017-10-20 09:09:07 +00:00
}
func checkSameZone(zones []*net.IPNet, ipnet *net.IPNet) bool {
for _, i := range zones {
if i.Contains(ipnet.IP) {
return true
}
}
return false
}