aboutsummaryrefslogtreecommitdiffstats
path: root/worker/imap/worker.go
blob: ceff34d4568f20a38e1f20a5ae0b6b829b4390b4 (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
191
192
193
194
195
196
197
198
199
package imap

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"log"
	"net/url"
	"strings"

	"github.com/emersion/go-imap"
	"github.com/emersion/go-imap-idle"
	"github.com/emersion/go-imap/client"

	"git.sr.ht/~sircmpwn/aerc2/worker/types"
)

var errUnsupported = fmt.Errorf("unsupported command")

type imapClient struct {
	*client.Client
	*idle.IdleClient
}

type IMAPWorker struct {
	messages chan types.WorkerMessage
	actions  chan types.WorkerMessage

	config struct {
		scheme   string
		insecure bool
		addr     string
		user     *url.Userinfo
	}

	client  *imapClient
	updates chan client.Update
	logger  *log.Logger
}

func NewIMAPWorker(logger *log.Logger) *IMAPWorker {
	return &IMAPWorker{
		messages: make(chan types.WorkerMessage, 50),
		actions:  make(chan types.WorkerMessage, 50),
		updates:  make(chan client.Update, 50),
		logger:   logger,
	}
}

func (w *IMAPWorker) GetMessages() chan types.WorkerMessage {
	return w.messages
}

func (w *IMAPWorker) PostAction(msg types.WorkerMessage) {
	w.actions <- msg
}

func (w *IMAPWorker) postMessage(msg types.WorkerMessage) {
	w.logger.Printf("=> %T\n", msg)
	w.messages <- msg
}

func (w *IMAPWorker) verifyPeerCert(msg types.WorkerMessage) func(
	rawCerts [][]byte, _ [][]*x509.Certificate) error {

	return func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
		pool := x509.NewCertPool()
		for _, rawCert := range rawCerts {
			cert, err := x509.ParseCertificate(rawCert)
			if err != nil {
				return err
			}
			pool.AddCert(cert)
		}

		request := types.ApproveCertificate{
			Message:  types.RespondTo(msg),
			CertPool: pool,
		}
		w.postMessage(request)

		response := <-w.actions
		if response.InResponseTo() != request {
			return fmt.Errorf("Expected UI to answer cert request")
		}
		switch response.(type) {
		case types.Ack:
			return nil
		case types.Disconnect:
			return fmt.Errorf("UI rejected certificate")
		default:
			return fmt.Errorf("Expected UI to answer cert request")
		}
	}
}

func (w *IMAPWorker) handleMessage(msg types.WorkerMessage) error {
	switch msg := msg.(type) {
	case types.Ping:
		// No-op
	case types.Configure:
		u, err := url.Parse(msg.Config.Source)
		if err != nil {
			return err
		}

		w.config.scheme = u.Scheme
		if strings.HasSuffix(w.config.scheme, "+insecure") {
			w.config.scheme = strings.TrimSuffix(w.config.scheme, "+insecure")
			w.config.insecure = true
		}

		w.config.addr = u.Host
		if !strings.ContainsRune(w.config.addr, ':') {
			w.config.addr += ":" + u.Scheme
		}

		w.config.scheme = u.Scheme
		w.config.user = u.User
	case types.Connect:
		var (
			c   *client.Client
			err error
		)
		tlsConfig := &tls.Config{
			InsecureSkipVerify:    true,
			VerifyPeerCertificate: w.verifyPeerCert(&msg),
		}
		switch w.config.scheme {
		case "imap":
			c, err = client.Dial(w.config.addr)
			if err != nil {
				return err
			}

			if !w.config.insecure {
				if err := c.StartTLS(tlsConfig); err != nil {
					return err
				}
			}
		case "imaps":
			c, err = client.DialTLS(w.config.addr, tlsConfig)
			if err != nil {
				return err
			}
		default:
			return fmt.Errorf("Unknown IMAP scheme %s", w.config.scheme)
		}

		if w.config.user != nil {
			username := w.config.user.Username()
			password, hasPassword := w.config.user.Password()
			if !hasPassword {
				// TODO: ask password
			}
			if err := c.Login(username, password); err != nil {
				return err
			}
		}

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

		c.Updates = w.updates
		w.client = &imapClient{c, idle.NewClient(c)}

		// TODO: don't idle right away
		go w.client.IdleWithFallback(nil, 0)
	default:
		return errUnsupported
	}
	return nil
}

func (w *IMAPWorker) Run() {
	for {
		select {
		case msg := <-w.actions:
			w.logger.Printf("<= %T\n", msg)
			if err := w.handleMessage(msg); err == errUnsupported {
				w.postMessage(types.Unsupported{
					Message: types.RespondTo(msg),
				})
			} else if err != nil {
				w.postMessage(types.Error{
					Message: types.RespondTo(msg),
					Error:   err,
				})
			} else {
				w.postMessage(types.Ack{
					Message: types.RespondTo(msg),
				})
			}
		case update := <-w.updates:
			w.logger.Printf("[= %T", update)
		}
	}
}