115 lines
2.4 KiB
Go
115 lines
2.4 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"
|
|
)
|
|
|
|
// GetIps ...
|
|
func GetIps(ctx *context.Context, config *config.Config, limit int) (apimailboxes []*api.IP, err error) {
|
|
var ips []IP
|
|
err = config.Db.Limit(limit).Find(&ips)
|
|
for _, ml := range ips {
|
|
apimailboxes = append(apimailboxes, ml.APIFormat())
|
|
}
|
|
return
|
|
}
|
|
|
|
// GetIp ...
|
|
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, numfail int64, err error) {
|
|
for _, ip := range *ips {
|
|
num, err := cfg.Db.Insert(ip)
|
|
if err != nil {
|
|
numfail++
|
|
continue
|
|
}
|
|
numinserts += num
|
|
}
|
|
return
|
|
}
|
|
|
|
func ScanIP(cfg *config.Config) (err error) {
|
|
for {
|
|
var orphans = []IP{}
|
|
cfg.Db.Where("rdns IS NULL").Asc("ip").Find(&orphans)
|
|
if len(orphans) > 0 {
|
|
for _, i := range orphans {
|
|
reverse, _ := i.UpdateRDNS()
|
|
if reverse == "" {
|
|
fmt.Printf("Set \"none\" rdns to IP %s\n", i.IP)
|
|
i.Rdns.String = "none"
|
|
} else {
|
|
fmt.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)
|
|
}
|
|
}
|
|
}
|
|
|
|
// APIFormat returns a JSON formatted object of IP
|
|
func (admin *IP) APIFormat() *api.IP {
|
|
if admin == nil {
|
|
return nil
|
|
}
|
|
return &api.IP{
|
|
ID: admin.ID,
|
|
IP: admin.IP,
|
|
Rdns: admin.Rdns.String,
|
|
Src: admin.Src,
|
|
}
|
|
}
|
|
|
|
// IP describe IP objects
|
|
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:"-"`
|
|
}
|