forked from getlantern/marionette
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdialer.go
93 lines (77 loc) · 1.81 KB
/
dialer.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
93
package marionette
import (
"context"
"errors"
"net"
"sync"
"github.com/redjack/marionette/mar"
"go.uber.org/zap"
)
var (
// ErrDialerClosed is returned when trying to operate on a closed dialer.
ErrDialerClosed = errors.New("marionette: dialer closed")
)
// Dialer represents a client-side dialer that communicates over the marionette protocol.
type Dialer struct {
mu sync.RWMutex
fsm FSM
streamSet *StreamSet
ctx context.Context
cancel func()
closed bool
wg sync.WaitGroup
}
// NewDialer returns a new instance of Dialer.
func NewDialer(doc *mar.Document, addr string, streamSet *StreamSet) (*Dialer, error) {
conn, err := net.Dial(doc.Transport, net.JoinHostPort(addr, doc.Port))
if err != nil {
return nil, err
}
// Run execution in a separate goroutine.
d := &Dialer{
fsm: NewFSM(doc, addr, PartyClient, conn, streamSet),
streamSet: streamSet,
}
d.ctx, d.cancel = context.WithCancel(context.Background())
d.wg.Add(1)
go func() { defer d.wg.Done(); d.execute() }()
return d, nil
}
// Close stops the dialer and its underlying connections.
func (d *Dialer) Close() error {
err := d.close()
d.wg.Wait()
return err
}
func (d *Dialer) close() (err error) {
d.mu.Lock()
d.closed = true
err = d.fsm.Close()
d.mu.Unlock()
d.cancel()
return err
}
// Closed returns true if the dialer has been closed.
func (d *Dialer) Closed() bool {
d.mu.RLock()
closed := d.closed
d.mu.RUnlock()
return closed
}
// Dial returns a new stream from the dialer.
func (d *Dialer) Dial() (net.Conn, error) {
if d.Closed() {
return nil, ErrDialerClosed
}
return d.streamSet.Create(), nil
}
func (d *Dialer) execute() {
defer d.close()
for !d.Closed() {
if err := d.fsm.Execute(d.ctx); err != nil {
Logger.Debug("dialer error", zap.Error(err))
return
}
d.fsm.Reset()
}
}