From ff9ff23e5aec1d6d48824757a4054090fa176a3b Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Wed, 26 Sep 2018 07:42:03 +0200 Subject: [PATCH] fix \r\n trim for multipart lines --- internal/multipart/component.go | 18 +++++++++++++++--- internal/multipart/reader.go | 8 ++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/internal/multipart/component.go b/internal/multipart/component.go index c1f01a3..8acc47f 100644 --- a/internal/multipart/component.go +++ b/internal/multipart/component.go @@ -2,6 +2,8 @@ package multipart import ( "bufio" + "fmt" + "io" "strings" ) @@ -85,8 +87,10 @@ func (comp *Component) read(_reader *bufio.Reader, _boundary string) error { // 1. Stop on error if err != nil { // remove last CR (newline) - if string(comp.Data[len(comp.Data)-1]) == "\n" { + if strings.HasSuffix(string(comp.Data), "\n") { comp.Data = comp.Data[0 : len(comp.Data)-1] + } else if strings.HasSuffix(string(comp.Data), "\r\n") { + comp.Data = comp.Data[0 : len(comp.Data)-2] } return err } @@ -95,14 +99,22 @@ func (comp *Component) read(_reader *bufio.Reader, _boundary string) error { if strings.HasPrefix(string(line), _boundary) { // remove last CR (newline) - if string(comp.Data[len(comp.Data)-1]) == "\n" { + if strings.HasSuffix(string(comp.Data), "\n") { comp.Data = comp.Data[0 : len(comp.Data)-1] + } else if strings.HasSuffix(string(comp.Data), "\r\n") { + comp.Data = comp.Data[0 : len(comp.Data)-2] } + + // io.EOF if last boundary + if strings.Trim(string(line), " \t\r\n") == fmt.Sprintf("%s--", _boundary) { + return io.EOF + } + return nil } // 3. Ignore empty lines - if string(line) != "\n" && len(line) > 0 { + if len(strings.Trim(string(line), " \t\r\n")) > 0 { // add to header if not finished if !headerRead { diff --git a/internal/multipart/reader.go b/internal/multipart/reader.go index 4a21201..3db12cd 100644 --- a/internal/multipart/reader.go +++ b/internal/multipart/reader.go @@ -44,21 +44,21 @@ func (reader *Reader) Parse() error { /* (1) For each component (until boundary) */ for { - mpd := &Component{ + comp := &Component{ ContentType: "raw", Data: make([]byte, 0), Headers: make(map[string]string), } // 1. Read and parse data - err := mpd.read(reader.reader, reader.boundary) + err := comp.read(reader.reader, reader.boundary) // 3. Dispatch error if err != nil && err != io.EOF { return err } - name := mpd.GetHeader("name") + name := comp.GetHeader("name") if len(name) < 1 { return ErrMissingDataName } @@ -67,7 +67,7 @@ func (reader *Reader) Parse() error { return ErrDataNameConflict } - reader.Data[name] = mpd + reader.Data[name] = comp if err == io.EOF { return nil