Clash.Meta/component/mmdb/mmdb.go

102 lines
1.9 KiB
Go
Raw Normal View History

2022-03-15 01:30:17 +08:00
package mmdb
import (
2023-04-10 21:03:31 +08:00
"context"
2023-01-09 21:07:31 +08:00
"io"
"net/http"
"os"
2022-03-15 01:30:17 +08:00
"sync"
2023-04-10 21:03:31 +08:00
"time"
2022-03-15 01:30:17 +08:00
2024-03-05 10:57:25 +08:00
mihomoOnce "github.com/metacubex/mihomo/common/once"
2023-11-03 21:01:45 +08:00
mihomoHttp "github.com/metacubex/mihomo/component/http"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
2023-04-10 21:03:31 +08:00
2023-07-14 22:28:24 +08:00
"github.com/oschwald/maxminddb-golang"
)
type databaseType = uint8
const (
typeMaxmind databaseType = iota
typeSing
typeMetaV0
2022-03-15 01:30:17 +08:00
)
var (
2023-07-14 22:28:24 +08:00
reader Reader
once sync.Once
2022-03-15 01:30:17 +08:00
)
func LoadFromBytes(buffer []byte) {
once.Do(func() {
2023-07-14 22:28:24 +08:00
mmdb, err := maxminddb.FromBytes(buffer)
2022-03-15 01:30:17 +08:00
if err != nil {
log.Fatalln("Can't load mmdb: %s", err.Error())
}
2023-07-14 22:28:24 +08:00
reader = Reader{Reader: mmdb}
switch mmdb.Metadata.DatabaseType {
case "sing-geoip":
2023-07-14 22:28:24 +08:00
reader.databaseType = typeSing
case "Meta-geoip0":
reader.databaseType = typeMetaV0
default:
2023-07-14 22:28:24 +08:00
reader.databaseType = typeMaxmind
}
2022-03-15 01:30:17 +08:00
})
}
func Verify() bool {
2023-07-14 22:28:24 +08:00
instance, err := maxminddb.Open(C.Path.MMDB())
2022-03-15 01:30:17 +08:00
if err == nil {
instance.Close()
}
return err == nil
}
2023-07-14 22:28:24 +08:00
func Instance() Reader {
2022-03-15 01:30:17 +08:00
once.Do(func() {
mmdbPath := C.Path.MMDB()
2024-02-21 21:56:20 +08:00
log.Infoln("Load MMDB file: %s", mmdbPath)
mmdb, err := maxminddb.Open(mmdbPath)
2022-03-15 01:30:17 +08:00
if err != nil {
log.Fatalln("Can't load MMDB: %s", err.Error())
2022-03-15 01:30:17 +08:00
}
2023-07-14 22:28:24 +08:00
reader = Reader{Reader: mmdb}
switch mmdb.Metadata.DatabaseType {
case "sing-geoip":
2023-07-14 22:28:24 +08:00
reader.databaseType = typeSing
case "Meta-geoip0":
reader.databaseType = typeMetaV0
default:
2023-07-14 22:28:24 +08:00
reader.databaseType = typeMaxmind
}
2022-03-15 01:30:17 +08:00
})
2023-07-14 22:28:24 +08:00
return reader
2022-03-15 01:30:17 +08:00
}
2023-01-09 21:07:31 +08:00
func DownloadMMDB(path string) (err error) {
2023-04-10 21:03:31 +08:00
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
defer cancel()
2023-11-12 02:44:55 +08:00
resp, err := mihomoHttp.HttpRequest(ctx, C.MmdbUrl, http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil)
2023-01-09 21:07:31 +08:00
if err != nil {
return
}
defer resp.Body.Close()
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
return err
}
2024-02-21 21:56:20 +08:00
func Reload() {
2024-03-05 10:57:25 +08:00
mihomoOnce.Reset(&once)
2024-02-21 21:56:20 +08:00
}