[优化] 增加对节点 IP 的自动探测,优先通过第三方 API 获取公网 IP

This commit is contained in:
ryan
2026-05-30 10:18:05 +08:00
parent 2a00d21987
commit 4e339caa9a
13 changed files with 370 additions and 9 deletions
+1 -1
View File
@@ -69,7 +69,7 @@ func main() {
// Initialize options
model.InitOptionMap()
geoip.InitGeoIP()
geoip.InitGeoIP(common.GeoIPProvider)
backgroundCtx, cancelBackgroundTasks := context.WithCancel(context.Background())
defer cancelBackgroundTasks()
service.StartDatabaseAutoCleanupScheduler(backgroundCtx)
+1 -1
View File
@@ -406,6 +406,6 @@ func updateOptionMap(key string, value string) {
}
common.OptionMapRWMutex.Unlock()
if shouldRefreshGeoIP {
geoip.InitGeoIP()
geoip.InitGeoIP(common.GeoIPProvider)
}
}
+2 -3
View File
@@ -4,7 +4,6 @@ import (
"fmt"
"log/slog"
"net"
"openflare/common"
"strings"
"sync"
"time"
@@ -110,8 +109,8 @@ func GetRegionUnicodeEmoji(isoCode string) string {
return string(rune1) + string(rune2)
}
func InitGeoIP() {
providerName := normalizeProvider(common.GeoIPProvider)
func InitGeoIP(provider string) {
providerName := normalizeProvider(provider)
nextProvider, err := providerFactory(providerName)
if err != nil {
slog.Error("initialize GeoIP provider failed", "provider", providerName, "error", err)
+151
View File
@@ -0,0 +1,151 @@
package geoip
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"openflare/utils/geoip/iputil"
"strings"
"time"
)
const defaultOutboundIPLookupTimeout = 5 * time.Second
// OutboundIPStrategy defines a lookup strategy for the current public egress IP.
type OutboundIPStrategy interface {
Name() string
GetOutboundIP(ctx context.Context) (net.IP, error)
}
// OutboundIPAPIAdapter adapts a third-party HTTP API response into an IP value.
type OutboundIPAPIAdapter interface {
Name() string
Endpoint() string
DecodeIP(io.Reader) (net.IP, error)
}
type HTTPOutboundIPStrategy struct {
Client *http.Client
Adapter OutboundIPAPIAdapter
}
func NewHTTPOutboundIPStrategy(adapter OutboundIPAPIAdapter, client *http.Client) *HTTPOutboundIPStrategy {
if client == nil {
client = &http.Client{Timeout: defaultOutboundIPLookupTimeout}
}
return &HTTPOutboundIPStrategy{
Client: client,
Adapter: adapter,
}
}
func (s *HTTPOutboundIPStrategy) Name() string {
if s == nil || s.Adapter == nil {
return "http-outbound-ip"
}
return s.Adapter.Name()
}
func (s *HTTPOutboundIPStrategy) GetOutboundIP(ctx context.Context) (net.IP, error) {
if s == nil || s.Adapter == nil {
return nil, errors.New("outbound IP adapter is nil")
}
if ctx == nil {
ctx = context.Background()
}
client := s.Client
if client == nil {
client = &http.Client{Timeout: defaultOutboundIPLookupTimeout}
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, s.Adapter.Endpoint(), nil)
if err != nil {
return nil, fmt.Errorf("%s create request failed: %w", s.Name(), err)
}
response, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("%s request failed: %w", s.Name(), err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s returned non-200 status: %d %s", s.Name(), response.StatusCode, response.Status)
}
ip, err := s.Adapter.DecodeIP(response.Body)
if err != nil {
return nil, fmt.Errorf("%s decode response failed: %w", s.Name(), err)
}
if !iputil.IsPublic(ip) {
return nil, fmt.Errorf("%s returned non-public IP: %s", s.Name(), ip.String())
}
return ip, nil
}
type RealIPCCAdapter struct {
URL string
}
type realIPCCResponse struct {
IP string `json:"ip"`
}
func NewRealIPCCOutboundIPStrategy() *HTTPOutboundIPStrategy {
return NewHTTPOutboundIPStrategy(RealIPCCAdapter{}, nil)
}
func (a RealIPCCAdapter) Name() string {
return "realip.cc"
}
func (a RealIPCCAdapter) Endpoint() string {
if strings.TrimSpace(a.URL) != "" {
return strings.TrimSpace(a.URL)
}
return "https://realip.cc"
}
func (a RealIPCCAdapter) DecodeIP(reader io.Reader) (net.IP, error) {
var payload realIPCCResponse
if err := json.NewDecoder(reader).Decode(&payload); err != nil {
return nil, err
}
ip := net.ParseIP(strings.TrimSpace(payload.IP))
if ip == nil {
return nil, fmt.Errorf("invalid IP %q", payload.IP)
}
if ipv4 := ip.To4(); ipv4 != nil {
return ipv4, nil
}
return ip, nil
}
func DefaultOutboundIPStrategies() []OutboundIPStrategy {
return []OutboundIPStrategy{
NewRealIPCCOutboundIPStrategy(),
}
}
func GetOutboundIP(ctx context.Context, strategies ...OutboundIPStrategy) (net.IP, error) {
if len(strategies) == 0 {
strategies = DefaultOutboundIPStrategies()
}
var errs []error
for _, strategy := range strategies {
if strategy == nil {
continue
}
ip, err := strategy.GetOutboundIP(ctx)
if err == nil && ip != nil {
return ip, nil
}
if err != nil {
errs = append(errs, fmt.Errorf("%s: %w", strategy.Name(), err))
}
}
if len(errs) == 0 {
return nil, errors.New("no outbound IP lookup strategy configured")
}
return nil, errors.Join(errs...)
}
@@ -0,0 +1,82 @@
package geoip
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type fakeOutboundIPStrategy struct {
name string
ip net.IP
err error
}
func (f fakeOutboundIPStrategy) Name() string {
return f.name
}
func (f fakeOutboundIPStrategy) GetOutboundIP(ctx context.Context) (net.IP, error) {
return f.ip, f.err
}
func TestRealIPCCAdapterDecodeIP(t *testing.T) {
ip, err := RealIPCCAdapter{}.DecodeIP(strings.NewReader(`{"ip":"8.8.8.8","country":"United States"}`))
if err != nil {
t.Fatalf("DecodeIP failed: %v", err)
}
if ip.String() != "8.8.8.8" {
t.Fatalf("unexpected IP: %s", ip.String())
}
}
func TestHTTPOutboundIPStrategyUsesAdapter(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
t.Fatalf("unexpected method: %s", r.Method)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ip":"8.8.4.4"}`))
}))
defer server.Close()
strategy := NewHTTPOutboundIPStrategy(RealIPCCAdapter{URL: server.URL}, server.Client())
ip, err := strategy.GetOutboundIP(context.Background())
if err != nil {
t.Fatalf("GetOutboundIP failed: %v", err)
}
if ip.String() != "8.8.4.4" {
t.Fatalf("unexpected outbound IP: %s", ip.String())
}
}
func TestGetOutboundIPFallsBackToNextStrategy(t *testing.T) {
ip, err := GetOutboundIP(
context.Background(),
fakeOutboundIPStrategy{name: "first", err: errors.New("temporary failure")},
fakeOutboundIPStrategy{name: "second", ip: net.ParseIP("1.1.1.1")},
)
if err != nil {
t.Fatalf("GetOutboundIP failed: %v", err)
}
if ip.String() != "1.1.1.1" {
t.Fatalf("unexpected outbound IP: %s", ip.String())
}
}
func TestHTTPOutboundIPStrategyRejectsPrivateIP(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ip":"172.17.0.2"}`))
}))
defer server.Close()
strategy := NewHTTPOutboundIPStrategy(RealIPCCAdapter{URL: server.URL}, server.Client())
if _, err := strategy.GetOutboundIP(context.Background()); err == nil {
t.Fatal("expected private IP to be rejected")
}
}