ipbl/src/models/ip.go
2022-03-10 19:56:03 +01:00

124 lines
2.9 KiB
Go

package models
import (
"context"
"database/sql"
"fmt"
"log"
"net"
"time"
"git.paulbsd.com/paulbsd/ipbl/src/api"
"git.paulbsd.com/paulbsd/ipbl/src/config"
)
var lastday = time.Now().Add(-(time.Hour * 24))
func GetIPs(ctx *context.Context, config *config.Config, limit int) (apimailboxes []*api.IP, err error) {
var ips []IP
err = config.Db.Limit(limit).Desc("created").Find(&ips)
for _, ml := range ips {
apimailboxes = append(apimailboxes, ml.APIFormat())
}
return
}
func GetIPsLast(ctx *context.Context, config *config.Config, interval string) (apimailboxes []*api.IP, err error) {
var ips []IP
err = config.Db.Where(fmt.Sprintf("updated >= (now()-'%s'::interval)", interval)).GroupBy("ip").Find(&ips)
for _, ml := range ips {
apimailboxes = append(apimailboxes, ml.APIFormat())
}
return
}
func GetIP(ctx *context.Context, config *config.Config, ipquery interface{}) (apiip *api.IP, err error) {
var ip IP
has, err := config.Db.Where("ip = ?", ipquery).Get(&ip)
if !has {
err = fmt.Errorf("not found")
return nil, err
}
if err != nil {
return
}
apiip = ip.APIFormat()
return
}
func (i *IP) UpdateRDNS() (result string, err error) {
res, err := net.LookupAddr(i.IP)
if err != nil {
result = ""
} else {
result = res[0]
}
return
}
func (i *IP) InsertIP(cfg *config.Config) (num int64, err error) {
num, err = cfg.Db.Insert(i)
return
}
func InsertIPBulk(cfg *config.Config, ips *[]IP) (numinserts int64, numupdates int64, numfail int64, err error) {
var iplist []string
for _, ip := range *ips {
iplist = append(iplist, ip.IP)
}
var searchips []IP
cfg.Db.In("ip", iplist).Find(&searchips)
var toupdateips []string
for _, ip := range searchips {
toupdateips = append(toupdateips, ip.IP)
}
numupdates, _ = cfg.Db.In("ip", toupdateips).Cols("updated").Update(&IP{})
var toinsertip, _ = differ(*ips, searchips)
numinserts, err = cfg.Db.Insert(toinsertip)
return
}
func ScanIP(cfg *config.Config) (err error) {
for {
orphans := []IP{}
if cfg.Db.Where("rdns IS NULL").Asc("ip").Find(&orphans); len(orphans) > 0 {
for _, i := range orphans {
reverse, _ := i.UpdateRDNS()
log.Printf("%s -> \"%s\"\n", i.IP, reverse)
i.Rdns.String = reverse
i.Rdns.Valid = true
_, err = cfg.Db.ID(i.ID).Cols("rdns").Update(&i)
if err != nil {
log.Println(err)
}
}
} else {
time.Sleep(60 * time.Second)
}
}
}
func (ip *IP) APIFormat() *api.IP {
if ip == nil {
return nil
}
return &api.IP{
IP: ip.IP,
Rdns: ip.Rdns.String,
Src: ip.Src,
}
}
type IP struct {
ID int `xorm:"pk autoincr" json:"-"`
IP string `xorm:"text notnull unique(ipsrc)" json:"ip"`
Rdns sql.NullString `xorm:"text default" json:"rdns"`
Src string `xorm:"text notnull unique(ipsrc)" json:"src"`
Created time.Time `xorm:"created notnull" json:"-"`
Updated time.Time `xorm:"updated notnull" json:"-"`
}