aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/emersion/go-imap/responses/authenticate.go
blob: 8e134cb7bc0d62278737b451f931c6599ed76a24 (plain)
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
package responses

import (
	"encoding/base64"

	"github.com/emersion/go-imap"
	"github.com/emersion/go-sasl"
)

// An AUTHENTICATE response.
type Authenticate struct {
	Mechanism       sasl.Client
	InitialResponse []byte
	RepliesCh       chan []byte
}

// Implements
func (r *Authenticate) Replies() <-chan []byte {
	return r.RepliesCh
}

func (r *Authenticate) writeLine(l string) error {
	r.RepliesCh <- []byte(l + "\r\n")
	return nil
}

func (r *Authenticate) cancel() error {
	return r.writeLine("*")
}

func (r *Authenticate) Handle(resp imap.Resp) error {
	cont, ok := resp.(*imap.ContinuationReq)
	if !ok {
		return ErrUnhandled
	}

	// Empty challenge, send initial response as stated in RFC 2222 section 5.1
	if cont.Info == "" && r.InitialResponse != nil {
		encoded := base64.StdEncoding.EncodeToString(r.InitialResponse)
		if err := r.writeLine(encoded); err != nil {
			return err
		}
		r.InitialResponse = nil
		return nil
	}

	challenge, err := base64.StdEncoding.DecodeString(cont.Info)
	if err != nil {
		r.cancel()
		return err
	}

	reply, err := r.Mechanism.Next(challenge)
	if err != nil {
		r.cancel()
		return err
	}

	encoded := base64.StdEncoding.EncodeToString(reply)
	return r.writeLine(encoded)
}