golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.03k stars 17.54k forks source link

mime: handling invalid mime media parameters #19498

Closed neganovalexey closed 7 years ago

neganovalexey commented 7 years ago

Sometimes it's necessary to deal with emails that do not follow the specification; in particular, it's possible to download such email via gmail. When Golang standard library handle invalid mime media parameters, it returns nils and error, although there is a valid media type, which may be returned. If this behavior changes, it may not affect any existing programs, but it will help to parse some emails.

I suggest to change file src/mime/mediatype.go as follows:

diff --git a/mediatype.go b/mediatype.go
index 4383431..758d621 100644
--- a/mediatype.go
+++ b/mediatype.go
@@ -94,6 +94,9 @@ func checkMediaTypeDisposition(s string) error {
    return nil
 }

+// ErrInvalidMediaParameter means that mime media parameter list is invalid
+var ErrInvalidMediaParameter = errors.New("mime: invalid media parameter")
+
 // ParseMediaType parses a media type value and any optional
 // parameters, per RFC 1521.  Media types are the values in
 // Content-Type and Content-Disposition headers (RFC 2183).
@@ -134,7 +137,7 @@ func ParseMediaType(v string) (mediatype string, params map[string]string, err e
                return
            }
            // Parse error.
-           return "", nil, errors.New("mime: invalid media parameter")
+           return mediatype, nil, ErrInvalidMediaParameter
        }

        pmap := params
@@ -368,4 +371,3 @@ func unhex(c byte) byte {
    }
    return 0
 }
-
-- 
2.7.4
ALTree commented 7 years ago

Can you edit your message so that it includes the proposed API change (instead of putting the change in an attachment)?

neganovalexey commented 7 years ago

OK

rsc commented 7 years ago

@bradfitz says yes. We will need to document the new behavior; unclear we need the new error variable. I'd leave that out.

rsc commented 7 years ago

CL welcome.

gopherbot commented 7 years ago

CL https://golang.org/cl/38190 mentions this issue.