9 "github.com/mjl-/bstore"
11 "github.com/mjl-/mox/config"
12 "github.com/mjl-/mox/message"
13 "github.com/mjl-/mox/mlog"
14 "github.com/mjl-/mox/store"
17// Replace relaces a message for another, atomically, possibly in another mailbox,
18// without needing a sequence of: append message, store \deleted flag, expunge.
21func (c *conn) cmdxReplace(isUID bool, tag, cmd string, p *parser) {
36 var storeFlags store.Flags
39 // Error must be a syntax error, to properly abort the connection due to literal.
41 storeFlags, keywords, err = store.ParseFlagsKeywords(p.xflagList())
43 xsyntaxErrorf("parsing flags: %v", err)
56 // todo: only with utf8 should we we accept message headers with utf-8. we currently always accept them.
57 // todo: this is only relevant if we also support the CATENATE extension?
59 utf8 := p.take("UTF8 (")
64 // For utf8, we already consumed the required ~ above.
65 size, synclit := p.xliteralSize(!utf8, false)
67 // Check the request, including old message in database, whether the message fits
68 // in quota. If a non-nil func is returned, an error was found. Calling the
69 // function aborts handling this command.
71 checkMessage := func(tx *bstore.Tx) func() {
73 return func() { xuserErrorf("mailbox open in read-only mode") }
76 mb, err := c.account.MailboxFind(tx, name)
78 return func() { xserverErrorf("finding mailbox: %v", err) }
81 return func() { xusercodeErrorf("TRYCREATE", "%w", store.ErrUnknownMailbox) }
84 // Resolve "*" for UID or message sequence.
87 q := bstore.QueryTx[store.Message](tx)
88 q.FilterNonzero(store.Message{MailboxID: c.mailboxID})
89 q.FilterEqual("Expunged", false)
90 q.FilterLess("UID", c.uidnext)
94 if err == bstore.ErrAbsent {
95 return func() { xsyntaxErrorf("cannot use * on empty mailbox") }
97 xcheckf(err, "get last message in mailbox")
99 } else if c.exists == 0 {
100 return func() { xsyntaxErrorf("cannot use * on empty mailbox") }
102 num = uint32(c.uids[c.exists-1])
104 num = uint32(c.exists)
109 // Find or verify UID of message to replace.
111 uidOld = store.UID(num)
112 } else if num > c.exists {
113 return func() { xuserErrorf("invalid msgseq") }
115 uidOld = c.uids[int(num)-1]
118 // Check the message still exists in the database. If it doesn't, it may have been
119 // deleted just now and we won't check the quota. We'll raise an error later on,
120 // when we are not possibly reading a sync literal and can respond with unsolicited
122 q := bstore.QueryTx[store.Message](tx)
123 q.FilterNonzero(store.Message{MailboxID: c.mailboxID, UID: uidOld})
124 q.FilterEqual("Expunged", false)
125 q.FilterLess("UID", c.uidnext)
127 if err == bstore.ErrAbsent {
131 return func() { xserverErrorf("get message to replace: %v", err) }
134 // Check if we can add size bytes. We can't necessarily remove the current message yet.
135 ok, maxSize, err := c.account.CanAddMessageSize(tx, size)
137 return func() { xserverErrorf("check quota: %v", err) }
141 return func() { xusercodeErrorf("OVERQUOTA", "account over maximum total message size %d", maxSize) }
148 // Check request, if it cannot succeed, fail it now before client is sending the data.
150 name = xcheckmailboxname(name, true)
152 c.account.WithRLock(func() {
153 c.xdbread(func(tx *bstore.Tx) {
154 errfn = checkMessage(tx)
164 name, _, err = config.CheckMailboxName(name, true)
166 errfn = func() { xusercodeErrorf("CANNOT", "%s", err) }
168 c.account.WithRLock(func() {
169 c.xdbread(func(tx *bstore.Tx) {
170 errfn = checkMessage(tx)
177 var newID int64 // Delivered message ID, file removed on error.
182 // We got a non-sync literal, we will consume some data, but abort if there's too
183 // much. We draw the line at 1mb. Client should have used synchronizing literal.
184 if size > 1000*1000 {
186 err := errors.New("error condition and non-synchronizing literal too big")
187 bye := "* BYE [ALERT] " + err.Error()
188 panic(syntaxError{bye, "TOOBIG", err.Error(), err})
190 // Message will not be accepted.
193 // Read the message into a temporary file.
195 file, err = store.CreateMessageTemp(c.log, "imap-replace")
196 xcheckf(err, "creating temp file for message")
197 defer store.CloseRemoveTempFile(c.log, file, "temporary message file")
201 if !commit && newID != 0 {
202 p := c.account.MessagePath(newID)
204 c.xsanity(err, "remove message file for replace after error")
209 // Read the message data.
210 defer c.xtraceread(mlog.LevelTracedata)()
211 mw := message.NewWriter(f)
212 msize, err := io.Copy(mw, io.LimitReader(c.br, size))
213 c.xtraceread(mlog.LevelTrace) // Restore.
215 // Cannot use xcheckf due to %w handling of errIO.
216 c.xbrokenf("reading literal message: %s (%w)", err, errIO)
219 c.xbrokenf("read %d bytes for message, expected %d (%w)", msize, size, errIO)
222 // Finish reading the command.
223 line := c.xreadline(false)
224 p = newParser(line, c)
230 // If an error was found earlier, abort the command now that we've read the message.
235 var oldMsgExpunged bool
237 var om, nm store.Message
238 var mbSrc, mbDst store.Mailbox // Src and dst mailboxes can be different.
../rfc/8508:263
240 var pendingChanges []store.Change
243 c.flushChanges(pendingChanges)
246 c.account.WithWLock(func() {
247 var changes []store.Change
249 c.xdbwrite(func(tx *bstore.Tx) {
250 mbSrc = c.xmailboxID(tx, c.mailboxID)
252 // Get old message. If it has been expunged, we should have a pending change for
253 // it. We'll send untagged responses and fail the command.
255 qom := bstore.QueryTx[store.Message](tx)
256 qom.FilterNonzero(store.Message{MailboxID: mbSrc.ID, UID: uidOld})
258 xcheckf(err, "get old message to replace from database")
260 oldMsgExpunged = true
264 // Check quota for addition of new message. We can't necessarily yet remove the old message.
265 ok, maxSize, err := c.account.CanAddMessageSize(tx, mw.Size)
266 xcheckf(err, "checking quota")
269 xusercodeErrorf("OVERQUOTA", "account over maximum total message size %d", maxSize)
272 modseq, err := c.account.NextModSeq(tx)
273 xcheckf(err, "get next mod seq")
275 chremuids, _, err := c.account.MessageRemove(c.log, tx, modseq, &mbSrc, store.RemoveOpts{}, om)
276 xcheckf(err, "expunge old message")
277 changes = append(changes, chremuids)
278 // Note: we only add a mbSrc counts change later on, if it is not equal to mbDst.
280 err = tx.Update(&mbSrc)
281 xcheckf(err, "updating source mailbox counts")
283 mbDst = c.xmailbox(tx, name, "TRYCREATE")
284 mbDst.ModSeq = modseq
286 nkeywords := len(mbDst.Keywords)
288 // Make new message to deliver.
291 MailboxOrigID: mbDst.ID,
300 err = c.account.MessageAdd(c.log, tx, &mbDst, &nm, file, store.AddOpts{})
301 xcheckf(err, "delivering message")
304 changes = append(changes, nm.ChangeAddUID(mbDst), mbDst.ChangeCounts())
305 if nkeywords != len(mbDst.Keywords) {
306 changes = append(changes, mbDst.ChangeKeywords())
309 err = tx.Update(&mbDst)
310 xcheckf(err, "updating destination mailbox")
313 // Fetch pending changes, possibly with new UIDs, so we can apply them before adding our own new UID.
314 overflow, pendingChanges = c.comm.Get()
320 // Success, make sure messages aren't cleaned up anymore.
323 // Broadcast the change to other connections.
324 if mbSrc.ID != mbDst.ID {
325 changes = append(changes, mbSrc.ChangeCounts())
330 // Must update our msgseq/uids tracking with latest pending changes.
333 c.xapplyChanges(overflow, l, false)
335 // If we couldn't find the message, send a NO response. We've just applied pending
336 // changes, which should have expunged the absent message.
338 xuserErrorf("message to be replaced has been expunged")
341 // If the destination mailbox is our currently selected mailbox, we register and
342 // announce the new message.
343 if mbDst.ID == c.mailboxID {
345 // We send an untagged OK with APPENDUID, for sane bookkeeping in clients.
../rfc/8508:401
346 c.xbwritelinef("* OK [APPENDUID %d %d] ", mbDst.UIDValidity, nm.UID)
347 c.xbwritelinef("* %d EXISTS", c.exists)
350 // We must return vanished instead of expunge, and also highestmodseq, when qresync
352 qresync := c.enabled[capQresync]
354 // Now that we are in sync with msgseq, we can find our old msgseq and say it is
360 oseq = c.xsequence(om.UID)
361 c.sequenceRemove(oseq, om.UID)
363 if qresync || c.uidonly {
364 c.xbwritelinef("* VANISHED %d", om.UID)
367 c.xbwritelinef("* %d EXPUNGE", oseq)
369 c.xwriteresultf("%s OK [HIGHESTMODSEQ %d] replaced", tag, nm.ModSeq.Client())