forked from fiorix/go-smpp
/
client.go
258 lines (233 loc) · 5.76 KB
/
client.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
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
// Copyright 2015 go-smpp authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package smpp
import (
"crypto/tls"
"io"
"math"
"sync"
"time"
"github.com/zpas-lab/go-smpp/smpp/pdu"
"github.com/zpas-lab/go-smpp/smpp/pdu/pdufield"
)
// ConnStatus is an abstract interface for a connection status change.
type ConnStatus interface {
Status() ConnStatusID
Error() error
}
type connStatus struct {
s ConnStatusID
err error
}
func (c *connStatus) Status() ConnStatusID { return c.s }
func (c *connStatus) Error() error { return c.err }
// ConnStatusID represents a connection status change.
type ConnStatusID uint8
// Supported connection statuses.
const (
Connected ConnStatusID = iota + 1
Disconnected
ConnectionFailed
BindFailed
)
var connStatusText = map[ConnStatusID]string{
Connected: "Connected",
Disconnected: "Disconnected",
ConnectionFailed: "Connection failed",
BindFailed: "Bind failed",
}
// String implements the Stringer interface.
func (cs ConnStatusID) String() string {
return connStatusText[cs]
}
// ClientConn provides a persistent client connection that handles
// reconnection with a back-off algorithm.
type ClientConn interface {
// Bind starts the client connection and returns a
// channel that is triggered every time the connection
// status changes.
Bind() <-chan ConnStatus
// Closer embeds the Closer interface. When Close is
// called, client sends the Unbind command first and
// terminates the connection upon response, or 1s timeout.
Closer
}
// client provides a persistent client connection.
type client struct {
Addr string
TLS *tls.Config
Status chan ConnStatus
BindFunc func(c Conn) error
EnquireLink time.Duration
RespTimeout time.Duration
WindowSize uint
// internal stuff.
inbox chan pdu.Body
inboxMutex sync.Mutex
conn *connSwitch
stop chan struct{}
once sync.Once
}
func (c *client) init() {
c.conn = &connSwitch{}
c.stop = make(chan struct{})
if c.EnquireLink < 10*time.Second {
c.EnquireLink = 10 * time.Second
}
}
// Bind starts the connection manager and blocks until Close is called.
// It must be called in a goroutine.
func (c *client) Bind() {
delay := 1.0
const maxdelay = 120.0
for !c.closed() {
eli := make(chan struct{})
c.inboxMutex.Lock()
c.inbox = make(chan pdu.Body)
c.inboxMutex.Unlock()
conn, err := Dial(c.Addr, c.TLS)
if err != nil {
c.notify(&connStatus{
s: ConnectionFailed,
err: err,
})
goto retry
}
c.conn.Set(conn)
if err = c.BindFunc(c.conn); err != nil {
c.notify(&connStatus{s: BindFailed, err: err})
goto retry
}
go c.enquireLink(eli)
c.notify(&connStatus{s: Connected})
delay = 1
for {
p, err := c.conn.Read()
if err != nil {
c.notify(&connStatus{
s: Disconnected,
err: err,
})
break
}
switch p.Header().ID {
case pdu.EnquireLinkID:
// TODO: respond
case pdu.EnquireLinkRespID:
// TODO: don't just ignore
default:
c.inbox <- p
}
}
retry:
close(eli)
// NOTE(michalm,#415): this channel is closed to avoid goroutines ( c.bindFunc() -> ... -> c.Read() )
// block on c.inbox when connection is broken before sending anything to c.inbox (c.inbox <- p).
// However, closing the channel does not resolve the issue completely. Theoretically, it is possible
// that this loop (l.100) iterates a couple of times before c.inbox is read in c.Read().
// In such a case we still end up with some goroutines hanging. But now they have a chance to return
// once the connection fails and c.inbox is closed.
close(c.inbox)
c.conn.Close()
delay = math.Min(delay*math.E, maxdelay)
c.trysleep(time.Duration(delay) * time.Second)
}
close(c.Status)
}
func (c *client) enquireLink(stop chan struct{}) {
for {
select {
case <-time.After(c.EnquireLink):
err := c.conn.Write(pdu.NewEnquireLink())
if err != nil {
return
}
case <-stop:
return
case <-c.stop:
return
}
}
}
func (c *client) notify(ev ConnStatus) {
select {
case c.Status <- ev:
default:
}
}
// Read reads PDU binary data off the wire and returns it.
func (c *client) Read() (pdu.Body, error) {
c.inboxMutex.Lock()
in := c.inbox
c.inboxMutex.Unlock()
select {
case pdu, ok := <-in:
if !ok {
return nil, io.ErrUnexpectedEOF
}
return pdu, nil
case <-c.stop:
return nil, io.EOF
}
}
// Write serializes the given PDU and writes to the connection.
func (c *client) Write(w pdu.Body) error {
return c.conn.Write(w)
}
// Close terminates the current connection and stop any further attempts.
func (c *client) Close() error {
c.once.Do(func() {
close(c.stop)
if err := c.conn.Write(pdu.NewUnbind()); err == nil {
select {
case <-c.inbox: // TODO: validate UnbindResp
case <-time.After(time.Second):
}
}
c.conn.Close()
})
return nil
}
// trysleep for the given duration, or return if Close is called.
func (c *client) trysleep(d time.Duration) {
select {
case <-time.After(d):
case <-c.stop:
}
}
// closed returns true after Close is called once.
func (c *client) closed() bool {
select {
case <-c.stop:
return true
default:
return false
}
}
// respTimeout returns a channel that fires based on the configured
// response timeout, or the default 1s.
func (c *client) respTimeout() <-chan time.Time {
if c.RespTimeout == 0 {
return time.After(time.Second)
}
return time.After(c.RespTimeout)
}
// bind attempts to bind the connection.
func bind(c Conn, p pdu.Body) (pdu.Body, error) {
f := p.Fields()
f.Set(pdufield.InterfaceVersion, 0x34)
err := c.Write(p)
if err != nil {
return nil, err
}
resp, err := c.Read()
if err != nil {
return nil, err
}
h := resp.Header()
if h.Status != 0 {
return nil, h.Status
}
return resp, nil
}