aboutsummaryrefslogtreecommitdiffstats
path: root/lib/crypto/util/cleartext.go
blob: fe6faa89acabba29d14f2ab495c9431cb1b2a3a5 (plain) (blame)
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
package cryptoutil

import (
	"bytes"
	"errors"
	"io"
	"strings"

	"git.sr.ht/~rjarry/aerc/app"
	"git.sr.ht/~rjarry/aerc/lib/rfc822"
	"github.com/emersion/go-message/mail"
)

func Cleartext(r io.Reader, header mail.Header) ([]byte, error) {
	msg, err := app.CryptoProvider().Decrypt(
		rfc822.NewCRLFReader(r), app.DecryptKeys)
	if err != nil {
		return nil, errors.New("decrypt error")
	}
	full, err := createMessage(header, msg.Body)
	if err != nil {
		return nil, errors.New("failed to create decrypted message")
	}
	return full, nil
}

func createMessage(header mail.Header, body io.Reader) ([]byte, error) {
	e, err := rfc822.ReadMessage(body)
	if err != nil {
		return nil, err
	}

	// copy the header values from the "decrypted body". This should set
	// the correct content type.
	hf := e.Header.Fields()
	for hf.Next() {
		header.Set(hf.Key(), hf.Value())
	}

	ctype, params, err := header.ContentType()
	if err != nil {
		return nil, err
	}

	// in case there remains a multipart/{encrypted,signed} content type,
	// manually correct them to multipart/mixed as a fallback.
	ct := strings.ToLower(ctype)
	if strings.Contains(ct, "multipart/encrypted") ||
		strings.Contains(ct, "multipart/signed") {
		delete(params, "protocol")
		delete(params, "micalg")
		header.SetContentType("multipart/mixed", params)
	}

	// a SingleInlineWriter is sufficient since the "decrypted body"
	// already contains the proper boundaries of the parts; we just want to
	// combine it with the headers.
	var message bytes.Buffer
	w, err := mail.CreateSingleInlineWriter(&message, header)
	if err != nil {
		return nil, err
	}
	if _, err := io.Copy(w, e.Body); err != nil {
		return nil, err
	}
	w.Close()

	return message.Bytes(), nil
}