Files
EdgeCommon/pkg/iplibrary/default_ip_library.go

118 lines
2.1 KiB
Go
Raw Normal View History

// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package iplibrary
import (
"bytes"
"compress/gzip"
_ "embed"
"net"
2023-03-30 20:02:46 +08:00
"sync"
)
//go:embed internal-ip-library.db
var ipLibraryData []byte
var defaultLibrary = NewIPLibrary()
2023-03-30 20:02:46 +08:00
var commonLibrary *IPLibrary
var libraryLocker = &sync.Mutex{} // 为了保持加载顺序性
func DefaultIPLibraryData() []byte {
return ipLibraryData
}
2023-03-30 20:02:46 +08:00
// InitDefault 加载默认的IP库
func InitDefault() error {
2023-03-30 20:02:46 +08:00
libraryLocker.Lock()
defer libraryLocker.Unlock()
if commonLibrary != nil {
defaultLibrary = commonLibrary
return nil
}
var library = NewIPLibrary()
err := library.InitFromData(ipLibraryData, "")
if err != nil {
return err
}
commonLibrary = library
defaultLibrary = commonLibrary
return nil
}
2023-03-30 20:02:46 +08:00
// Lookup 查询IP信息
func Lookup(ip net.IP) *QueryResult {
return defaultLibrary.Lookup(ip)
}
2023-03-30 20:02:46 +08:00
// LookupIP 查询IP信息
func LookupIP(ip string) *QueryResult {
return defaultLibrary.LookupIP(ip)
}
type IPLibrary struct {
reader *Reader
}
func NewIPLibrary() *IPLibrary {
return &IPLibrary{}
}
func NewIPLibraryWithReader(reader *Reader) *IPLibrary {
return &IPLibrary{reader: reader}
}
2023-03-30 20:02:46 +08:00
func (this *IPLibrary) InitFromData(data []byte, password string) error {
if len(data) == 0 || this.reader != nil {
2022-08-21 23:09:25 +08:00
return nil
}
2023-03-30 20:02:46 +08:00
if len(password) > 0 {
srcData, err := NewEncrypt().Decode(data, password)
if err != nil {
return err
}
data = srcData
}
var reader = bytes.NewReader(data)
gzipReader, err := gzip.NewReader(reader)
if err != nil {
return err
}
defer func() {
_ = gzipReader.Close()
}()
libReader, err := NewReader(gzipReader)
if err != nil {
return err
}
this.reader = libReader
2022-08-21 23:09:25 +08:00
return nil
}
func (this *IPLibrary) Lookup(ip net.IP) *QueryResult {
if this.reader == nil {
return &QueryResult{}
}
var result = this.reader.Lookup(ip)
if result == nil {
result = &QueryResult{}
}
return result
}
func (this *IPLibrary) LookupIP(ip string) *QueryResult {
if this.reader == nil {
return &QueryResult{}
}
return this.Lookup(net.ParseIP(ip))
}