10// Record is a parsed SPF DNS record.
12// An example record for example.com:
14// v=spf1 +mx a:colo.example.com/28 -all
16 Version string // Must be "spf1".
17 Directives []Directive // An IP is evaluated against each directive until a match is found.
18 Redirect string // Modifier that redirects SPF checks to other domain after directives did not match. Optional. For "redirect=".
19 Explanation string // Modifier for creating a user-friendly error message when an IP results in status "fail".
20 Other []Modifier // Other modifiers.
23// Directive consists of a mechanism that describes how to check if an IP matches,
24// an (optional) qualifier indicating the policy for a match, and optional
25// parameters specific to the mechanism.
26type Directive struct {
27 Qualifier string // Sets the result if this directive matches. "" and "+" are "pass", "-" is "fail", "?" is "neutral", "~" is "softfail".
28 Mechanism string // "all", "include", "a", "mx", "ptr", "ip4", "ip6", "exists".
29 DomainSpec string // For include, a, mx, ptr, exists. Always in lower-case when parsed using ParseRecord.
30 IP net.IP `json:"-"` // For ip4, ip6.
31 IPstr string // Original string for IP, always with /subnet.
32 IP4CIDRLen *int // For a, mx, ip4.
33 IP6CIDRLen *int // For a, mx, ip6.
36// MechanismString returns a directive in string form for use in the Received-SPF header.
37func (d Directive) MechanismString() string {
38 s := d.Qualifier + d.Mechanism
39 if d.DomainSpec != "" {
40 s += ":" + d.DomainSpec
41 } else if d.IP != nil {
42 s += ":" + d.IP.String()
44 if d.IP4CIDRLen != nil {
45 s += fmt.Sprintf("/%d", *d.IP4CIDRLen)
47 if d.IP6CIDRLen != nil {
48 if d.Mechanism != "ip6" {
51 s += fmt.Sprintf("/%d", *d.IP6CIDRLen)
56// Modifier provides additional information for a policy.
57// "redirect" and "exp" are not represented as a Modifier but explicitly in a Record.
59 Key string // Key is case-insensitive.
63// Record returns an DNS record, to be configured as a TXT record for a domain,
64// e.g. a TXT record for example.com.
65func (r Record) Record() (string, error) {
66 b := &strings.Builder{}
68 b.WriteString(r.Version)
69 for _, d := range r.Directives {
70 b.WriteString(" " + d.MechanismString())
73 fmt.Fprintf(b, " redirect=%s", r.Redirect)
75 if r.Explanation != "" {
76 fmt.Fprintf(b, " exp=%s", r.Explanation)
78 for _, m := range r.Other {
79 fmt.Fprintf(b, " %s=%s", m.Key, m.Value)
81 return b.String(), nil
92func (e parseError) Error() string {
96// toLower lower cases bytes that are A-Z. strings.ToLower does too much. and
97// would replace invalid bytes with unicode replacement characters, which would
98// break our requirement that offsets into the original and upper case strings
99// point to the same character.
100func toLower(s string) string {
102 for i, c := range r {
103 if c >= 'A' && c <= 'Z' {
110// ParseRecord parses an SPF DNS TXT record.
111func ParseRecord(s string) (r *Record, isspf bool, rerr error) {
112 p := parser{s: s, lower: toLower(s)}
123 if err, ok := x.(parseError); ok {
140 qualifier := p.takelist("+", "-", "?", "~")
141 mechanism := p.takelist("all", "include:", "a", "mx", "ptr", "ip4:", "ip6:", "exists:")
142 if qualifier != "" && mechanism == "" {
143 p.xerrorf("expected mechanism after qualifier")
147 modifier := p.takelist("redirect=", "exp=")
150 name := p.xtakefn1(func(c rune, i int) bool {
151 alpha := c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
152 return alpha || i > 0 && (c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.')
155 v := p.xmacroString(true)
156 r.Other = append(r.Other, Modifier{name, v})
159 v := p.xdomainSpec(true)
160 modifier = strings.TrimSuffix(modifier, "=")
161 if modifier == "redirect" {
162 if r.Redirect != "" {
164 p.xerrorf("duplicate redirect modifier")
168 if modifier == "exp" {
169 if r.Explanation != "" {
171 p.xerrorf("duplicate exp modifier")
179 Qualifier: qualifier,
180 Mechanism: strings.TrimSuffix(mechanism, ":"),
185 d.DomainSpec = p.xdomainSpec(false)
188 d.DomainSpec = p.xdomainSpec(false)
192 num, _ := p.xnumber()
194 p.xerrorf("invalid ip4 cidr length %d", num)
201 num, _ := p.xnumber()
203 p.xerrorf("invalid ip6 cidr length %d", num)
209 d.DomainSpec = p.xdomainSpec(false)
212 d.IP, d.IPstr = p.xip4address()
214 num, _ := p.xnumber()
216 p.xerrorf("invalid ip4 cidr length %d", num)
219 d.IPstr += fmt.Sprintf("/%d", num)
224 d.IP, d.IPstr = p.xip6address()
226 num, _ := p.xnumber()
228 p.xerrorf("invalid ip6 cidr length %d", num)
231 d.IPstr += fmt.Sprintf("/%d", num)
236 d.DomainSpec = p.xdomainSpec(false)
238 return nil, true, fmt.Errorf("internal error, missing case for mechanism %q", d.Mechanism)
240 r.Directives = append(r.Directives, d)
245func (p *parser) xerrorf(format string, args ...any) {
246 msg := fmt.Sprintf(format, args...)
248 msg += fmt.Sprintf(" (leftover %q)", p.s[p.o:])
250 panic(parseError(msg))
253// operates on original-cased characters.
254func (p *parser) xtakefn1(fn func(rune, int) bool) string {
256 for i, c := range p.s[p.o:] {
263 p.xerrorf("need at least 1 char")
269// caller should set includingSlash to false when parsing "a" or "mx", or the / would be consumed as valid macro literal.
270func (p *parser) xdomainSpec(includingSlash bool) string {
272 // This also consumes the "domain-end" part, which we check below.
273 s := p.xmacroString(includingSlash)
275 // The ABNF says s must either end in macro-expand, or "." toplabel ["."]. The
276 // toplabel rule implies the intention is to force a valid DNS name. We cannot just
277 // check if the name is valid, because "macro-expand" is not a valid label. So we
278 // recognize the macro-expand, and check for valid toplabel otherwise, because we
279 // syntax errors must result in Permerror.
280 for _, suf := range []string{"%%", "%_", "%-", "}"} {
281 // The check for "}" assumes a "%{" precedes it...
282 if strings.HasSuffix(s, suf) {
286 tl := strings.Split(strings.TrimSuffix(s, "."), ".")
289 p.xerrorf("invalid empty toplabel")
292 for i, c := range t {
294 case c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z':
295 case c >= '0' && c <= '9':
299 p.xerrorf("bad toplabel, invalid leading dash")
302 p.xerrorf("bad toplabel, invalid trailing dash")
305 p.xerrorf("bad toplabel, invalid character")
309 p.xerrorf("bad toplabel, cannot be all digits")
314func (p *parser) xmacroString(includingSlash bool) string {
318 w := p.takelist("%{", "%%", "%_", "%-") // "macro-expand"
323 if b > ' ' && b < 0x7f && b != '%' && (includingSlash || b != '/') {
335 r += p.xtakelist("s", "l", "o", "d", "i", "p", "h", "c", "r", "t", "v") // "macro-letter"
338 if v, err := strconv.Atoi(digits); err != nil {
339 p.xerrorf("bad digits: %v", err)
341 p.xerrorf("bad digits 0 for 0 labels")
349 delimiter := p.takelist(".", "-", "+", ",", "/", "_", "=")
360func (p *parser) empty() bool {
361 return p.o >= len(p.s)
364// returns next original-cased character.
365func (p *parser) peekchar() byte {
369func (p *parser) xtakelist(l ...string) string {
370 w := p.takelist(l...)
372 p.xerrorf("no match for %v", l)
377func (p *parser) takelist(l ...string) string {
378 for _, w := range l {
379 if strings.HasPrefix(p.lower[p.o:], w) {
387// digits parses zero or more digits.
388func (p *parser) digits() string {
392 if b >= '0' && b <= '9' {
402func (p *parser) take(s string) bool {
403 if strings.HasPrefix(p.lower[p.o:], s) {
410func (p *parser) xtake(s string) string {
413 p.xerrorf("expected %q", s)
418func (p *parser) xnumber() (int, string) {
421 p.xerrorf("expected number")
426 if strings.HasPrefix(s, "0") {
427 p.xerrorf("bogus leading 0 in number")
429 v, err := strconv.Atoi(s)
431 p.xerrorf("parsing number for %q: %s", s, err)
436func (p *parser) xip4address() (net.IP, string) {
438 ip4num := func() (byte, string) {
441 p.xerrorf("bad ip4 number %d", v)
452 return net.IPv4(a, b, c, d), as + "." + bs + "." + cs + "." + ds
455func (p *parser) xip6address() (net.IP, string) {
457 // We just take in a string that has characters that IPv6 uses, then parse it.
458 s := p.xtakefn1(func(c rune, i int) bool {
459 return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' || c == ':' || c == '.'
463 p.xerrorf("ip6 address %q not valid", s)