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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
|
package server
import (
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"runtime/debug"
"time"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/backend"
)
// Conn is a connection to a client.
type Conn interface {
io.Reader
// Server returns this connection's server.
Server() *Server
// Context returns this connection's context.
Context() *Context
// Capabilities returns a list of capabilities enabled for this connection.
Capabilities() []string
// WriteResp writes a response to this connection.
WriteResp(res imap.WriterTo) error
// IsTLS returns true if TLS is enabled.
IsTLS() bool
// TLSState returns the TLS connection state if TLS is enabled, nil otherwise.
TLSState() *tls.ConnectionState
// Upgrade upgrades a connection, e.g. wrap an unencrypted connection with an
// encrypted tunnel.
Upgrade(upgrader imap.ConnUpgrader) error
// Close closes this connection.
Close() error
WaitReady()
Info() *imap.ConnInfo
setTLSConn(*tls.Conn)
silent() *bool // TODO: remove this
serve(Conn) error
commandHandler(cmd *imap.Command) (hdlr Handler, err error)
}
// Context stores a connection's metadata.
type Context struct {
// This connection's current state.
State imap.ConnState
// If the client is logged in, the user.
User backend.User
// If the client has selected a mailbox, the mailbox.
Mailbox backend.Mailbox
// True if the currently selected mailbox has been opened in read-only mode.
MailboxReadOnly bool
// Responses to send to the client.
Responses chan<- imap.WriterTo
// Closed when the client is logged out.
LoggedOut <-chan struct{}
}
type conn struct {
*imap.Conn
conn Conn // With extensions overrides
s *Server
ctx *Context
tlsConn *tls.Conn
continues chan bool
upgrade chan bool
responses chan imap.WriterTo
loggedOut chan struct{}
silentVal bool
}
func newConn(s *Server, c net.Conn) *conn {
// Create an imap.Reader and an imap.Writer
continues := make(chan bool)
r := imap.NewServerReader(nil, continues)
w := imap.NewWriter(nil)
responses := make(chan imap.WriterTo)
loggedOut := make(chan struct{})
tlsConn, _ := c.(*tls.Conn)
conn := &conn{
Conn: imap.NewConn(c, r, w),
s: s,
ctx: &Context{
State: imap.ConnectingState,
Responses: responses,
LoggedOut: loggedOut,
},
tlsConn: tlsConn,
continues: continues,
upgrade: make(chan bool),
responses: responses,
loggedOut: loggedOut,
}
if s.Debug != nil {
conn.Conn.SetDebug(s.Debug)
}
if s.MaxLiteralSize > 0 {
conn.Conn.MaxLiteralSize = s.MaxLiteralSize
}
go conn.send()
return conn
}
func (c *conn) Server() *Server {
return c.s
}
func (c *conn) Context() *Context {
return c.ctx
}
type response struct {
response imap.WriterTo
done chan struct{}
}
func (r *response) WriteTo(w *imap.Writer) error {
err := r.response.WriteTo(w)
close(r.done)
return err
}
func (c *conn) setDeadline() {
if c.s.AutoLogout == 0 {
return
}
dur := c.s.AutoLogout
if dur < MinAutoLogout {
dur = MinAutoLogout
}
t := time.Now().Add(dur)
c.Conn.SetDeadline(t)
}
func (c *conn) WriteResp(r imap.WriterTo) error {
done := make(chan struct{})
c.responses <- &response{r, done}
<-done
c.setDeadline()
return nil
}
func (c *conn) Close() error {
if c.ctx.User != nil {
c.ctx.User.Logout()
}
return c.Conn.Close()
}
func (c *conn) Capabilities() []string {
caps := []string{"IMAP4rev1", "LITERAL+", "SASL-IR", "CHILDREN", "UNSELECT", "MOVE", "IDLE"}
appendLimitSet := false
if c.ctx.State == imap.AuthenticatedState {
if u, ok := c.ctx.User.(backend.AppendLimitUser); ok {
if limit := u.CreateMessageLimit(); limit != nil {
caps = append(caps, fmt.Sprintf("APPENDLIMIT=%v", *limit))
appendLimitSet = true
}
}
} else if be, ok := c.Server().Backend.(backend.AppendLimitBackend); ok {
if limit := be.CreateMessageLimit(); limit != nil {
caps = append(caps, fmt.Sprintf("APPENDLIMIT=%v", *limit))
appendLimitSet = true
}
}
if !appendLimitSet {
caps = append(caps, "APPENDLIMIT")
}
if c.ctx.State == imap.NotAuthenticatedState {
if !c.IsTLS() && c.s.TLSConfig != nil {
caps = append(caps, "STARTTLS")
}
if !c.canAuth() {
caps = append(caps, "LOGINDISABLED")
} else {
for name := range c.s.auths {
caps = append(caps, "AUTH="+name)
}
}
}
for _, ext := range c.s.extensions {
caps = append(caps, ext.Capabilities(c)...)
}
return caps
}
func (c *conn) writeAndFlush(w imap.WriterTo) error {
if err := w.WriteTo(c.Writer); err != nil {
return err
}
return c.Writer.Flush()
}
func (c *conn) send() {
// Send responses
for {
select {
case <-c.upgrade:
// Wait until upgrade is finished.
c.Wait()
case needCont := <-c.continues:
// Send continuation requests
if needCont {
resp := &imap.ContinuationReq{Info: "send literal"}
if err := c.writeAndFlush(resp); err != nil {
c.Server().ErrorLog.Println("cannot send continuation request: ", err)
}
}
case res := <-c.responses:
// Got a response that needs to be sent
// Request to send the response
if err := c.writeAndFlush(res); err != nil {
c.Server().ErrorLog.Println("cannot send response: ", err)
}
case <-c.loggedOut:
return
}
}
}
func (c *conn) greet() error {
c.ctx.State = imap.NotAuthenticatedState
caps := c.Capabilities()
args := make([]interface{}, len(caps))
for i, cap := range caps {
args[i] = imap.RawString(cap)
}
greeting := &imap.StatusResp{
Type: imap.StatusRespOk,
Code: imap.CodeCapability,
Arguments: args,
Info: "IMAP4rev1 Service Ready",
}
return c.WriteResp(greeting)
}
func (c *conn) setTLSConn(tlsConn *tls.Conn) {
c.tlsConn = tlsConn
}
func (c *conn) IsTLS() bool {
return c.tlsConn != nil
}
func (c *conn) TLSState() *tls.ConnectionState {
if c.tlsConn != nil {
state := c.tlsConn.ConnectionState()
return &state
}
return nil
}
// canAuth checks if the client can use plain text authentication.
func (c *conn) canAuth() bool {
return c.IsTLS() || c.s.AllowInsecureAuth
}
func (c *conn) silent() *bool {
return &c.silentVal
}
func (c *conn) serve(conn Conn) (err error) {
c.conn = conn
defer func() {
c.ctx.State = imap.LogoutState
close(c.loggedOut)
}()
defer func() {
if r := recover(); r != nil {
c.WriteResp(&imap.StatusResp{
Type: imap.StatusRespBye,
Info: "Internal server error, closing connection.",
})
stack := debug.Stack()
c.s.ErrorLog.Printf("panic serving %v: %v\n%s", c.Info().RemoteAddr, r, stack)
err = fmt.Errorf("%v", r)
}
}()
// Send greeting
if err := c.greet(); err != nil {
return err
}
for {
if c.ctx.State == imap.LogoutState {
return nil
}
var res *imap.StatusResp
var up Upgrader
fields, err := c.ReadLine()
if err == io.EOF || c.ctx.State == imap.LogoutState {
return nil
}
c.setDeadline()
if err != nil {
if imap.IsParseError(err) {
res = &imap.StatusResp{
Type: imap.StatusRespBad,
Info: err.Error(),
}
} else {
c.s.ErrorLog.Println("cannot read command:", err)
return err
}
} else {
cmd := &imap.Command{}
if err := cmd.Parse(fields); err != nil {
res = &imap.StatusResp{
Tag: cmd.Tag,
Type: imap.StatusRespBad,
Info: err.Error(),
}
} else {
var err error
res, up, err = c.handleCommand(cmd)
if err != nil {
res = &imap.StatusResp{
Tag: cmd.Tag,
Type: imap.StatusRespBad,
Info: err.Error(),
}
}
}
}
if res != nil {
if err := c.WriteResp(res); err != nil {
c.s.ErrorLog.Println("cannot write response:", err)
continue
}
if up != nil && res.Type == imap.StatusRespOk {
if err := up.Upgrade(c.conn); err != nil {
c.s.ErrorLog.Println("cannot upgrade connection:", err)
return err
}
}
}
}
}
func (c *conn) WaitReady() {
c.upgrade <- true
c.Conn.WaitReady()
}
func (c *conn) commandHandler(cmd *imap.Command) (hdlr Handler, err error) {
newHandler := c.s.Command(cmd.Name)
if newHandler == nil {
err = errors.New("Unknown command")
return
}
hdlr = newHandler()
err = hdlr.Parse(cmd.Arguments)
return
}
func (c *conn) handleCommand(cmd *imap.Command) (res *imap.StatusResp, up Upgrader, err error) {
hdlr, err := c.commandHandler(cmd)
if err != nil {
return
}
hdlrErr := hdlr.Handle(c.conn)
if statusErr, ok := hdlrErr.(*imap.ErrStatusResp); ok {
res = statusErr.Resp
} else if hdlrErr != nil {
res = &imap.StatusResp{
Type: imap.StatusRespNo,
Info: hdlrErr.Error(),
}
} else {
res = &imap.StatusResp{
Type: imap.StatusRespOk,
}
}
if res != nil {
res.Tag = cmd.Tag
if res.Type == imap.StatusRespOk && res.Info == "" {
res.Info = cmd.Name + " completed"
}
}
up, _ = hdlr.(Upgrader)
return
}
|