1
0
mirror of https://github.com/zu1k/nali.git synced 2025-01-22 21:29:02 +08:00
nali/pkg/qqwry/qqwry.go

105 lines
2.0 KiB
Go
Raw Normal View History

2020-07-17 09:05:25 +08:00
package qqwry
import (
"encoding/binary"
2021-08-02 12:01:25 +08:00
"errors"
2020-07-17 09:05:25 +08:00
"fmt"
"io"
2020-07-17 09:05:25 +08:00
"log"
"net"
"os"
"github.com/zu1k/nali/pkg/download"
"github.com/zu1k/nali/pkg/wry"
2020-07-17 09:05:25 +08:00
)
var DownloadUrls = []string{
"https://99wry.cf/qqwry.dat",
}
2020-07-17 09:05:25 +08:00
type QQwry struct {
wry.IPDB[uint32]
2020-07-17 09:05:25 +08:00
}
2021-08-02 12:01:25 +08:00
// NewQQwry new database from path
func NewQQwry(filePath string) (*QQwry, error) {
2020-07-18 10:48:41 +08:00
var fileData []byte
2020-07-17 09:05:25 +08:00
_, err := os.Stat(filePath)
if err != nil && os.IsNotExist(err) {
log.Println("文件不存在,尝试从网络获取最新纯真 IP 库")
fileData, err = download.Download(filePath, DownloadUrls...)
2020-07-17 09:05:25 +08:00
if err != nil {
return nil, err
2020-07-17 09:05:25 +08:00
}
} else {
fileBase, err := os.OpenFile(filePath, os.O_RDONLY, 0400)
2020-07-17 09:05:25 +08:00
if err != nil {
return nil, err
2020-07-17 09:05:25 +08:00
}
defer fileBase.Close()
2020-07-17 09:05:25 +08:00
fileData, err = io.ReadAll(fileBase)
2020-07-17 09:05:25 +08:00
if err != nil {
return nil, err
2020-07-17 09:05:25 +08:00
}
}
2022-10-24 09:51:19 +08:00
if !CheckFile(fileData) {
2022-10-20 16:05:02 +08:00
log.Fatalln("纯真 IP 库存在错误,请重新下载")
}
header := fileData[0:8]
start := binary.LittleEndian.Uint32(header[:4])
end := binary.LittleEndian.Uint32(header[4:])
2020-07-17 09:05:25 +08:00
return &QQwry{
IPDB: wry.IPDB[uint32]{
Data: fileData,
OffLen: 3,
IPLen: 4,
IPCnt: (end-start)/7 + 1,
IdxStart: start,
IdxEnd: end,
2020-07-18 09:52:59 +08:00
},
}, nil
2020-07-17 09:05:25 +08:00
}
2021-08-02 12:01:25 +08:00
func (db QQwry) Find(query string, params ...string) (result fmt.Stringer, err error) {
ip := net.ParseIP(query)
if ip == nil {
return nil, errors.New("query should be IPv4")
2020-07-17 09:05:25 +08:00
}
2021-08-02 12:01:25 +08:00
ip4 := ip.To4()
if ip4 == nil {
return nil, errors.New("query should be IPv4")
2021-08-02 12:01:25 +08:00
}
ip4uint := binary.BigEndian.Uint32(ip4)
2020-07-18 09:19:27 +08:00
offset := db.SearchIndexV4(ip4uint)
2020-07-17 09:05:25 +08:00
if offset <= 0 {
return nil, errors.New("query not valid")
2020-07-17 09:05:25 +08:00
}
reader := wry.NewReader(db.Data)
reader.Parse(offset + 4)
return reader.Result.DecodeGBK(), nil
2020-07-17 09:05:25 +08:00
}
2022-10-24 09:51:19 +08:00
func CheckFile(data []byte) bool {
if len(data) < 8 {
return false
}
header := data[0:8]
start := binary.LittleEndian.Uint32(header[:4])
end := binary.LittleEndian.Uint32(header[4:])
if start >= end || uint32(len(data)) < end+7 {
return false
}
return true
}