package digest

import (
	
	
	
	
)

// cchal is a cached challenge and the number of times it's been used.
type cchal struct {
	c *Challenge
	n int
}

// Transport implements http.RoundTripper
type Transport struct {
	Username string
	Password string

	// Digest computes the digest credentials.
	// If nil, the Digest function is used.
	Digest func(*http.Request, *Challenge, Options) (*Credentials, error)

	// FindChallenge extracts the challenge from the request headers.
	// If nil, the FindChallenge function is used.
	FindChallenge func(http.Header) (*Challenge, error)

	// Transport specifies the mechanism by which individual
	// HTTP requests are made.
	// If nil, DefaultTransport is used.
	Transport http.RoundTripper

	// Jar specifies the cookie jar.
	//
	// The Jar is used to insert relevant cookies into every
	// outbound Request and is updated with the cookie values
	// of every inbound Response. The Jar is consulted for every
	// redirect that the Client follows.
	//
	// If Jar is nil, cookies are only sent if they are explicitly
	// set on the Request.
	Jar http.CookieJar

	// NoReuse prevents the transport from reusing challenges.
	NoReuse bool

	// Probe discovers the challenge with a bodyless request before streaming the
	// body, so it's only sent once authenticated — for servers that reject the
	// unauthenticated request without draining the body. Applies only when uncached.
	Probe bool

	// cache of challenges indexed by host
	cache   map[string]*cchal
	cacheMu sync.Mutex
}

// save parses the digest challenge from the response
// and adds it to the cache
func ( *Transport) ( *http.Response) error {
	// save cookies
	if .Jar != nil {
		.Jar.SetCookies(.Request.URL, .Cookies())
	}
	// find and save digest challenge
	 := .FindChallenge
	if  == nil {
		 = FindChallenge
	}
	,  := (.Header)
	.cacheMu.Lock()
	defer .cacheMu.Unlock()
	if .cache == nil {
		.cache = map[string]*cchal{}
	}
	// TODO: if the challenge contains a domain, we should be using that
	//       to match against outgoing requests. We're currently ignoring
	//       it and just matching the hostname. That being said, none of
	//       the major browsers respect the domain either.
	 := .Request.URL.Hostname()
	if  != nil {
		// if save is being invoked, the existing cached challenge didn't work
		delete(.cache, )
		return 
	}
	.cache[] = &cchal{c: }
	return nil
}

// digest creates credentials from the cached challenge
func ( *Transport) ( *http.Request,  *Challenge,  int) (*Credentials, error) {
	 := Options{
		Method:   .Method,
		URI:      .URL.RequestURI(),
		GetBody:  .GetBody,
		Count:    ,
		Username: .Username,
		Password: .Password,
	}
	if .Digest != nil {
		return .Digest(, , )
	}
	return Digest(, )
}

// challenge returns a cached challenge and count for the provided request
func ( *Transport) ( *http.Request) (*Challenge, int, bool) {
	.cacheMu.Lock()
	defer .cacheMu.Unlock()
	 := .URL.Hostname()
	,  := .cache[]
	if ! {
		return nil, 0, false
	}
	if .NoReuse {
		delete(.cache, )
	}
	.n++
	return .c, .n, true
}

// prepare sets the Authorization header from a cached challenge if one exists.
// It reports whether the caller should send a bodyless probe first (Probe set,
// request has a body, no challenge cached yet).
func ( *Transport) ( *http.Request) (bool, error) {
	// add cookies
	if .Jar != nil {
		for ,  := range .Jar.Cookies(.URL) {
			.AddCookie()
		}
	}
	// add auth
	, ,  := .challenge()
	if ! {
		// no cached challenge yet: probe bodyless first when configured
		 := .Body != nil && .Body != http.NoBody
		return .Probe && , nil
	}
	,  := .digest(, , )
	if  != nil {
		return false, 
	}
	if  != nil {
		.Header.Set("Authorization", .String())
	}
	return false, nil
}

// RoundTrip will try to authorize the request using a cached challenge.
// If that doesn't work and we receive a 401, we'll try again using that challenge.
func ( *Transport) ( *http.Request) (*http.Response, error) {
	// use the configured transport if there is one
	 := .Transport
	if  == nil {
		 = http.DefaultTransport
	}
	// don't modify the original request
	,  := cloner()
	if  != nil {
		return nil, 
	}
	// make a copy of the request
	,  := ()
	if  != nil {
		return nil, 
	}
	// prepare the first request using a cached challenge
	,  := .prepare()
	if  != nil {
		return nil, 
	}
	// probe bodyless so the body is only streamed on the authenticated retry
	if  {
		.Body = nil
		.ContentLength = 0
		.GetBody = nil
	}
	// the first request will either succeed or return a 401
	,  := .RoundTrip()
	if  != nil {
		return , 
	}
	if .StatusCode != http.StatusUnauthorized {
		if ! {
			return , nil
		}
		// a probe response isn't valid for the caller since the body was
		// stripped; discard it and send the real request as-is
		_, _ = io.Copy(io.Discard, .Body)
		_ = .Body.Close()
		,  := ()
		if  != nil {
			return nil, 
		}
		return .RoundTrip()
	}
	// drain and close the first message body
	_, _ = io.Copy(io.Discard, .Body)
	_ = .Body.Close()
	// save the challenge for future use
	if  := .save();  != nil {
		if  == ErrNoChallenge {
			return , nil
		}
		return nil, 
	}
	// make a second copy of the request
	,  := ()
	if  != nil {
		return nil, 
	}
	// prepare the second request based on the new challenge
	if ,  := .prepare();  != nil {
		return nil, 
	}
	return .RoundTrip()
}

// CloseIdleConnections delegates the call to the underlying transport.
func ( *Transport) () {
	 := .Transport
	if  == nil {
		 = http.DefaultTransport
	}
	type  interface {
		()
	}
	if ,  := .();  {
		.()
	}
}

// cloner returns a function which makes clones of the provided request
func cloner( *http.Request) (func() (*http.Request, error), error) {
	 := .GetBody
	// if there's no GetBody function set we have to copy the body
	// into memory to use for future clones
	if  == nil {
		if .Body == nil || .Body == http.NoBody {
			 = func() (io.ReadCloser, error) {
				return http.NoBody, nil
			}
		} else {
			,  := io.ReadAll(.Body)
			if  != nil {
				return nil, 
			}
			if  := .Body.Close();  != nil {
				return nil, 
			}
			 = func() (io.ReadCloser, error) {
				return io.NopCloser(bytes.NewReader()), nil
			}
		}
	}
	return func() (*http.Request, error) {
		 := .Clone(.Context())
		,  := ()
		if  != nil {
			return nil, 
		}
		.Body = 
		.GetBody = 
		return , nil
	}, nil
}