2023-01-15 16:14:19 +01:00
|
|
|
// SPDX-FileCopyrightText: 2022-2023 The go-mail Authors
|
2022-08-14 12:07:59 +02:00
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
2022-08-14 12:06:26 +02:00
|
|
|
package mail
|
|
|
|
|
2022-09-08 11:47:11 +02:00
|
|
|
import (
|
2024-08-16 10:16:53 +02:00
|
|
|
"errors"
|
2022-09-08 11:47:11 +02:00
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2022-09-08 15:43:14 +02:00
|
|
|
// ErrNoOutWriter is an error message that should be used if a Base64LineBreaker has no out io.Writer set
|
|
|
|
const ErrNoOutWriter = "no io.Writer set for Base64LineBreaker"
|
|
|
|
|
2022-08-14 12:06:26 +02:00
|
|
|
// Base64LineBreaker is a io.WriteCloser that writes Base64 encoded data streams
|
|
|
|
// with line breaks at a given line length
|
|
|
|
type Base64LineBreaker struct {
|
|
|
|
line [MaxBodyLength]byte
|
|
|
|
used int
|
|
|
|
out io.Writer
|
|
|
|
}
|
|
|
|
|
2024-02-24 21:38:20 +01:00
|
|
|
var newlineBytes = []byte(SingleNewLine)
|
2022-08-14 12:06:26 +02:00
|
|
|
|
|
|
|
// Write writes the data stream and inserts a SingleNewLine when the maximum
|
|
|
|
// line length is reached
|
2024-02-24 21:38:20 +01:00
|
|
|
func (l *Base64LineBreaker) Write(data []byte) (numBytes int, err error) {
|
2022-09-08 11:47:11 +02:00
|
|
|
if l.out == nil {
|
2024-08-16 10:16:53 +02:00
|
|
|
err = errors.New(ErrNoOutWriter)
|
2022-09-08 15:40:42 +02:00
|
|
|
return
|
2022-09-08 11:47:11 +02:00
|
|
|
}
|
2024-02-24 21:38:20 +01:00
|
|
|
if l.used+len(data) < MaxBodyLength {
|
|
|
|
copy(l.line[l.used:], data)
|
|
|
|
l.used += len(data)
|
|
|
|
return len(data), nil
|
2022-08-14 12:06:26 +02:00
|
|
|
}
|
|
|
|
|
2024-02-24 21:38:20 +01:00
|
|
|
numBytes, err = l.out.Write(l.line[0:l.used])
|
2022-08-14 12:06:26 +02:00
|
|
|
if err != nil {
|
2022-09-08 15:40:42 +02:00
|
|
|
return
|
2022-08-14 12:06:26 +02:00
|
|
|
}
|
|
|
|
excess := MaxBodyLength - l.used
|
|
|
|
l.used = 0
|
|
|
|
|
2024-02-24 21:38:20 +01:00
|
|
|
numBytes, err = l.out.Write(data[0:excess])
|
2022-08-14 12:06:26 +02:00
|
|
|
if err != nil {
|
2022-09-08 15:40:42 +02:00
|
|
|
return
|
2022-08-14 12:06:26 +02:00
|
|
|
}
|
|
|
|
|
2024-02-24 21:38:20 +01:00
|
|
|
numBytes, err = l.out.Write(newlineBytes)
|
2022-08-14 12:06:26 +02:00
|
|
|
if err != nil {
|
2022-09-08 15:40:42 +02:00
|
|
|
return
|
2022-08-14 12:06:26 +02:00
|
|
|
}
|
|
|
|
|
2024-02-24 21:38:20 +01:00
|
|
|
return l.Write(data[excess:])
|
2022-08-14 12:06:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the Base64LineBreaker and writes any access data that is still
|
|
|
|
// unwritten in memory
|
|
|
|
func (l *Base64LineBreaker) Close() (err error) {
|
|
|
|
if l.used > 0 {
|
|
|
|
_, err = l.out.Write(l.line[0:l.used])
|
|
|
|
if err != nil {
|
2022-09-08 15:40:42 +02:00
|
|
|
return
|
2022-08-14 12:06:26 +02:00
|
|
|
}
|
2024-02-24 21:38:20 +01:00
|
|
|
_, err = l.out.Write(newlineBytes)
|
2022-08-14 12:06:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|