diff --git a/.gitignore b/.gitignore index b5c0aee..6358c7d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ demo demo.toml -demo.wanf *.log *.bak list.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a2cb2a..9a9638b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,18 +1,5 @@ # 更新日志 -4.3.0 - 2025-08-11 ---- -- CHANGE: 为OCI镜像(Docker)代理带来自动library附加功能 -- CHANGE(refactor): 改进OCI镜像(Docker)代理路径组成流程 -- ADD: 新增[WANF](https://github.com/WJQSERVER/wanf)配置文件格式支持 - -4.3.0-rc.0 - 2025-08-11 ---- -- PRE-RELEASE: v4.3.0-rc.0是v4.3.0发布版本,请勿在生产环境中使用; -- CHANGE: 为OCI镜像(Docker)代理带来自动library附加功能 -- CHANGE(refactor): 改进OCI镜像(Docker)代理路径组成流程 -- ADD: 新增[WANF](https://github.com/WJQSERVER/wanf)配置文件格式支持 - 4.2.7 - 2025-08-04 --- - CHANGE: 在OCI镜像(docker)代理部分增加特殊处理, 保证可用性 参看[#159](https://github.com/WJQSERVER-STUDIO/ghproxy/issues/159) diff --git a/DEV-VERSION b/DEV-VERSION index 51ff7c7..4c573d6 100644 --- a/DEV-VERSION +++ b/DEV-VERSION @@ -1 +1 @@ -4.3.0-rc.0 \ No newline at end of file +4.2.4-rc.0 \ No newline at end of file diff --git a/VERSION b/VERSION index 8191138..c30a815 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -4.3.0 \ No newline at end of file +4.2.7 \ No newline at end of file diff --git a/config/config.go b/config/config.go index 6a6b039..3ea330d 100644 --- a/config/config.go +++ b/config/config.go @@ -2,28 +2,24 @@ package config import ( "os" - "path/filepath" "github.com/BurntSushi/toml" - - "github.com/WJQSERVER/wanf" ) -// Config 结构体定义了整个应用程序的配置 type Config struct { - Server ServerConfig `toml:"server" wanf:"server"` - Httpc HttpcConfig `toml:"httpc" wanf:"httpc"` - GitClone GitCloneConfig `toml:"gitclone" wanf:"gitclone"` - Shell ShellConfig `toml:"shell" wanf:"shell"` - Pages PagesConfig `toml:"pages" wanf:"pages"` - Log LogConfig `toml:"log" wanf:"log"` - Auth AuthConfig `toml:"auth" wanf:"auth"` - Blacklist BlacklistConfig `toml:"blacklist" wanf:"blacklist"` - Whitelist WhitelistConfig `toml:"whitelist" wanf:"whitelist"` - IPFilter IPFilterConfig `toml:"ipFilter" wanf:"ipFilter"` - RateLimit RateLimitConfig `toml:"rateLimit" wanf:"rateLimit"` - Outbound OutboundConfig `toml:"outbound" wanf:"outbound"` - Docker DockerConfig `toml:"docker" wanf:"docker"` + Server ServerConfig `toml:"server"` + Httpc HttpcConfig `toml:"httpc"` + GitClone GitCloneConfig `toml:"gitclone"` + Shell ShellConfig `toml:"shell"` + Pages PagesConfig `toml:"pages"` + Log LogConfig `toml:"log"` + Auth AuthConfig `toml:"auth"` + Blacklist BlacklistConfig `toml:"blacklist"` + Whitelist WhitelistConfig `toml:"whitelist"` + IPFilter IPFilterConfig `toml:"ipFilter"` + RateLimit RateLimitConfig `toml:"rateLimit"` + Outbound OutboundConfig `toml:"outbound"` + Docker DockerConfig `toml:"docker"` } /* @@ -36,14 +32,13 @@ cors = "*" # "*"/"" -> "*" ; "nil" -> "" ; debug = false */ -// ServerConfig 定义服务器相关的配置 type ServerConfig struct { - Port int `toml:"port" wanf:"port"` - Host string `toml:"host" wanf:"host"` - SizeLimit int `toml:"sizeLimit" wanf:"sizeLimit"` - MemLimit int64 `toml:"memLimit" wanf:"memLimit"` - Cors string `toml:"cors" wanf:"cors"` - Debug bool `toml:"debug" wanf:"debug"` + Port int `toml:"port"` + Host string `toml:"host"` + SizeLimit int `toml:"sizeLimit"` + MemLimit int64 `toml:"memLimit"` + Cors string `toml:"cors"` + Debug bool `toml:"debug"` } /* @@ -54,13 +49,12 @@ maxIdleConnsPerHost = 60 # only for advanced mode maxConnsPerHost = 0 # only for advanced mode useCustomRawHeaders = false */ -// HttpcConfig 定义 HTTP 客户端相关的配置 type HttpcConfig struct { - Mode string `toml:"mode" wanf:"mode"` - MaxIdleConns int `toml:"maxIdleConns" wanf:"maxIdleConns"` - MaxIdleConnsPerHost int `toml:"maxIdleConnsPerHost" wanf:"maxIdleConnsPerHost"` - MaxConnsPerHost int `toml:"maxConnsPerHost" wanf:"maxConnsPerHost"` - UseCustomRawHeaders bool `toml:"useCustomRawHeaders" wanf:"useCustomRawHeaders"` + Mode string `toml:"mode"` + MaxIdleConns int `toml:"maxIdleConns"` + MaxIdleConnsPerHost int `toml:"maxIdleConnsPerHost"` + MaxConnsPerHost int `toml:"maxConnsPerHost"` + UseCustomRawHeaders bool `toml:"useCustomRawHeaders"` } /* @@ -70,12 +64,11 @@ smartGitAddr = "http://127.0.0.1:8080" //cacheTimeout = 10 ForceH2C = true */ -// GitCloneConfig 定义 Git 克隆相关的配置 type GitCloneConfig struct { - Mode string `toml:"mode" wanf:"mode"` - SmartGitAddr string `toml:"smartGitAddr" wanf:"smartGitAddr"` + Mode string `toml:"mode"` + SmartGitAddr string `toml:"smartGitAddr"` //CacheTimeout int `toml:"cacheTimeout"` - ForceH2C bool `toml:"ForceH2C" wanf:"ForceH2C"` + ForceH2C bool `toml:"ForceH2C"` } /* @@ -83,10 +76,9 @@ type GitCloneConfig struct { editor = true rewriteAPI = false */ -// ShellConfig 定义 Shell 相关的配置 type ShellConfig struct { - Editor bool `toml:"editor" wanf:"editor"` - RewriteAPI bool `toml:"rewriteAPI" wanf:"rewriteAPI"` + Editor bool `toml:"editor"` + RewriteAPI bool `toml:"rewriteAPI"` } /* @@ -95,18 +87,16 @@ mode = "internal" # "internal" or "external" theme = "bootstrap" # "bootstrap" or "nebula" staticDir = "/data/www" */ -// PagesConfig 定义静态页面相关的配置 type PagesConfig struct { - Mode string `toml:"mode" wanf:"mode"` - Theme string `toml:"theme" wanf:"theme"` - StaticDir string `toml:"staticDir" wanf:"staticDir"` + Mode string `toml:"mode"` + Theme string `toml:"theme"` + StaticDir string `toml:"staticDir"` } -// LogConfig 定义日志相关的配置 type LogConfig struct { - LogFilePath string `toml:"logFilePath" wanf:"logFilePath"` - MaxLogSize int64 `toml:"maxLogSize" wanf:"maxLogSize"` - Level string `toml:"level" wanf:"level"` + LogFilePath string `toml:"logFilePath"` + MaxLogSize int64 `toml:"maxLogSize"` + Level string `toml:"level"` } /* @@ -119,35 +109,31 @@ passThrough = false ForceAllowApi = false ForceAllowApiPassList = false */ -// AuthConfig 定义认证相关的配置 type AuthConfig struct { - Enabled bool `toml:"enabled" wanf:"enabled"` - Method string `toml:"method" wanf:"method"` - Key string `toml:"key" wanf:"key"` - Token string `toml:"token" wanf:"token"` - PassThrough bool `toml:"passThrough" wanf:"passThrough"` - ForceAllowApi bool `toml:"ForceAllowApi" wanf:"ForceAllowApi"` - ForceAllowApiPassList bool `toml:"ForceAllowApiPassList" wanf:"ForceAllowApiPassList"` + Enabled bool `toml:"enabled"` + Method string `toml:"method"` + Key string `toml:"key"` + Token string `toml:"token"` + PassThrough bool `toml:"passThrough"` + ForceAllowApi bool `toml:"ForceAllowApi"` + ForceAllowApiPassList bool `toml:"ForceAllowApiPassList"` } -// BlacklistConfig 定义黑名单相关的配置 type BlacklistConfig struct { - Enabled bool `toml:"enabled" wanf:"enabled"` - BlacklistFile string `toml:"blacklistFile" wanf:"blacklistFile"` + Enabled bool `toml:"enabled"` + BlacklistFile string `toml:"blacklistFile"` } -// WhitelistConfig 定义白名单相关的配置 type WhitelistConfig struct { - Enabled bool `toml:"enabled" wanf:"enabled"` - WhitelistFile string `toml:"whitelistFile" wanf:"whitelistFile"` + Enabled bool `toml:"enabled"` + WhitelistFile string `toml:"whitelistFile"` } -// IPFilterConfig 定义 IP 过滤相关的配置 type IPFilterConfig struct { - Enabled bool `toml:"enabled" wanf:"enabled"` - EnableAllowList bool `toml:"enableAllowList" wanf:"enableAllowList"` - EnableBlockList bool `toml:"enableBlockList" wanf:"enableBlockList"` - IPFilterFile string `toml:"ipFilterFile" wanf:"ipFilterFile"` + Enabled bool `toml:"enabled"` + EnableAllowList bool `toml:"enableAllowList"` + EnableBlockList bool `toml:"enableBlockList"` + IPFilterFile string `toml:"ipFilterFile"` } /* @@ -164,21 +150,19 @@ burst = 10 singleBurst = "10mbps" */ -// RateLimitConfig 定义限速相关的配置 type RateLimitConfig struct { - Enabled bool `toml:"enabled" wanf:"enabled"` - RatePerMinute int `toml:"ratePerMinute" wanf:"ratePerMinute"` - Burst int `toml:"burst" wanf:"burst"` - BandwidthLimit BandwidthLimitConfig `toml:"bandwidthLimit" wanf:"bandwidthLimit"` + Enabled bool `toml:"enabled"` + RatePerMinute int `toml:"ratePerMinute"` + Burst int `toml:"burst"` + BandwidthLimit BandwidthLimitConfig } -// BandwidthLimitConfig 定义带宽限制相关的配置 type BandwidthLimitConfig struct { - Enabled bool `toml:"enabled" wanf:"enabled"` - TotalLimit string `toml:"totalLimit" wanf:"totalLimit"` - TotalBurst string `toml:"totalBurst" wanf:"totalBurst"` - SingleLimit string `toml:"singleLimit" wanf:"singleLimit"` - SingleBurst string `toml:"singleBurst" wanf:"singleBurst"` + Enabled bool `toml:"enabled"` + TotalLimit string `toml:"totalLimit"` + TotalBurst string `toml:"totalBurst"` + SingleLimit string `toml:"singleLimit"` + SingleBurst string `toml:"singleBurst"` } /* @@ -186,10 +170,9 @@ type BandwidthLimitConfig struct { enabled = false url = "socks5://127.0.0.1:1080" # "http://127.0.0.1:7890" */ -// OutboundConfig 定义出站代理相关的配置 type OutboundConfig struct { - Enabled bool `toml:"enabled" wanf:"enabled"` - Url string `toml:"url" wanf:"url"` + Enabled bool `toml:"enabled"` + Url string `toml:"url"` } /* @@ -201,16 +184,15 @@ auth = false user1 = "testpass" test = "test123" */ -// DockerConfig 定义 Docker 相关的配置 type DockerConfig struct { - Enabled bool `toml:"enabled" wanf:"enabled"` - Target string `toml:"target" wanf:"target"` - Auth bool `toml:"auth" wanf:"auth"` - Credentials map[string]string `toml:"credentials" wanf:"credentials"` - AuthPassThrough bool `toml:"authPassThrough" wanf:"authPassThrough"` + Enabled bool `toml:"enabled"` + Target string `toml:"target"` + Auth bool `toml:"auth"` + Credentials map[string]string `toml:"credentials"` + AuthPassThrough bool `toml:"authPassThrough"` } -// LoadConfig 从配置文件加载配置 +// LoadConfig 从 TOML 配置文件加载配置 func LoadConfig(filePath string) (*Config, error) { if !FileExists(filePath) { // 楔入配置文件 @@ -220,22 +202,15 @@ func LoadConfig(filePath string) (*Config, error) { } return DefaultConfig(), nil } - var config Config - ext := filepath.Ext(filePath) - if ext == ".wanf" { - if err := wanf.DecodeFile(filePath, &config); err != nil { - return nil, err - } - return &config, nil - } + var config Config if _, err := toml.DecodeFile(filePath, &config); err != nil { return nil, err } return &config, nil } -// WriteConfig 写入配置文件 +// 写入配置文件 func (c *Config) WriteConfig(filePath string) error { file, err := os.Create(filePath) if err != nil { @@ -243,26 +218,17 @@ func (c *Config) WriteConfig(filePath string) error { } defer file.Close() - ext := filepath.Ext(filePath) - if ext == ".wanf" { - err := wanf.NewStreamEncoder(file).Encode(c) - if err != nil { - return err - } - return nil - } - encoder := toml.NewEncoder(file) return encoder.Encode(c) } -// FileExists 检测文件是否存在 +// 检测文件是否存在 func FileExists(filename string) bool { _, err := os.Stat(filename) return !os.IsNotExist(err) } -// DefaultConfig 返回默认配置结构体 +// 默认配置结构体 func DefaultConfig() *Config { return &Config{ Server: ServerConfig{ diff --git a/go.mod b/go.mod index 84ecf8e..a267aaf 100644 --- a/go.mod +++ b/go.mod @@ -1,18 +1,17 @@ module ghproxy -go 1.24.6 +go 1.24.5 require ( github.com/BurntSushi/toml v1.5.0 github.com/WJQSERVER-STUDIO/httpc v0.8.2 - golang.org/x/net v0.43.0 + golang.org/x/net v0.42.0 golang.org/x/time v0.12.0 ) require ( github.com/WJQSERVER-STUDIO/go-utils/iox v0.0.2 github.com/WJQSERVER-STUDIO/go-utils/limitreader v0.0.2 - github.com/WJQSERVER/wanf v0.0.0-20250810023226-e51d9d0737ee github.com/fenthope/bauth v0.0.1 github.com/fenthope/ikumi v0.0.2 github.com/fenthope/ipfilter v0.0.1 diff --git a/go.sum b/go.sum index 08e3e56..d84ed19 100644 --- a/go.sum +++ b/go.sum @@ -6,8 +6,6 @@ github.com/WJQSERVER-STUDIO/go-utils/limitreader v0.0.2 h1:8bBkKk6E2Zr+I5szL7gyc github.com/WJQSERVER-STUDIO/go-utils/limitreader v0.0.2/go.mod h1:yPX8xuZH+py7eLJwOYj3VVI/4/Yuy5+x8Mhq8qezcPg= github.com/WJQSERVER-STUDIO/httpc v0.8.2 h1:PFPLodV0QAfGEP6915J57vIqoKu9cGuuiXG/7C9TNUk= github.com/WJQSERVER-STUDIO/httpc v0.8.2/go.mod h1:8WhHVRO+olDFBSvL5PC/bdMkb6U3vRdPJ4p4pnguV5Y= -github.com/WJQSERVER/wanf v0.0.0-20250810023226-e51d9d0737ee h1:tJ31DNBn6UhWkk8fiikAQWqULODM+yBcGAEar1tzdZc= -github.com/WJQSERVER/wanf v0.0.0-20250810023226-e51d9d0737ee/go.mod h1:q2Pyg+G+s1acMWxrbI4CwS/Yk76/BzLREEdZ8iFwUNE= github.com/fenthope/bauth v0.0.1 h1:+4UIQshGx3mYD4L3f2S4MLZOi5PWU7fU5GK3wsZvwzE= github.com/fenthope/bauth v0.0.1/go.mod h1:1fveTpgfR1p+WXQ8MXm9BfBCeNYi55j23jxCOGOvBSA= github.com/fenthope/ikumi v0.0.2 h1:5oaSTf/Msp7M2O3o/X20omKWEQbFhX4KV0CVF21oCdk= @@ -28,7 +26,7 @@ github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6Kllzaw github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/wjqserver/modembed v0.0.1 h1:8ZDz7t9M5DLrUFlYgBUUmrMzxWsZPmHvOazkr/T2jEs= github.com/wjqserver/modembed v0.0.1/go.mod h1:sYbQJMAjSBsdYQrUsuHY380XXE1CuRh8g9yyCztTXOQ= -golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= -golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= +golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= +golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= diff --git a/main.go b/main.go index 48c10fe..078a1b5 100644 --- a/main.go +++ b/main.go @@ -474,11 +474,20 @@ func main() { proxy.RoutingHandler(cfg)(c) }) - r.ANY("/v2/*path", + r.GET("/v2/", r.UseIf(cfg.Docker.Auth, func() touka.HandlerFunc { return bauth.BasicAuthForStatic(cfg.Docker.Credentials, "GHProxy Docker Proxy") }), - proxy.OciWithImageRouting(cfg), + func(c *touka.Context) { + emptyJSON := "{}" + c.Header("Content-Type", "application/json") + c.Header("Content-Length", fmt.Sprint(len(emptyJSON))) + + c.Header("Docker-Distribution-API-Version", "registry/2.0") + + c.Status(200) + c.Writer.Write([]byte(emptyJSON)) + }, ) r.GET("/v2", func(c *touka.Context) { @@ -486,6 +495,10 @@ func main() { c.Redirect(http.StatusMovedPermanently, "/v2/") }) + r.ANY("/v2/:target/:user/:repo/*filepath", func(c *touka.Context) { + proxy.GhcrWithImageRouting(cfg)(c) + }) + r.NoRoute(func(c *touka.Context) { proxy.NoRouteHandler(cfg)(c) }) diff --git a/proxy/docker.go b/proxy/docker.go index fb0c309..955f7e0 100644 --- a/proxy/docker.go +++ b/proxy/docker.go @@ -40,167 +40,90 @@ func InitWeakCache() *weakcache.Cache[string] { return cache } -var ( - authEndpoint = "/" - passTypeMap = map[string]struct{}{ - "manifests": {}, - "blobs": {}, - "tags": {}, - "index": {}, - } -) - -// 处理路径各种情况 -func OciWithImageRouting(cfg *config.Config) touka.HandlerFunc { +// GhcrWithImageRouting 处理带有镜像路由的请求, 根据目标路由到不同的Docker注册表 +func GhcrWithImageRouting(cfg *config.Config) touka.HandlerFunc { return func(c *touka.Context) { - if !cfg.Docker.Enabled { - ErrorPage(c, NewErrorWithStatusLookup(403, "Docker proxy is not enabled")) - return - } - var ( - p1 string - p2 string - p3 string - p4 string - target string - user string - repo string - extpath string - p1IsTarget bool - ignorep3 bool - imageNameForAuth string - finalreqUrl string - iInfo *imageInfo - ) - ociPath := c.Param("path") - if ociPath == authEndpoint { - emptyJSON := "{}" - c.Header("Content-Type", "application/json") - c.Header("Content-Length", fmt.Sprint(len(emptyJSON))) + // 从 main.go 中固定的路由 "/v2/:target/:user/:repo/*filepath" 获取参数 + reqTarget := c.Param("target") + reqImageUser := c.Param("user") + reqImageName := c.Param("repo") + reqFilePath := c.Param("filepath") - c.Header("Docker-Distribution-API-Version", "registry/2.0") + var upstreamTarget string + var requestPath string + var imageNameForAuth string - c.Status(200) - c.Writer.Write([]byte(emptyJSON)) - return - } + // 关键逻辑: 判断 reqTarget 是真实主机名还是镜像名的一部分 + // 依据: 真实主机名/IP通常包含'.'或':' + if strings.Contains(reqTarget, ".") || strings.Contains(reqTarget, ":") { + // 情况 A: reqTarget 是一个显式指定的主机名 (例如 "ghcr.io", "my-registry.com", "127.0.0.1:5000") + c.Debugf("Request target '%s' identified as an explicit hostname.", reqTarget) - // 根据/分割 /:target/:user/:repo/*ext - ociPath = ociPath[1:] - i := strings.IndexByte(ociPath, '/') - if i <= 0 { - ErrorPage(c, NewErrorWithStatusLookup(404, "Not Found")) - return - } - p1 = ociPath[:i] - - // 开始判断p1是否为target - if strings.Contains(p1, ".") || strings.Contains(p1, ":") { - p1IsTarget = true - if p1 == "docker.io" { - target = dockerhubTarget + // https://github.com/WJQSERVER-STUDIO/ghproxy/issues/159 + if reqTarget == "docker.io" { + upstreamTarget = dockerhubTarget } else { - target = p1 + upstreamTarget = reqTarget } + // 上游请求的路径是主机名之后的部分 + requestPath = fmt.Sprintf("%s/%s%s", reqImageUser, reqImageName, reqFilePath) + // 用于认证的镜像名是 user/repo + imageNameForAuth = fmt.Sprintf("%s/%s", reqImageUser, reqImageName) } else { + // 情况 B: reqTarget 是镜像名的一部分 (例如 "wjqserver", "library") + c.Debugf("Request target '%s' identified as part of an image name. Using default registry.", reqTarget) + // 使用配置文件中的默认目标 switch cfg.Docker.Target { case "ghcr": - target = ghcrTarget + upstreamTarget = ghcrTarget case "dockerhub": - target = dockerhubTarget + upstreamTarget = dockerhubTarget case "": ErrorPage(c, NewErrorWithStatusLookup(500, "Default Docker Target is not configured in config file")) return default: - target = cfg.Docker.Target + upstreamTarget = cfg.Docker.Target } + // 必须将路由错误分割的所有部分重新组合成完整的镜像路径 + requestPath = fmt.Sprintf("%s/%s/%s%s", reqTarget, reqImageUser, reqImageName, reqFilePath) + // 用于认证的镜像名是 target/user (例如 "wjqserver/ghproxy", "library/ubuntu") + imageNameForAuth = fmt.Sprintf("%s/%s", reqTarget, reqImageUser) } - ociPath = ociPath[i+1:] - i = strings.IndexByte(ociPath, '/') - if i <= 0 { - ErrorPage(c, NewErrorWithStatusLookup(404, "Not Found")) - return - } - p2 = ociPath[:i] - ociPath = ociPath[i+1:] + // 清理路径, 防止出现 "//" + requestPath = strings.TrimPrefix(requestPath, "/") - // 若p2和passTypeMap匹配 - if !p1IsTarget { - if _, ok := passTypeMap[p2]; ok { - ignorep3 = true - switch cfg.Docker.Target { - case "ghcr": - target = ghcrTarget - case "dockerhub": - target = dockerhubTarget - case "": - ErrorPage(c, NewErrorWithStatusLookup(500, "Default Docker Target is not configured in config file")) - return - default: - target = cfg.Docker.Target - } - user = "library" - repo = p1 - extpath = "/" + p2 + "/" + ociPath - } - } - - if !ignorep3 { - i = strings.IndexByte(ociPath, '/') - if i <= 0 { - ErrorPage(c, NewErrorWithStatusLookup(404, "Not Found")) - return - } - p3 = ociPath[:i] - - ociPath = ociPath[i+1:] - p4 = ociPath - - if p1IsTarget { - if _, ok := passTypeMap[p3]; ok { - user = "library" - repo = p2 - extpath = "/" + p3 + "/" + p4 - } else { - user = p2 - repo = p3 - extpath = "/" + p4 - } - } else { - switch cfg.Docker.Target { - case "ghcr": - target = ghcrTarget - case "dockerhub": - target = dockerhubTarget - case "": - ErrorPage(c, NewErrorWithStatusLookup(500, "Default Docker Target is not configured in config file")) - return - default: - target = cfg.Docker.Target - } - user = p1 - repo = p2 - extpath = "/" + p3 + "/" + p4 - } - } - - imageNameForAuth = user + "/" + repo - finalreqUrl = "https://" + target + "/v2/" + imageNameForAuth + extpath - if query := c.GetReqQueryString(); query != "" { - finalreqUrl += "?" + query - } - - iInfo = &imageInfo{ - User: user, - Repo: repo, + // 为认证和缓存准备镜像信息 + image := &imageInfo{ Image: imageNameForAuth, } - GhcrRequest(c.Request.Context(), c, finalreqUrl, iInfo, cfg, target) + // 调用 GhcrToTarget 处理实际的代理请求 + GhcrToTarget(c, cfg, upstreamTarget, requestPath, image) } } +// GhcrToTarget 根据配置和目标信息将请求代理到上游Docker注册表 +func GhcrToTarget(c *touka.Context, cfg *config.Config, target string, path string, image *imageInfo) { + // 检查Docker代理是否启用 + if !cfg.Docker.Enabled { + ErrorPage(c, NewErrorWithStatusLookup(403, "Docker is not Allowed")) + return + } + + var ctx = c.Request.Context() + + // 构造目标URL. 这里的target和path都是由GhcrWithImageRouting正确解析得来的. + destUrl := "https://" + target + "/v2/" + path + if query := c.GetReqQueryString(); query != "" { + destUrl += "?" + query + } + c.Debugf("Proxying to target '%s' with path '%s'. Final URL: %s", target, path, destUrl) + + // 执行实际的代理请求 + GhcrRequest(ctx, c, destUrl, image, cfg, target) +} + // GhcrRequest 执行对Docker注册表的HTTP请求, 处理认证和重定向 func GhcrRequest(ctx context.Context, c *touka.Context, u string, image *imageInfo, cfg *config.Config, target string) { var ( diff --git a/proxy/match.go b/proxy/match.go index 9353c8b..9a37f0a 100644 --- a/proxy/match.go +++ b/proxy/match.go @@ -23,7 +23,6 @@ const ( gistPrefix = "https://gist.github.com/" gistContentPrefix = "https://gist.githubusercontent.com/" apiPrefix = "https://api.github.com/" - ociv2Prefix = "https://v2/" releasesDownloadSnippet = "releases/download/" ) @@ -37,11 +36,9 @@ func init() { // Matcher 从原始URL路径中高效地解析并匹配代理规则. func Matcher(rawPath string, cfg *config.Config) (string, string, string, *GHProxyErrors) { - /* - if len(rawPath) < 18 { - return "", "", "", NewErrorWithStatusLookup(404, "path too short") - } - */ + if len(rawPath) < 18 { + return "", "", "", NewErrorWithStatusLookup(404, "path too short") + } // 匹配 "https://github.com/" if strings.HasPrefix(rawPath, githubPrefix) {