1package imapclient
2
3import (
4 "bufio"
5 "crypto/tls"
6 "encoding/base64"
7 "fmt"
8 "hash"
9 "strings"
10 "time"
11
12 "github.com/mjl-/mox/scram"
13)
14
15// Capability requests a list of capabilities from the server. They are returned in
16// an UntaggedCapability response. The server also sends capabilities in initial
17// server greeting, in the response code.
18func (c *Conn) Capability() (untagged []Untagged, result Result, rerr error) {
19 defer c.recover(&rerr)
20 return c.Transactf("capability")
21}
22
23// Noop does nothing on its own, but a server will return any pending untagged
24// responses for new message delivery and changes to mailboxes.
25func (c *Conn) Noop() (untagged []Untagged, result Result, rerr error) {
26 defer c.recover(&rerr)
27 return c.Transactf("noop")
28}
29
30// Logout ends the IMAP session by writing a LOGOUT command. Close must still be
31// called on this client to close the socket.
32func (c *Conn) Logout() (untagged []Untagged, result Result, rerr error) {
33 defer c.recover(&rerr)
34 return c.Transactf("logout")
35}
36
37// Starttls enables TLS on the connection with the STARTTLS command.
38func (c *Conn) Starttls(config *tls.Config) (untagged []Untagged, result Result, rerr error) {
39 defer c.recover(&rerr)
40 untagged, result, rerr = c.Transactf("starttls")
41 c.xcheckf(rerr, "starttls command")
42 conn := tls.Client(c.conn, config)
43 err := conn.Handshake()
44 c.xcheckf(err, "tls handshake")
45 c.conn = conn
46 c.r = bufio.NewReader(conn)
47 return untagged, result, nil
48}
49
50// Login authenticates with username and password
51func (c *Conn) Login(username, password string) (untagged []Untagged, result Result, rerr error) {
52 defer c.recover(&rerr)
53 return c.Transactf("login %s %s", astring(username), astring(password))
54}
55
56// Authenticate with plaintext password using AUTHENTICATE PLAIN.
57func (c *Conn) AuthenticatePlain(username, password string) (untagged []Untagged, result Result, rerr error) {
58 defer c.recover(&rerr)
59
60 untagged, result, rerr = c.Transactf("authenticate plain %s", base64.StdEncoding.EncodeToString(fmt.Appendf(nil, "\u0000%s\u0000%s", username, password)))
61 return
62}
63
64// Authenticate with SCRAM-SHA-1 or SCRAM-SHA-256, where the password is not
65// exchanged in original plaintext form, but only derived hashes are exchanged by
66// both parties as proof of knowledge of password.
67func (c *Conn) AuthenticateSCRAM(method string, h func() hash.Hash, username, password string) (untagged []Untagged, result Result, rerr error) {
68 defer c.recover(&rerr)
69
70 sc := scram.NewClient(h, username, "")
71 clientFirst, err := sc.ClientFirst()
72 c.xcheckf(err, "scram clientFirst")
73 c.LastTag = c.nextTag()
74 err = c.Writelinef("%s authenticate %s %s", c.LastTag, method, base64.StdEncoding.EncodeToString([]byte(clientFirst)))
75 c.xcheckf(err, "writing command line")
76
77 xreadContinuation := func() []byte {
78 var line string
79 line, untagged, result, rerr = c.ReadContinuation()
80 c.xcheckf(err, "read continuation")
81 if result.Status != "" {
82 c.xerrorf("unexpected status %q", result.Status)
83 }
84 buf, err := base64.StdEncoding.DecodeString(line)
85 c.xcheckf(err, "parsing base64 from remote")
86 return buf
87 }
88
89 serverFirst := xreadContinuation()
90 clientFinal, err := sc.ServerFirst(serverFirst, password)
91 c.xcheckf(err, "scram clientFinal")
92 err = c.Writelinef("%s", base64.StdEncoding.EncodeToString([]byte(clientFinal)))
93 c.xcheckf(err, "write scram clientFinal")
94
95 serverFinal := xreadContinuation()
96 err = sc.ServerFinal(serverFinal)
97 c.xcheckf(err, "scram serverFinal")
98
99 // We must send a response to the server continuation line, but we have nothing to say. ../rfc/9051:6221
100 err = c.Writelinef("%s", base64.StdEncoding.EncodeToString(nil))
101 c.xcheckf(err, "scram client end")
102
103 return c.ResponseOK()
104}
105
106// Enable enables capabilities for use with the connection, verifying the server has indeed enabled them.
107func (c *Conn) Enable(capabilities ...string) (untagged []Untagged, result Result, rerr error) {
108 defer c.recover(&rerr)
109
110 untagged, result, rerr = c.Transactf("enable %s", strings.Join(capabilities, " "))
111 c.xcheck(rerr)
112 var enabled UntaggedEnabled
113 c.xgetUntagged(untagged, &enabled)
114 got := map[string]struct{}{}
115 for _, cap := range enabled {
116 got[cap] = struct{}{}
117 }
118 for _, cap := range capabilities {
119 if _, ok := got[cap]; !ok {
120 c.xerrorf("capability %q not enabled by server", cap)
121 }
122 }
123 return
124}
125
126// Select opens mailbox as active mailbox.
127func (c *Conn) Select(mailbox string) (untagged []Untagged, result Result, rerr error) {
128 defer c.recover(&rerr)
129 return c.Transactf("select %s", astring(mailbox))
130}
131
132// Examine opens mailbox as active mailbox read-only.
133func (c *Conn) Examine(mailbox string) (untagged []Untagged, result Result, rerr error) {
134 defer c.recover(&rerr)
135 return c.Transactf("examine %s", astring(mailbox))
136}
137
138// Create makes a new mailbox on the server.
139func (c *Conn) Create(mailbox string) (untagged []Untagged, result Result, rerr error) {
140 defer c.recover(&rerr)
141 return c.Transactf("create %s", astring(mailbox))
142}
143
144// Delete removes an entire mailbox and its messages.
145func (c *Conn) Delete(mailbox string) (untagged []Untagged, result Result, rerr error) {
146 defer c.recover(&rerr)
147 return c.Transactf("delete %s", astring(mailbox))
148}
149
150// Rename changes the name of a mailbox and all its child mailboxes.
151func (c *Conn) Rename(omailbox, nmailbox string) (untagged []Untagged, result Result, rerr error) {
152 defer c.recover(&rerr)
153 return c.Transactf("rename %s %s", astring(omailbox), astring(nmailbox))
154}
155
156// Subscribe marks a mailbox as subscribed. The mailbox does not have to exist. It
157// is not an error if the mailbox is already subscribed.
158func (c *Conn) Subscribe(mailbox string) (untagged []Untagged, result Result, rerr error) {
159 defer c.recover(&rerr)
160 return c.Transactf("subscribe %s", astring(mailbox))
161}
162
163// Unsubscribe marks a mailbox as unsubscribed.
164func (c *Conn) Unsubscribe(mailbox string) (untagged []Untagged, result Result, rerr error) {
165 defer c.recover(&rerr)
166 return c.Transactf("unsubscribe %s", astring(mailbox))
167}
168
169// List lists mailboxes with the basic LIST syntax.
170// Pattern can contain * (match any) or % (match any except hierarchy delimiter).
171func (c *Conn) List(pattern string) (untagged []Untagged, result Result, rerr error) {
172 defer c.recover(&rerr)
173 return c.Transactf(`list "" %s`, astring(pattern))
174}
175
176// ListFull lists mailboxes with the extended LIST syntax requesting all supported data.
177// Pattern can contain * (match any) or % (match any except hierarchy delimiter).
178func (c *Conn) ListFull(subscribedOnly bool, patterns ...string) (untagged []Untagged, result Result, rerr error) {
179 defer c.recover(&rerr)
180 var subscribedStr string
181 if subscribedOnly {
182 subscribedStr = "subscribed recursivematch"
183 }
184 for i, s := range patterns {
185 patterns[i] = astring(s)
186 }
187 return c.Transactf(`list (%s) "" (%s) return (subscribed children special-use status (messages uidnext uidvalidity unseen deleted size recent appendlimit))`, subscribedStr, strings.Join(patterns, " "))
188}
189
190// Namespace returns the hiearchy separator in an UntaggedNamespace response with personal/shared/other namespaces if present.
191func (c *Conn) Namespace() (untagged []Untagged, result Result, rerr error) {
192 defer c.recover(&rerr)
193 return c.Transactf("namespace")
194}
195
196// Status requests information about a mailbox, such as number of messages, size, etc.
197func (c *Conn) Status(mailbox string) (untagged []Untagged, result Result, rerr error) {
198 defer c.recover(&rerr)
199 return c.Transactf("status %s", astring(mailbox))
200}
201
202// Append adds message to mailbox with flags and optional receive time.
203func (c *Conn) Append(mailbox string, flags []string, received *time.Time, message []byte) (untagged []Untagged, result Result, rerr error) {
204 defer c.recover(&rerr)
205 var date string
206 if received != nil {
207 date = ` "` + received.Format("_2-Jan-2006 15:04:05 -0700") + `"`
208 }
209 return c.Transactf("append %s (%s)%s {%d+}\r\n%s", astring(mailbox), strings.Join(flags, " "), date, len(message), message)
210}
211
212// note: No idle command. Idle is better implemented by writing the request and reading and handling the responses as they come in.
213
214// CloseMailbox closes the currently selected/active mailbox, permanently removing
215// any messages marked with \Deleted.
216func (c *Conn) CloseMailbox() (untagged []Untagged, result Result, rerr error) {
217 return c.Transactf("close")
218}
219
220// Unselect closes the currently selected/active mailbox, but unlike CloseMailbox
221// does not permanently remove any messages marked with \Deleted.
222func (c *Conn) Unselect() (untagged []Untagged, result Result, rerr error) {
223 return c.Transactf("unselect")
224}
225
226// Expunge removes messages marked as deleted for the selected mailbox.
227func (c *Conn) Expunge() (untagged []Untagged, result Result, rerr error) {
228 defer c.recover(&rerr)
229 return c.Transactf("expunge")
230}
231
232// UIDExpunge is like expunge, but only removes messages matching uidSet.
233func (c *Conn) UIDExpunge(uidSet NumSet) (untagged []Untagged, result Result, rerr error) {
234 defer c.recover(&rerr)
235 return c.Transactf("uid expunge %s", uidSet.String())
236}
237
238// Note: No search, fetch command yet due to its large syntax.
239
240// StoreFlagsSet stores a new set of flags for messages from seqset with the STORE command.
241// If silent, no untagged responses with the updated flags will be sent by the server.
242func (c *Conn) StoreFlagsSet(seqset string, silent bool, flags ...string) (untagged []Untagged, result Result, rerr error) {
243 defer c.recover(&rerr)
244 item := "flags"
245 if silent {
246 item += ".silent"
247 }
248 return c.Transactf("store %s %s (%s)", seqset, item, strings.Join(flags, " "))
249}
250
251// StoreFlagsAdd is like StoreFlagsSet, but only adds flags, leaving current flags on the message intact.
252func (c *Conn) StoreFlagsAdd(seqset string, silent bool, flags ...string) (untagged []Untagged, result Result, rerr error) {
253 defer c.recover(&rerr)
254 item := "+flags"
255 if silent {
256 item += ".silent"
257 }
258 return c.Transactf("store %s %s (%s)", seqset, item, strings.Join(flags, " "))
259}
260
261// StoreFlagsClear is like StoreFlagsSet, but only removes flags, leaving other flags on the message intact.
262func (c *Conn) StoreFlagsClear(seqset string, silent bool, flags ...string) (untagged []Untagged, result Result, rerr error) {
263 defer c.recover(&rerr)
264 item := "-flags"
265 if silent {
266 item += ".silent"
267 }
268 return c.Transactf("store %s %s (%s)", seqset, item, strings.Join(flags, " "))
269}
270
271// Copy adds messages from the sequences in seqSet in the currently selected/active mailbox to dstMailbox.
272func (c *Conn) Copy(seqSet NumSet, dstMailbox string) (untagged []Untagged, result Result, rerr error) {
273 defer c.recover(&rerr)
274 return c.Transactf("copy %s %s", seqSet.String(), astring(dstMailbox))
275}
276
277// UIDCopy is like copy, but operates on UIDs.
278func (c *Conn) UIDCopy(uidSet NumSet, dstMailbox string) (untagged []Untagged, result Result, rerr error) {
279 defer c.recover(&rerr)
280 return c.Transactf("uid copy %s %s", uidSet.String(), astring(dstMailbox))
281}
282
283// Move moves messages from the sequences in seqSet in the currently selected/active mailbox to dstMailbox.
284func (c *Conn) Move(seqSet NumSet, dstMailbox string) (untagged []Untagged, result Result, rerr error) {
285 defer c.recover(&rerr)
286 return c.Transactf("move %s %s", seqSet.String(), astring(dstMailbox))
287}
288
289// UIDMove is like move, but operates on UIDs.
290func (c *Conn) UIDMove(uidSet NumSet, dstMailbox string) (untagged []Untagged, result Result, rerr error) {
291 defer c.recover(&rerr)
292 return c.Transactf("uid move %s %s", uidSet.String(), astring(dstMailbox))
293}
294