aboutsummaryrefslogtreecommitdiffstats
path: root/worker/imap/connect.go
blob: 84d69fe534654b8bfccaa9f21f5ab9c6e0a8884f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package imap

import (
	"crypto/tls"
	"fmt"
	"net"
	"time"

	"git.sr.ht/~rjarry/aerc/lib"
	"git.sr.ht/~rjarry/aerc/log"
	"github.com/emersion/go-imap"
	"github.com/emersion/go-imap/client"
)

// connect establishes a new tcp connection to the imap server, logs in and
// selects the default inbox. If no error is returned, the imap client will be
// in the imap.SelectedState.
func (w *IMAPWorker) connect() (*client.Client, error) {
	var (
		conn *net.TCPConn
		err  error
		c    *client.Client
	)

	conn, err = newTCPConn(w.config.addr, w.config.connection_timeout)
	if conn == nil || err != nil {
		return nil, err
	}

	if w.config.connection_timeout > 0 {
		end := time.Now().Add(w.config.connection_timeout)
		err = conn.SetDeadline(end)
		if err != nil {
			return nil, err
		}
	}

	if w.config.keepalive_period > 0 {
		err = w.setKeepaliveParameters(conn)
		if err != nil {
			return nil, err
		}
	}

	serverName, _, _ := net.SplitHostPort(w.config.addr)
	tlsConfig := &tls.Config{ServerName: serverName}

	switch w.config.scheme {
	case "imap":
		c, err = client.New(conn)
		if err != nil {
			return nil, err
		}
		if !w.config.insecure {
			if err = c.StartTLS(tlsConfig); err != nil {
				return nil, err
			}
		}
	case "imaps":
		tlsConn := tls.Client(conn, tlsConfig)
		c, err = client.New(tlsConn)
		if err != nil {
			return nil, err
		}
	default:
		return nil, fmt.Errorf("Unknown IMAP scheme %s", w.config.scheme)
	}

	c.ErrorLog = log.ErrorLogger()

	if w.config.user != nil {
		username := w.config.user.Username()

		// TODO: 2nd parameter false if no password is set. ask for it
		// if unset.
		password, _ := w.config.user.Password()

		if w.config.oauthBearer.Enabled {
			if err := w.config.oauthBearer.Authenticate(
				username, password, c); err != nil {
				return nil, err
			}
		} else if w.config.xoauth2.Enabled {
			if err := w.config.xoauth2.Authenticate(
				username, password, w.worker.Name, c); err != nil {
				return nil, err
			}
		} else if err := c.Login(username, password); err != nil {
			return nil, err
		}
	}

	if _, err := c.Select(imap.InboxName, false); err != nil {
		return nil, err
	}

	info := make(chan *imap.MailboxInfo, 1)
	if err := c.List("", "", info); err != nil {
		return nil, fmt.Errorf("failed to retrieve delimiter: %w", err)
	}
	mailboxinfo := <-info
	w.delimiter = mailboxinfo.Delimiter
	if w.delimiter == "" {
		// just in case some implementation does not follow standards
		w.delimiter = "/"
	}

	return c, nil
}

// newTCPConn establishes a new tcp connection. Timeout will ensure that the
// function does not hang when there is no connection. If there is a timeout,
// but a valid connection is eventually returned, ensure that it is properly
// closed.
func newTCPConn(addr string, timeout time.Duration) (*net.TCPConn, error) {
	errTCPTimeout := fmt.Errorf("tcp connection timeout")

	type tcpConn struct {
		conn *net.TCPConn
		err  error
	}

	done := make(chan tcpConn)
	go func() {
		defer log.PanicHandler()
		addr, err := net.ResolveTCPAddr("tcp", addr)
		if err != nil {
			done <- tcpConn{nil, err}
			return
		}

		newConn, err := net.DialTCP("tcp", nil, addr)
		if err != nil {
			done <- tcpConn{nil, err}
			return
		}

		done <- tcpConn{newConn, nil}
	}()

	select {
	case <-time.After(timeout):
		go func() {
			defer log.PanicHandler()
			if tcpResult := <-done; tcpResult.conn != nil {
				tcpResult.conn.Close()
			}
		}()
		return nil, errTCPTimeout
	case tcpResult := <-done:
		if tcpResult.conn == nil || tcpResult.err != nil {
			return nil, tcpResult.err
		}
		return tcpResult.conn, nil
	}
}

// Set additional keepalive parameters.
// Uses new interfaces introduced in Go1.11, which let us get connection's file
// descriptor, without blocking, and therefore without uncontrolled spawning of
// threads (not goroutines, actual threads).
func (w *IMAPWorker) setKeepaliveParameters(conn *net.TCPConn) error {
	err := conn.SetKeepAlive(true)
	if err != nil {
		return err
	}
	// Idle time before sending a keepalive probe
	err = conn.SetKeepAlivePeriod(w.config.keepalive_period)
	if err != nil {
		return err
	}
	rawConn, e := conn.SyscallConn()
	if e != nil {
		return e
	}
	err = rawConn.Control(func(fdPtr uintptr) {
		fd := int(fdPtr)
		// Max number of probes before failure
		err := lib.SetTcpKeepaliveProbes(fd, w.config.keepalive_probes)
		if err != nil {
			w.worker.Errorf("cannot set tcp keepalive probes: %v", err)
		}
		// Wait time after an unsuccessful probe
		err = lib.SetTcpKeepaliveInterval(fd, w.config.keepalive_interval)
		if err != nil {
			w.worker.Errorf("cannot set tcp keepalive interval: %v", err)
		}
	})
	return err
}