10 "github.com/mjl-/mox/dns"
11 "github.com/mjl-/mox/mlog"
14// DialHook can be used during tests to override the regular dialer from being used.
15var DialHook func(ctx context.Context, dialer Dialer, timeout time.Duration, addr string, laddr net.Addr) (net.Conn, error)
17func dial(ctx context.Context, dialer Dialer, timeout time.Duration, addr string, laddr net.Addr) (net.Conn, error) {
18 // todo: see if we can remove this function and DialHook in favor of the Dialer interface.
21 return DialHook(ctx, dialer, timeout, addr, laddr)
24 // If this is a net.Dialer, use its settings and add the timeout and localaddr.
25 // This is the typical case, but SOCKS5 support can use a different dialer.
26 if d, ok := dialer.(*net.Dialer); ok {
30 return nd.DialContext(ctx, "tcp", addr)
32 return dialer.DialContext(ctx, "tcp", addr)
35// Dialer is used to dial mail servers, an interface to facilitate testing.
36type Dialer interface {
37 DialContext(ctx context.Context, network, addr string) (c net.Conn, err error)
40// Dial connects to host by dialing ips, taking previous attempts in dialedIPs into
41// accounts (for greylisting, blocklisting and ipv4/ipv6).
43// If the previous attempt used IPv4, this attempt will use IPv6 (useful in case
44// one of the IPs is in a DNSBL).
46// The second attempt for an address family we prefer the same IP as earlier, to
47// increase our chances if remote is doing greylisting.
49// Dial updates dialedIPs, callers may want to save it so it can be taken into
50// account for future delivery attempts.
52// The first matching protocol family from localIPs is set for the local side
53// of the TCP connection.
54func Dial(ctx context.Context, elog *slog.Logger, dialer Dialer, host dns.IPDomain, ips []net.IP, port int, dialedIPs map[string][]net.IP, localIPs []net.IP) (conn net.Conn, ip net.IP, rerr error) {
55 log := mlog.New("smtpclient", elog)
56 timeout := 30 * time.Second
57 if deadline, ok := ctx.Deadline(); ok && len(ips) > 0 {
58 timeout = time.Until(deadline) / time.Duration(len(ips))
63 for _, ip := range ips {
64 addr := net.JoinHostPort(ip.String(), fmt.Sprintf("%d", port))
65 log.Debug("dialing host", slog.String("addr", addr))
67 for _, lip := range localIPs {
68 ipIs4 := ip.To4() != nil
69 lipIs4 := lip.To4() != nil
71 laddr = &net.TCPAddr{IP: lip}
75 conn, err := dial(ctx, dialer, timeout, addr, laddr)
77 log.Debug("connected to host",
78 slog.Any("host", host),
79 slog.String("addr", addr),
80 slog.Any("laddr", laddr))
82 dialedIPs[name] = append(dialedIPs[name], ip)
85 log.Debugx("connection attempt", err,
86 slog.Any("host", host),
87 slog.String("addr", addr),
88 slog.Any("laddr", laddr))
92 // todo: possibly return all errors joined?
93 return nil, lastIP, lastErr