summaryrefslogtreecommitdiff
path: root/libgo/go/mime/multipart/multipart.go
blob: 1d855c74c9d493c41b348349354ebc46a4c110d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//

/*
Package multipart implements MIME multipart parsing, as defined in RFC
2046.

The implementation is sufficient for HTTP (RFC 2388) and the multipart
bodies generated by popular browsers.
*/
package multipart

import (
	"bufio"
	"bytes"
	"io"
	"mime"
	"os"
	"regexp"
	"strings"
)

var headerRegexp *regexp.Regexp = regexp.MustCompile("^([a-zA-Z0-9\\-]+): *([^\r\n]+)")

// Reader is an iterator over parts in a MIME multipart body.
// Reader's underlying parser consumes its input as needed.  Seeking
// isn't supported.
type Reader interface {
	// NextPart returns the next part in the multipart, or (nil,
	// nil) on EOF.  An error is returned if the underlying reader
	// reports errors, or on truncated or otherwise malformed
	// input.
	NextPart() (*Part, os.Error)
}

// A Part represents a single part in a multipart body.
type Part struct {
	// The headers of the body, if any, with the keys canonicalized
	// in the same fashion that the Go http.Request headers are.
	// i.e. "foo-bar" changes case to "Foo-Bar"
	Header map[string]string

	buffer *bytes.Buffer
	mr     *multiReader
}

// FormName returns the name parameter if p has a Content-Disposition
// of type "form-data".  Otherwise it returns the empty string.
func (p *Part) FormName() string {
	// See http://tools.ietf.org/html/rfc2183 section 2 for EBNF
	// of Content-Disposition value format.
	v, ok := p.Header["Content-Disposition"]
	if !ok {
		return ""
	}
	d, params := mime.ParseMediaType(v)
	if d != "form-data" {
		return ""
	}
	return params["name"]
}

// NewReader creates a new multipart Reader reading from r using the
// given MIME boundary.
func NewReader(reader io.Reader, boundary string) Reader {
	return &multiReader{
		boundary:     boundary,
		dashBoundary: "--" + boundary,
		endLine:      "--" + boundary + "--",
		bufReader:    bufio.NewReader(reader),
	}
}

// Implementation ....

type devNullWriter bool

func (*devNullWriter) Write(p []byte) (n int, err os.Error) {
	return len(p), nil
}

var devNull = devNullWriter(false)

func newPart(mr *multiReader) (bp *Part, err os.Error) {
	bp = new(Part)
	bp.Header = make(map[string]string)
	bp.mr = mr
	bp.buffer = new(bytes.Buffer)
	if err = bp.populateHeaders(); err != nil {
		bp = nil
	}
	return
}

func (bp *Part) populateHeaders() os.Error {
	for {
		line, err := bp.mr.bufReader.ReadString('\n')
		if err != nil {
			return err
		}
		if line == "\n" || line == "\r\n" {
			return nil
		}
		if matches := headerRegexp.FindStringSubmatch(line); len(matches) == 3 {
			key := matches[1]
			value := matches[2]
			// TODO: canonicalize headers ala http.Request.Header?
			bp.Header[key] = value
			continue
		}
		return os.NewError("Unexpected header line found parsing multipart body")
	}
	panic("unreachable")
}

// Read reads the body of a part, after its headers and before the
// next part (if any) begins.
func (bp *Part) Read(p []byte) (n int, err os.Error) {
	for {
		if bp.buffer.Len() >= len(p) {
			// Internal buffer of unconsumed data is large enough for
			// the read request.  No need to parse more at the moment.
			break
		}
		if !bp.mr.ensureBufferedLine() {
			return 0, io.ErrUnexpectedEOF
		}
		if bp.mr.bufferedLineIsBoundary() {
			// Don't consume this line
			break
		}

		// Write all of this line, except the final CRLF
		s := *bp.mr.bufferedLine
		if strings.HasSuffix(s, "\r\n") {
			bp.mr.consumeLine()
			if !bp.mr.ensureBufferedLine() {
				return 0, io.ErrUnexpectedEOF
			}
			if bp.mr.bufferedLineIsBoundary() {
				// The final \r\n isn't ours.  It logically belongs
				// to the boundary line which follows.
				bp.buffer.WriteString(s[0 : len(s)-2])
			} else {
				bp.buffer.WriteString(s)
			}
			break
		}
		if strings.HasSuffix(s, "\n") {
			bp.buffer.WriteString(s)
			bp.mr.consumeLine()
			continue
		}
		return 0, os.NewError("multipart parse error during Read; unexpected line: " + s)
	}
	return bp.buffer.Read(p)
}

func (bp *Part) Close() os.Error {
	io.Copy(&devNull, bp)
	return nil
}

type multiReader struct {
	boundary     string
	dashBoundary string // --boundary
	endLine      string // --boundary--

	bufferedLine *string

	bufReader   *bufio.Reader
	currentPart *Part
	partsRead   int
}

func (mr *multiReader) eof() bool {
	return mr.bufferedLine == nil &&
		!mr.readLine()
}

func (mr *multiReader) readLine() bool {
	line, err := mr.bufReader.ReadString('\n')
	if err != nil {
		// TODO: care about err being EOF or not?
		return false
	}
	mr.bufferedLine = &line
	return true
}

func (mr *multiReader) bufferedLineIsBoundary() bool {
	return strings.HasPrefix(*mr.bufferedLine, mr.dashBoundary)
}

func (mr *multiReader) ensureBufferedLine() bool {
	if mr.bufferedLine == nil {
		return mr.readLine()
	}
	return true
}

func (mr *multiReader) consumeLine() {
	mr.bufferedLine = nil
}

func (mr *multiReader) NextPart() (*Part, os.Error) {
	if mr.currentPart != nil {
		mr.currentPart.Close()
	}

	for {
		if mr.eof() {
			return nil, io.ErrUnexpectedEOF
		}

		if isBoundaryDelimiterLine(*mr.bufferedLine, mr.dashBoundary) {
			mr.consumeLine()
			mr.partsRead++
			bp, err := newPart(mr)
			if err != nil {
				return nil, err
			}
			mr.currentPart = bp
			return bp, nil
		}

		if hasPrefixThenNewline(*mr.bufferedLine, mr.endLine) {
			mr.consumeLine()
			// Expected EOF (no error)
			return nil, nil
		}

		if mr.partsRead == 0 {
			// skip line
			mr.consumeLine()
			continue
		}

		return nil, os.NewError("Unexpected line in Next().")
	}
	panic("unreachable")
}

func isBoundaryDelimiterLine(line, dashPrefix string) bool {
	// http://tools.ietf.org/html/rfc2046#section-5.1
	//   The boundary delimiter line is then defined as a line
	//   consisting entirely of two hyphen characters ("-",
	//   decimal value 45) followed by the boundary parameter
	//   value from the Content-Type header field, optional linear
	//   whitespace, and a terminating CRLF.
	if !strings.HasPrefix(line, dashPrefix) {
		return false
	}
	if strings.HasSuffix(line, "\r\n") {
		return onlyHorizontalWhitespace(line[len(dashPrefix) : len(line)-2])
	}
	// Violate the spec and also support newlines without the
	// carriage return...
	if strings.HasSuffix(line, "\n") {
		return onlyHorizontalWhitespace(line[len(dashPrefix) : len(line)-1])
	}
	return false
}

func onlyHorizontalWhitespace(s string) bool {
	for i := 0; i < len(s); i++ {
		if s[i] != ' ' && s[i] != '\t' {
			return false
		}
	}
	return true
}

func hasPrefixThenNewline(s, prefix string) bool {
	return strings.HasPrefix(s, prefix) &&
		(len(s) == len(prefix)+1 && strings.HasSuffix(s, "\n") ||
			len(s) == len(prefix)+2 && strings.HasSuffix(s, "\r\n"))
}