69 lines
1.9 KiB
Go
69 lines
1.9 KiB
Go
package router
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"mime"
|
|
"net/mail"
|
|
"strings"
|
|
|
|
"github.com/emersion/go-message/textproto"
|
|
|
|
"codeberg.org/squidd/parsimony/internal/store"
|
|
)
|
|
|
|
// rewrite adds the list headers shared by every recipient and rewrites From so DMARC alignment holds.
|
|
// The body is copied byte for byte.
|
|
func rewrite(l store.List, data []byte) ([]byte, error) {
|
|
br := bufio.NewReader(bytes.NewReader(data))
|
|
h, err := textproto.ReadHeader(br)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse header: %w", err)
|
|
}
|
|
|
|
// Never trust list headers coming from outside.
|
|
for _, k := range []string{"List-Id", "List-Post", "List-Unsubscribe", "List-Unsubscribe-Post", "Precedence",
|
|
"List-Help", "List-Archive", "List-Owner", "List-Subscribe",
|
|
// The author's signature and authentication results do not survive our changes: they only confuse receivers.
|
|
"DKIM-Signature", "Authentication-Results"} {
|
|
h.Del(k)
|
|
}
|
|
for f := h.Fields(); f.Next(); {
|
|
if strings.HasPrefix(strings.ToLower(f.Key()), "arc-") {
|
|
f.Del()
|
|
}
|
|
}
|
|
|
|
id := l.Name + "." + l.Domain
|
|
// The phrase is RFC 2047 encoded when it is not ASCII; the <id> stays plain ASCII (list names and domains are).
|
|
h.Set("List-Id", fmt.Sprintf("%s <%s>", mime.QEncoding.Encode("utf-8", l.Title), id))
|
|
h.Set("List-Post", "<mailto:"+l.Address()+">")
|
|
// List-Unsubscribe is per recipient: Router.Send adds it.
|
|
h.Set("Precedence", "list")
|
|
|
|
if orig := h.Get("From"); orig != "" {
|
|
name := orig
|
|
if a, err := mail.ParseAddress(orig); err == nil {
|
|
name = a.Name
|
|
if name == "" {
|
|
name = a.Address
|
|
}
|
|
}
|
|
if h.Get("Reply-To") == "" {
|
|
h.Set("Reply-To", orig)
|
|
}
|
|
from := mail.Address{Name: name + " via " + l.Title, Address: l.Address()}
|
|
h.Set("From", from.String())
|
|
}
|
|
|
|
var out bytes.Buffer
|
|
if err := textproto.WriteHeader(&out, h); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := io.Copy(&out, br); err != nil {
|
|
return nil, err
|
|
}
|
|
return out.Bytes(), nil
|
|
}
|