forked from percipia/eslgo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinbound.go
92 lines (83 loc) · 2.07 KB
/
inbound.go
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
/*
* Copyright (c) 2020 Percipia
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Contributor(s):
* Andrew Querol <[email protected]>
*/
package eslgo
import (
"context"
"fmt"
"log"
"net"
"time"
"github.com/AkronimBlack/eslgo/command"
)
func Dial(address, password string, timeout time.Duration, onDisconnect func()) (*Conn, error) {
c, err := net.DialTimeout("tcp", address, timeout)
if err != nil {
return nil, err
}
connection := NewConnection(c, false)
// First auth
<-connection.responseChannels[TypeAuthRequest]
err = connection.doAuth(connection.runningContext, command.Auth{Password: password})
if err != nil {
// Try to gracefully disconnect, we have the wrong password.
connection.ExitAndClose()
if onDisconnect != nil {
go onDisconnect()
}
return nil, err
} else {
log.Printf("Sucessfully authenticated %s\n", connection.conn.RemoteAddr())
}
// Inbound only handlers
go connection.authLoop(command.Auth{Password: password})
go connection.disconnectLoop(onDisconnect)
return connection, nil
}
func (c *Conn) disconnectLoop(onDisconnect func()) {
select {
case <-c.responseChannels[TypeDisconnect]:
c.Close()
if onDisconnect != nil {
onDisconnect()
}
return
case <-c.runningContext.Done():
return
}
}
func (c *Conn) authLoop(auth command.Auth) {
for {
select {
case <-c.responseChannels[TypeAuthRequest]:
err := c.doAuth(c.runningContext, auth)
if err != nil {
log.Printf("Failed to auth %e\n", err)
// Close the connection, we have the wrong password
c.ExitAndClose()
return
} else {
log.Printf("Sucessfully authenticated %s\n", c.conn.RemoteAddr())
}
case <-c.runningContext.Done():
return
}
}
}
func (c *Conn) doAuth(ctx context.Context, auth command.Auth) error {
response, err := c.SendCommand(ctx, auth)
if err != nil {
return err
}
if !response.IsOk() {
return fmt.Errorf("failed to auth %#v", response)
}
return nil
}