MinIPAM/minipam.go

218 lines
5.3 KiB
Go
Raw Normal View History

2024-01-24 17:29:52 +01:00
package main
import (
"crypto/tls"
_ "embed"
"encoding/json"
2024-10-06 14:22:39 +02:00
"github.com/digineo/go-ping"
2024-01-24 17:29:52 +01:00
"github.com/gorilla/mux"
"gopkg.in/yaml.v3"
"log"
"net"
"net/http"
"net/netip"
"os"
"sync"
2024-01-24 17:29:52 +01:00
"time"
)
type ConfigT struct {
BindAddress string `yaml:"bind_address"`
ScanSubnets []string `yaml:"scan_subnets"`
DelayBetweenScans time.Duration `yaml:"delay_between_scans"`
ExcludeSpecialAddresses bool `yaml:"exclude_special_addresses"`
PersistenceLocation string `yaml:"persistence_location"`
UseTLS bool `yaml:"use_tls"`
TLSKeyFile string `yaml:"tls_key_file"`
TLSCertFile string `yaml:"tls_cert_file"`
}
type HostT struct {
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
Online bool `json:"online"`
RevDNS string `json:"rev_dns"`
}
type SubnetT struct {
Hosts map[string]HostT `json:"hosts"`
TotalAddresses int `json:"total_addresses"`
UsedAddresses int `json:"used_addresses"`
2024-01-24 18:39:01 +01:00
HostList []string `json:"host_list"` //I _REALLY_ didn't want to calculate this in javascript
2024-01-24 17:29:52 +01:00
}
type PersistenceT struct {
Subnets map[string]SubnetT
}
var conf ConfigT
var p PersistenceT
//go:embed index.html
var indexhtml []byte
2024-10-06 14:22:39 +02:00
var pinger *ping.Pinger
2024-01-24 17:29:52 +01:00
func main() {
if len(os.Args) < 2 {
log.Fatalf("Usage: %s <config location>", os.Args[0])
}
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatalf("Failed to open %s: %s", os.Args[1], err)
}
err = yaml.NewDecoder(f).Decode(&conf)
if err != nil {
log.Fatalf("Failed to load config file: %s", err)
}
_ = f.Close()
f, err = os.Open(conf.PersistenceLocation)
if err != nil {
log.Printf("Failed to open persistence file: %s. Will try to create new one later.", err)
} else {
err = json.NewDecoder(f).Decode(&p)
_ = f.Close()
if err != nil {
log.Fatalf("Failed to decode persistence file: %s", err)
}
}
if p.Subnets == nil {
p.Subnets = make(map[string]SubnetT)
}
2024-10-06 14:22:39 +02:00
pinger, err = ping.New("0.0.0.0", "")
if err != nil {
log.Fatalf("Failed to create pinger: %s", err)
}
2024-01-24 17:29:52 +01:00
go scanner()
r := mux.NewRouter()
r.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write(indexhtml)
}).Methods("GET")
r.HandleFunc("/data", func(writer http.ResponseWriter, request *http.Request) {
_ = json.NewEncoder(writer).Encode(&p)
}).Methods("GET")
server := &http.Server{
Addr: conf.BindAddress,
Handler: r,
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS13,
},
}
if conf.UseTLS {
err = server.ListenAndServeTLS(conf.TLSCertFile, conf.TLSKeyFile)
} else {
err = server.ListenAndServe()
}
if err != nil {
log.Fatalf("%s", err)
}
}
2024-10-06 14:22:39 +02:00
func PingFunc(addr net.IPAddr) bool {
_, err := pinger.PingAttempts(&addr, 200*time.Millisecond, 2)
return err == nil
2024-01-24 17:29:52 +01:00
}
func scanner() {
for {
var wg sync.WaitGroup
var mutex sync.Mutex
for _, subnet := range conf.ScanSubnets {
go func(v string) {
wg.Add(1)
defer wg.Done()
persistenceSubnet, ok := p.Subnets[v]
if !ok {
persistenceSubnet = SubnetT{}
persistenceSubnet.Hosts = make(map[string]HostT)
2024-01-24 17:29:52 +01:00
}
log.Printf("Scanning subnet %s", v)
prefix, err := netip.ParsePrefix(v)
if err != nil {
log.Printf("Error: %s", err)
return
2024-01-24 17:29:52 +01:00
}
prefix = prefix.Masked()
addr := prefix.Addr()
if conf.ExcludeSpecialAddresses {
addr = addr.Next()
}
persistenceSubnet.TotalAddresses = 0
persistenceSubnet.UsedAddresses = 0
persistenceSubnet.HostList = make([]string, 0)
for {
if !prefix.Contains(addr) {
break
2024-01-24 17:29:52 +01:00
}
//skip broadcast address
if conf.ExcludeSpecialAddresses && !prefix.Contains(addr.Next()) {
break
}
persistenceSubnet.TotalAddresses++
//fmt.Println(addr.String())
persistenceSubnet.HostList = append(persistenceSubnet.HostList, addr.String())
2024-10-06 14:22:39 +02:00
x := net.IPAddr{IP: net.ParseIP(addr.String())}
pingstate := PingFunc(x)
host, ok := persistenceSubnet.Hosts[addr.String()]
if pingstate {
persistenceSubnet.UsedAddresses++
//log.Printf("%s is up", addr.String())
rdnsString := ""
rdns, err := net.LookupAddr(addr.String())
if err == nil {
if len(rdns) > 0 {
rdnsString = rdns[0]
}
}
if !ok {
persistenceSubnet.Hosts[addr.String()] = HostT{
FirstSeen: time.Now(),
LastSeen: time.Now(),
Online: true,
RevDNS: rdnsString,
}
} else {
host.LastSeen = time.Now()
host.Online = true
host.RevDNS = rdnsString
persistenceSubnet.Hosts[addr.String()] = host
2024-01-24 17:29:52 +01:00
}
} else if ok {
host.Online = false
2024-01-24 17:29:52 +01:00
persistenceSubnet.Hosts[addr.String()] = host
persistenceSubnet.UsedAddresses++
2024-01-24 17:29:52 +01:00
}
addr = addr.Next()
2024-01-24 17:29:52 +01:00
}
mutex.Lock()
p.Subnets[v] = persistenceSubnet
mutex.Unlock()
log.Printf("Scan of %s finished", v)
}(subnet)
2024-01-24 17:29:52 +01:00
}
wg.Wait()
log.Printf("All scans finished")
2024-01-24 17:29:52 +01:00
f, err := os.Create(conf.PersistenceLocation)
if err != nil {
log.Printf("Failed to save persistence: %s", err)
} else {
err := json.NewEncoder(f).Encode(&p)
_ = f.Close()
if err != nil {
log.Printf("Failed to encode persistence: %s", err)
}
}
time.Sleep(conf.DelayBetweenScans)
}
}