Skip to content

Commit

Permalink
Disable head method
Browse files Browse the repository at this point in the history
  • Loading branch information
wzshiming committed Sep 5, 2024
1 parent cae4912 commit 4f7d87a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 18 deletions.
7 changes: 7 additions & 0 deletions cmd/crproxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ var (
enableInternalAPI bool

readmeURL string

allowHeadMethod bool
)

func init() {
Expand Down Expand Up @@ -114,6 +116,7 @@ func init() {
pflag.BoolVar(&enableInternalAPI, "enable-internal-api", false, "enable internal api")

pflag.StringVar(&readmeURL, "readme-url", "", "redirect readme url when not found")
pflag.BoolVar(&allowHeadMethod, "allow-head-method", false, "allow head method")
pflag.Parse()
}

Expand Down Expand Up @@ -440,6 +443,10 @@ func main() {
}))
}

if allowHeadMethod {
opts = append(opts, crproxy.WithAllowHeadMethod(allowHeadMethod))
}

crp, err := crproxy.NewCRProxy(opts...)
if err != nil {
logger.Println("failed to NewCRProxy:", err)
Expand Down
37 changes: 19 additions & 18 deletions crproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"strings"
"sync"
"time"
"bytes"

"github.com/daocloud/crproxy/internal/maps"
"github.com/distribution/distribution/v3/registry/api/errcode"
Expand Down Expand Up @@ -81,6 +82,7 @@ type CRProxy struct {

privilegedFunc func(r *http.Request, info *ImageInfo) bool
redirectToOriginBlobFunc func(r *http.Request, info *ImageInfo) bool
allowHeadMethod bool
}

type Option func(c *CRProxy)
Expand Down Expand Up @@ -243,6 +245,12 @@ func WithRetry(retry int, retryInterval time.Duration) Option {
}
}

func WithAllowHeadMethod(allowHeadMethod bool) Option {
return func(c *CRProxy) {
c.allowHeadMethod = allowHeadMethod
}
}

func NewCRProxy(opts ...Option) (*CRProxy, error) {
c := &CRProxy{
challengeManager: challenge.NewSimpleManager(),
Expand Down Expand Up @@ -419,25 +427,18 @@ func emptyTagsList(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, emptyTagsList)
}

func (c *CRProxy) do(cli *http.Client, r *http.Request) (*http.Response, error) {
resp, err := cli.Do(r)
if err == nil {
return resp, nil
}

if r.Method != http.MethodHead {
return nil, err
}
var emptyBody = io.NopCloser(bytes.NewBuffer([]byte{}))

r.Method = http.MethodGet
defer func() {
r.Method = http.MethodHead
}()
resp0, err0 := cli.Do(r)
if err0 != nil {
return nil, err
}
return resp0, nil
func (c *CRProxy) do(cli *http.Client, r *http.Request) (*http.Response, error) {
if !c.allowHeadMethod && r.Method == http.MethodHead {
r.Method = http.MethodGet
defer func() {
r.Method = http.MethodHead
_ = r.Body.Close()
r.Body = emptyBody
}()
}
return cli.Do(r)
}

func (c *CRProxy) doWithAuth(cli *http.Client, r *http.Request, host string) (*http.Response, error) {
Expand Down

0 comments on commit 4f7d87a

Please sign in to comment.