Browse Source

server: close response body on error (#6986)

This change closes the response body when an error occurs in
makeRequestWithRetry. Previously, the first, non-200 response body was
not closed before reattempting the request. This change ensures that
the response body is closed in all cases where an error occurs,
preventing leaks of file descriptors.

Fixes #6974
Blake Mizerany 7 months ago
parent
commit
03608cb46e
1 changed files with 4 additions and 0 deletions
  1. 4 0
      server/images.go

+ 4 - 0
server/images.go

@@ -1025,6 +1025,8 @@ func makeRequestWithRetry(ctx context.Context, method string, requestURL *url.UR
 
 
 		switch {
 		switch {
 		case resp.StatusCode == http.StatusUnauthorized:
 		case resp.StatusCode == http.StatusUnauthorized:
+			resp.Body.Close()
+
 			// Handle authentication error with one retry
 			// Handle authentication error with one retry
 			challenge := parseRegistryChallenge(resp.Header.Get("www-authenticate"))
 			challenge := parseRegistryChallenge(resp.Header.Get("www-authenticate"))
 			token, err := getAuthorizationToken(ctx, challenge)
 			token, err := getAuthorizationToken(ctx, challenge)
@@ -1040,8 +1042,10 @@ func makeRequestWithRetry(ctx context.Context, method string, requestURL *url.UR
 				}
 				}
 			}
 			}
 		case resp.StatusCode == http.StatusNotFound:
 		case resp.StatusCode == http.StatusNotFound:
+			resp.Body.Close()
 			return nil, os.ErrNotExist
 			return nil, os.ErrNotExist
 		case resp.StatusCode >= http.StatusBadRequest:
 		case resp.StatusCode >= http.StatusBadRequest:
+			defer resp.Body.Close()
 			responseBody, err := io.ReadAll(resp.Body)
 			responseBody, err := io.ReadAll(resp.Body)
 			if err != nil {
 			if err != nil {
 				return nil, fmt.Errorf("%d: %s", resp.StatusCode, err)
 				return nil, fmt.Errorf("%d: %s", resp.StatusCode, err)