2 SGBlog -- Git-backed CGI/UCSPI blogging/phlogging/gemlogging engine
3 Copyright (C) 2020-2023 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Affero General Public License as
7 published by the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU Affero General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
28 "mime/quotedprintable"
35 CTE = "Content-Transfer-Encoding"
39 func processTP(ct, cte string, body io.Reader) (io.Reader, error) {
40 _, params, err := mime.ParseMediaType(ct)
44 if c := strings.ToLower(params["charset"]); !(c == "" ||
48 return nil, errors.New("only utf-8/iso-8859-1/us-ascii charsets supported")
51 case "quoted-printable":
52 return quotedprintable.NewReader(body), nil
54 return base64.NewDecoder(base64.StdEncoding, body), nil
59 func parseEmail(msg *mail.Message) (subj string, body io.Reader, err error) {
60 subj = msg.Header.Get("Subject")
62 err = errors.New("no Subject")
65 subj, err = new(mime.WordDecoder).DecodeHeader(subj)
69 ct := msg.Header.Get(CT)
73 if strings.HasPrefix(ct, TP) {
74 body, err = processTP(ct, msg.Header.Get(CTE), msg.Body)
77 ct, params, err := mime.ParseMediaType(ct)
79 err = fmt.Errorf("can not ParseMediaType: %w", err)
82 if ct != "multipart/signed" {
83 err = errors.New("only text/plain and multipart/signed+text/plain Content-Type supported")
86 boundary := params["boundary"]
87 if len(boundary) == 0 {
88 err = errors.New("no boundary string")
91 data, err := io.ReadAll(msg.Body)
95 boundaryIdx := bytes.Index(data, []byte("--"+boundary))
96 if boundaryIdx == -1 {
97 err = errors.New("no boundary found")
100 mpr := multipart.NewReader(bytes.NewReader(data[boundaryIdx:]), boundary)
101 var part *multipart.Part
103 part, err = mpr.NextPart()
110 ct = part.Header.Get(CT)
111 if strings.HasPrefix(ct, TP) {
112 body, err = processTP(ct, part.Header.Get(CTE), part)
115 if strings.HasPrefix(ct, "multipart/mixed") {
116 _, params, err = mime.ParseMediaType(ct)
118 err = fmt.Errorf("can not ParseMediaType: %w", err)
121 boundary = params["boundary"]
122 if len(boundary) == 0 {
123 err = errors.New("no boundary string")
126 mpr := multipart.NewReader(part, boundary)
128 part, err = mpr.NextPart()
135 ct = part.Header.Get(CT)
136 if strings.HasPrefix(ct, TP) {
137 body, err = processTP(ct, part.Header.Get(CTE), part)
143 err = errors.New("no text/plain part found")