| 1 |
package cryptoutil |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"errors" |
| 6 |
"io" |
| 7 |
"strings" |
| 8 |
|
| 9 |
"git.sr.ht/~rjarry/aerc/app" |
| 10 |
"git.sr.ht/~rjarry/aerc/lib/rfc822" |
| 11 |
"github.com/emersion/go-message/mail" |
| 12 |
) |
| 13 |
|
| 14 |
func Cleartext(r io.Reader, header mail.Header) ([]byte, error) { |
| 15 |
msg, err := app.CryptoProvider().Decrypt( |
| 16 |
rfc822.NewCRLFReader(r), app.DecryptKeys) |
| 17 |
if err != nil { |
| 18 |
return nil, errors.New("decrypt error") |
| 19 |
} |
| 20 |
full, err := createMessage(header, msg.Body) |
| 21 |
if err != nil { |
| 22 |
return nil, errors.New("failed to create decrypted message") |
| 23 |
} |
| 24 |
return full, nil |
| 25 |
} |
| 26 |
|
| 27 |
func createMessage(header mail.Header, body io.Reader) ([]byte, error) { |
| 28 |
e, err := rfc822.ReadMessage(body) |
| 29 |
if err != nil { |
| 30 |
return nil, err |
| 31 |
} |
| 32 |
|
| 33 |
// copy the header values from the "decrypted body". This should set |
| 34 |
// the correct content type. |
| 35 |
hf := e.Header.Fields() |
| 36 |
for hf.Next() { |
| 37 |
header.Set(hf.Key(), hf.Value()) |
| 38 |
} |
| 39 |
|
| 40 |
ctype, params, err := header.ContentType() |
| 41 |
if err != nil { |
| 42 |
return nil, err |
| 43 |
} |
| 44 |
|
| 45 |
// in case there remains a multipart/{encrypted,signed} content type, |
| 46 |
// manually correct them to multipart/mixed as a fallback. |
| 47 |
ct := strings.ToLower(ctype) |
| 48 |
if strings.Contains(ct, "multipart/encrypted") || |
| 49 |
strings.Contains(ct, "multipart/signed") { |
| 50 |
delete(params, "protocol") |
| 51 |
delete(params, "micalg") |
| 52 |
header.SetContentType("multipart/mixed", params) |
| 53 |
} |
| 54 |
|
| 55 |
// a SingleInlineWriter is sufficient since the "decrypted body" |
| 56 |
// already contains the proper boundaries of the parts; we just want to |
| 57 |
// combine it with the headers. |
| 58 |
var message bytes.Buffer |
| 59 |
w, err := mail.CreateSingleInlineWriter(&message, header) |
| 60 |
if err != nil { |
| 61 |
return nil, err |
| 62 |
} |
| 63 |
if _, err := io.Copy(w, e.Body); err != nil { |
| 64 |
return nil, err |
| 65 |
} |
| 66 |
w.Close() |
| 67 |
|
| 68 |
return message.Bytes(), nil |
| 69 |
} |