Skip to content

Commit a629399

Browse files
mime/multipart: quote boundary in Content-Type if necessary
Fixes #26532 Change-Id: Ic086c90503c7b24982f947c828c7ccf016ddbf69 Reviewed-on: https://go-review.googlesource.com/c/154120 Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 784d810 commit a629399

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/mime/multipart/writer.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,13 @@ func (w *Writer) SetBoundary(boundary string) error {
7272
// FormDataContentType returns the Content-Type for an HTTP
7373
// multipart/form-data with this Writer's Boundary.
7474
func (w *Writer) FormDataContentType() string {
75-
return "multipart/form-data; boundary=" + w.boundary
75+
b := w.boundary
76+
// We must quote the boundary if it contains any of the
77+
// tspecials characters defined by RFC 2045, or space.
78+
if strings.ContainsAny(b, `()<>@,;:\"/[]?= `) {
79+
b = `"` + b + `"`
80+
}
81+
return "multipart/form-data; boundary=" + b
7682
}
7783

7884
func randomBoundary() string {

src/mime/multipart/writer_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package multipart
77
import (
88
"bytes"
99
"io/ioutil"
10+
"mime"
1011
"net/textproto"
1112
"strings"
1213
"testing"
@@ -94,6 +95,7 @@ func TestWriterSetBoundary(t *testing.T) {
9495
{"my-separator", true},
9596
{"with space", true},
9697
{"badspace ", false},
98+
{"(boundary)", true},
9799
}
98100
for i, tt := range tests {
99101
var b bytes.Buffer
@@ -107,6 +109,17 @@ func TestWriterSetBoundary(t *testing.T) {
107109
if got != tt.b {
108110
t.Errorf("boundary = %q; want %q", got, tt.b)
109111
}
112+
113+
ct := w.FormDataContentType()
114+
mt, params, err := mime.ParseMediaType(ct)
115+
if err != nil {
116+
t.Errorf("could not parse Content-Type %q: %v", ct, err)
117+
} else if mt != "multipart/form-data" {
118+
t.Errorf("unexpected media type %q; want %q", mt, "multipart/form-data")
119+
} else if b := params["boundary"]; b != tt.b {
120+
t.Errorf("unexpected boundary parameter %q; want %q", b, tt.b)
121+
}
122+
110123
w.Close()
111124
wantSub := "\r\n--" + tt.b + "--\r\n"
112125
if got := b.String(); !strings.Contains(got, wantSub) {

0 commit comments

Comments
 (0)