mox/moxio/flatewriter.go
Mechiel Lukkien 17de90e29d
imapserver: Prevent spurious unhandled panics for connections with compress=deflate that break
Writing to a connection goes through the flate library to compress. That writes
the compressed bytes to the underlying connection. But that underlying
connection is wrapped to raise a panic with an i/o error instead of returning a
normal error.  Jumping out of flate leaves the internal state of the compressor
in undefined state. So far so good. But as part of cleaning up the connection,
we could try to flush output again. Specifically: If we were writing user data,
we had switched from tracing of protocol data to tracing of user data, and we
registered a defer that restored the tracing kind and flushed (to ensure data
was traced at the right level). That flush would cause a write into the
compressor again, which could panic with an out of bounds slice access due to
its inconsistent internal state.

This fix prevents that compressor panic in two ways:

1. We wrap the flate.Writer with a moxio.FlateWriter that keeps track of
   whether a panic came out of an operation on it. If so, any further operation
   raises the same panic. This prevents access to the inconsistent internal flate
   state entirely.
2. Once we raise an i/o error, we mark the connection as broken and that makes
   flushes a no-op.
2025-02-26 11:26:54 +01:00

49 lines
1.0 KiB
Go

package moxio
import (
"github.com/mjl-/flate"
)
// FlateWriter wraps a flate.Writer and ensures no Write/Flush/Close calls are made
// again on the underlying flate writer when a panic came out of the flate writer
// (e.g. raised by the destination writer of the flate writer). After a panic
// "through" a flate.Writer, its state is inconsistent and further calls could
// panic with out of bounds slice accesses.
type FlateWriter struct {
w *flate.Writer
panic any
}
func NewFlateWriter(w *flate.Writer) *FlateWriter {
return &FlateWriter{w, nil}
}
func (w *FlateWriter) checkBroken() func() {
if w.panic != nil {
panic(w.panic)
}
return func() {
x := recover()
if x == nil {
return
}
w.panic = x
panic(x)
}
}
func (w *FlateWriter) Write(data []byte) (int, error) {
defer w.checkBroken()()
return w.w.Write(data)
}
func (w *FlateWriter) Flush() error {
defer w.checkBroken()()
return w.w.Flush()
}
func (w *FlateWriter) Close() error {
defer w.checkBroken()()
return w.w.Close()
}