2023-01-30 16:27:06 +03:00
|
|
|
package message
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-02-08 16:49:01 +03:00
|
|
|
"log/slog"
|
2023-01-30 16:27:06 +03:00
|
|
|
"net/textproto"
|
|
|
|
|
|
|
|
"github.com/mjl-/mox/dns"
|
2023-08-15 09:25:56 +03:00
|
|
|
"github.com/mjl-/mox/mlog"
|
2023-01-30 16:27:06 +03:00
|
|
|
"github.com/mjl-/mox/smtp"
|
|
|
|
)
|
|
|
|
|
|
|
|
// From extracts the address in the From-header.
|
|
|
|
//
|
|
|
|
// An RFC5322 message must have a From header.
|
|
|
|
// In theory, multiple addresses may be present. In practice zero or multiple
|
|
|
|
// From headers may be present. From returns an error if there is not exactly
|
|
|
|
// one address. This address can be used for evaluating a DMARC policy against
|
|
|
|
// SPF and DKIM results.
|
2024-03-31 16:23:53 +03:00
|
|
|
func From(elog *slog.Logger, strict bool, r io.ReaderAt, p *Part) (raddr smtp.Address, envelope *Envelope, header textproto.MIMEHeader, rerr error) {
|
2023-12-05 15:35:58 +03:00
|
|
|
log := mlog.New("message", elog)
|
|
|
|
|
2023-01-30 16:27:06 +03:00
|
|
|
// ../rfc/7489:1243
|
|
|
|
|
|
|
|
// todo: only allow utf8 if enabled in session/message?
|
|
|
|
|
2024-03-31 16:23:53 +03:00
|
|
|
var err error
|
|
|
|
if p == nil {
|
|
|
|
var pp Part
|
|
|
|
pp, err = Parse(log.Logger, strict, r)
|
|
|
|
if err != nil {
|
|
|
|
// todo: should we continue with p, perhaps headers can be parsed?
|
|
|
|
return raddr, nil, nil, fmt.Errorf("parsing message: %v", err)
|
|
|
|
}
|
|
|
|
p = &pp
|
2023-01-30 16:27:06 +03:00
|
|
|
}
|
|
|
|
header, err = p.Header()
|
|
|
|
if err != nil {
|
2023-11-27 12:34:01 +03:00
|
|
|
return raddr, nil, nil, fmt.Errorf("parsing message header: %v", err)
|
2023-01-30 16:27:06 +03:00
|
|
|
}
|
|
|
|
from := p.Envelope.From
|
|
|
|
if len(from) != 1 {
|
2023-11-27 12:34:01 +03:00
|
|
|
return raddr, nil, nil, fmt.Errorf("from header has %d addresses, need exactly 1 address", len(from))
|
2023-01-30 16:27:06 +03:00
|
|
|
}
|
|
|
|
d, err := dns.ParseDomain(from[0].Host)
|
|
|
|
if err != nil {
|
2023-11-27 12:34:01 +03:00
|
|
|
return raddr, nil, nil, fmt.Errorf("bad domain in from address: %v", err)
|
2023-01-30 16:27:06 +03:00
|
|
|
}
|
2024-03-08 23:08:40 +03:00
|
|
|
lp, err := smtp.ParseLocalpart(from[0].User)
|
|
|
|
if err != nil {
|
|
|
|
return raddr, nil, nil, fmt.Errorf("parsing localpart in from address: %v", err)
|
|
|
|
}
|
|
|
|
addr := smtp.Address{Localpart: lp, Domain: d}
|
2023-11-27 12:34:01 +03:00
|
|
|
return addr, p.Envelope, textproto.MIMEHeader(header), nil
|
2023-01-30 16:27:06 +03:00
|
|
|
}
|