Skip to content

Commit

Permalink
+ bump code
Browse files Browse the repository at this point in the history
  • Loading branch information
ysicing committed Dec 14, 2024
1 parent 2f01eec commit 91857f1
Show file tree
Hide file tree
Showing 6 changed files with 393 additions and 495 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
caddy
caddy.log
caddy.log
Country.mmdb
Binary file modified Country.mmdb
Binary file not shown.
1 change: 0 additions & 1 deletion Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ tasks:
--with github.com/caddy-dns/tencentcloud
--with github.com/caddy-dns/alidns
--with github.com/caddy-dns/dnspod
--with github.com/WeidiDeng/caddy-cloudflare-ip
- ./caddy list-modules

run:
Expand Down
153 changes: 138 additions & 15 deletions geocn.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package geocn

import (
"context"
"fmt"
"io"
"net"
"net/http"
"os"
"time"

"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
Expand All @@ -20,12 +24,25 @@ var (
_ caddyfile.Unmarshaler = (*CNGeoIP)(nil)
)

const (
remotefile = "https://github.com/Hackl0us/GeoIP2-CN/raw/release/Country.mmdb"
)

func init() {
caddy.RegisterModule(CNGeoIP{})
}

type CNGeoIP struct {
DBFile string `json:"db_file"`
// refresh Interval
Interval caddy.Duration `json:"interval,omitempty"`
// request Timeout
Timeout caddy.Duration `json:"timeout,omitempty"`
// GeoIP2-CN remotefile
RemoteFile string `json:"georemote,omitempty"`
// GeoIP2-CN localfile
GeoFile string `json:"geolocal,omitempty"`

ctx caddy.Context
dbReader *geoip2.Reader
logger *zap.Logger
}
Expand All @@ -37,6 +54,14 @@ func (CNGeoIP) CaddyModule() caddy.ModuleInfo {
}
}

// getContext returns a cancelable context, with a timeout if configured.
func (s *CNGeoIP) getContext() (context.Context, context.CancelFunc) {
if s.Timeout > 0 {
return context.WithTimeout(s.ctx, time.Duration(s.Timeout))
}
return context.WithCancel(s.ctx)
}

func (m *CNGeoIP) validSource(ip net.IP) bool {
if ip == nil {
return false
Expand All @@ -54,16 +79,90 @@ func (m *CNGeoIP) validSource(ip net.IP) bool {
}

func (m *CNGeoIP) Provision(ctx caddy.Context) error {
var err error
m.dbReader, err = geoip2.Open(m.DBFile)
m.ctx = ctx
m.logger = ctx.Logger(m)
m.logger.Debug("provision ", zap.String("geodb file", m.DBFile))

// 检查 RemoteFile 是否为空
if m.RemoteFile == "" {
m.RemoteFile = remotefile
}

// 下载并加载文件
if err := m.updateGeoFile(); err != nil {
return err
}

// 如果设置了更新间隔,启动定时更新
if m.Interval > 0 {
go m.periodicUpdate()
}

return nil
}

func (m *CNGeoIP) updateGeoFile() error {
// 下载文件
if err := m.downloadFile(); err != nil {
return fmt.Errorf("download file %v: %v", m.RemoteFile, err)
}

// 如果已存在 Reader,先关闭
if m.dbReader != nil {
m.dbReader.Close()
}

// 加载新文件
var err error
m.dbReader, err = geoip2.Open(m.GeoFile)
if err != nil {
return fmt.Errorf("cannot open geodb file %v: %v", m.DBFile, err)
return fmt.Errorf("open geodb file %v: %v", m.GeoFile, err)
}

m.logger.Debug("update geodb file", zap.String("geodb file", m.GeoFile), zap.String("remote file", m.RemoteFile))
return nil
}

func (m *CNGeoIP) downloadFile() error {
ctx, cancel := m.getContext()
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.RemoteFile, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("download file %v: %v", m.RemoteFile, resp.StatusCode)
}

out, err := os.Create(m.GeoFile)
if err != nil {
return err
}
defer out.Close()

_, err = io.Copy(out, resp.Body)
return err
}

func (m *CNGeoIP) periodicUpdate() {
if m.Interval == 0 {
m.Interval = caddy.Duration(time.Hour * 12)
}
ticker := time.NewTicker(time.Duration(m.Interval))
defer ticker.Stop()

for range ticker.C {
if err := m.updateGeoFile(); err != nil {
m.logger.Error("periodic update geodb file", zap.Error(err))
}
}
}

func (m *CNGeoIP) Cleanup() error {
if m.dbReader != nil {
return m.dbReader.Close()
Expand All @@ -73,23 +172,47 @@ func (m *CNGeoIP) Cleanup() error {

// UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (m *CNGeoIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
crt := 0
for d.Next() {
for n := d.Nesting(); d.NextBlock(n); {
switch d.Val() {
case "db_file":
crt = 1
default:
switch crt {
case 1:
m.DBFile = d.Val()
crt = 0
case "interval":
if !d.NextArg() {
return d.ArgErr()
}
val, err := caddy.ParseDuration(d.Val())
if err != nil {
return err
}
m.Interval = caddy.Duration(val)
case "timeout":
if !d.NextArg() {
return d.ArgErr()
}
val, err := caddy.ParseDuration(d.Val())
if err != nil {
return err
}
m.Timeout = caddy.Duration(val)
case "geolocal":
if !d.NextArg() {
return d.ArgErr()
}
m.GeoFile = d.Val()
case "georemote":
if !d.NextArg() {
return d.ArgErr()
}
m.RemoteFile = d.Val()
default:
return d.ArgErr()
}
}
}
if len(m.DBFile) == 0 {
m.DBFile = "/etc/caddy/Country.mmdb"
if len(m.GeoFile) == 0 {
m.GeoFile = "/etc/caddy/Country.mmdb"
}
if len(m.RemoteFile) == 0 {
m.RemoteFile = remotefile
}
return nil
}
Expand Down
106 changes: 57 additions & 49 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,44 @@ module github.com/ysicing/caddy2-geocn
go 1.22.2

require (
github.com/caddyserver/caddy/v2 v2.7.6
github.com/oschwald/geoip2-golang v1.9.0
github.com/caddyserver/caddy/v2 v2.8.4
github.com/oschwald/geoip2-golang v1.11.0
go.uber.org/zap v1.27.0
)

require (
filippo.io/edwards25519 v1.0.0 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.2.0 // indirect
github.com/Masterminds/sprig/v3 v3.2.3 // indirect
github.com/Microsoft/go-winio v0.6.0 // indirect
github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230305170008-8188dc5388df // indirect
github.com/antlr4-go/antlr/v4 v4.13.0 // indirect
github.com/aryann/difflib v0.0.0-20210328193216-ff5ff6dc229b // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/caddyserver/certmagic v0.20.0 // indirect
github.com/caddyserver/certmagic v0.21.4 // indirect
github.com/caddyserver/zerossl v0.1.3 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/chzyer/readline v1.5.1 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect
github.com/dgraph-io/badger v1.6.2 // indirect
github.com/dgraph-io/badger/v2 v2.2007.4 // indirect
github.com/dgraph-io/ristretto v0.1.0 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-kit/kit v0.10.0 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-jose/go-jose/v3 v3.0.3 // indirect
github.com/go-kit/kit v0.13.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
github.com/golang/glog v1.1.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
github.com/golang/glog v1.2.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/cel-go v0.15.1 // indirect
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect
github.com/google/uuid v1.3.1 // indirect
github.com/google/cel-go v0.20.1 // indirect
github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/huandu/xstrings v1.3.3 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
Expand All @@ -49,63 +52,68 @@ require (
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
github.com/jackc/pgtype v1.14.3 // indirect
github.com/jackc/pgx/v4 v4.18.3 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/libdns/libdns v0.2.1 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/klauspost/cpuid/v2 v2.2.9 // indirect
github.com/libdns/libdns v0.2.2 // indirect
github.com/manifoldco/promptui v0.9.0 // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/mholt/acmez v1.2.0 // indirect
github.com/micromdm/scep/v2 v2.1.0 // indirect
github.com/miekg/dns v1.1.55 // indirect
github.com/mholt/acmez/v2 v2.0.3 // indirect
github.com/miekg/dns v1.1.62 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/go-ps v1.0.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/onsi/ginkgo/v2 v2.9.5 // indirect
github.com/oschwald/maxminddb-golang v1.12.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/onsi/ginkgo/v2 v2.22.0 // indirect
github.com/oschwald/maxminddb-golang v1.13.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_golang v1.19.1 // indirect
github.com/prometheus/client_model v0.5.0 // indirect
github.com/prometheus/common v0.48.0 // indirect
github.com/prometheus/procfs v0.12.0 // indirect
github.com/prometheus/client_golang v1.20.5 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.61.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.48.2 // indirect
github.com/rs/xid v1.5.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/shopspring/decimal v1.2.0 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/slackhq/nebula v1.6.1 // indirect
github.com/smallstep/certificates v0.25.0 // indirect
github.com/smallstep/nosql v0.6.0 // indirect
github.com/smallstep/truststore v0.12.1 // indirect
github.com/smallstep/certificates v0.26.1 // indirect
github.com/smallstep/nosql v0.6.1 // indirect
github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81 // indirect
github.com/smallstep/scep v0.0.0-20231024192529-aee96d7ad34d // indirect
github.com/smallstep/truststore v0.13.0 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/cobra v1.7.0 // indirect
github.com/spf13/cobra v1.8.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stoewer/go-strcase v1.2.0 // indirect
github.com/tailscale/tscert v0.0.0-20230806124524-28a91b69a046 // indirect
github.com/tailscale/tscert v0.0.0-20240517230440-bbccfbf48933 // indirect
github.com/urfave/cli v1.22.14 // indirect
github.com/zeebo/blake3 v0.2.3 // indirect
go.etcd.io/bbolt v1.3.7 // indirect
go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352 // indirect
go.step.sm/cli-utils v0.8.0 // indirect
go.step.sm/crypto v0.35.1 // indirect
github.com/zeebo/blake3 v0.2.4 // indirect
go.etcd.io/bbolt v1.3.9 // indirect
go.step.sm/cli-utils v0.9.0 // indirect
go.step.sm/crypto v0.45.0 // indirect
go.step.sm/linkedca v0.20.1 // indirect
go.uber.org/mock v0.4.0 // indirect
go.uber.org/automaxprocs v1.5.3 // indirect
go.uber.org/mock v0.5.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap/exp v0.3.0 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/crypto/x509roots/fallback v0.0.0-20240507223354-67b13616a595 // indirect
golang.org/x/exp v0.0.0-20241210194714-1829a127f884 // indirect
golang.org/x/mod v0.22.0 // indirect
golang.org/x/net v0.32.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/term v0.27.0 // indirect
golang.org/x/text v0.21.0 // indirect
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b // indirect
google.golang.org/grpc v1.59.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/square/go-jose.v2 v2.6.0 // indirect
golang.org/x/time v0.8.0 // indirect
golang.org/x/tools v0.28.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240506185236-b8a5c65736ae // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240429193739-8cf5692501f6 // indirect
google.golang.org/grpc v1.63.2 // indirect
google.golang.org/protobuf v1.35.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
howett.net/plist v1.0.0 // indirect
)
Loading

0 comments on commit 91857f1

Please sign in to comment.