This repository has been archived by the owner on Jan 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
gami.go
375 lines (308 loc) · 8.07 KB
/
gami.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
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
// Copyright 2014 Jovany Leandro G.C <bit4bit@riseup.net>. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file
// Package gami provites primitives for interacting with Asterisk AMI
Basic Usage
ami, err := gami.Dial("127.0.0.1:5038")
if err != nil {
fmt.Print(err)
os.Exit(1)
}
ami.Run()
defer ami.Close()
//install manager
go func() {
for {
select {
//handle network errors
case err := <-ami.NetError:
log.Println("Network Error:", err)
//try new connection every second
<-time.After(time.Second)
if err := ami.Reconnect(); err == nil {
//call start actions
ami.Action("Events", gami.Params{"EventMask": "on"})
}
case err := <-ami.Error:
log.Println("error:", err)
//wait events and process
case ev := <-ami.Events:
log.Println("Event Detect: %v", *ev)
//if want type of events
log.Println("EventType:", event.New(ev))
}
}
}()
if err := ami.Login("admin", "root"); err != nil {
log.Fatal(err)
}
if rs, err = ami.Action("Ping", nil); err == nil {
log.Fatal(rs)
}
//or with can do async
pingResp, pingErr := ami.AsyncAction("Ping", gami.Params{"ActionID": "miping"})
if pingErr != nil {
log.Fatal(pingErr)
}
if rs, err = ami.Action("Events", ami.Params{"EventMask":"on"}); err != nil {
fmt.Print(err)
}
log.Println("future ping:", <-pingResp)
*/
package gami
import (
"crypto/tls"
"errors"
"fmt"
"io"
"time"
"net"
"net/textproto"
"strings"
"sync"
"syscall"
)
var errNotEvent = errors.New("Not Event")
// Raise when not response expected protocol AMI
var ErrNotAMI = errors.New("Server not AMI interface")
// Params for the actions
type Params map[string]string
// AMIClient a connection to AMI server
type AMIClient struct {
conn *textproto.Conn
connRaw io.ReadWriteCloser
mutexAsyncAction *sync.RWMutex
address string
amiUser string
amiPass string
useTLS bool
unsecureTLS bool
// TLSConfig for secure connections
tlsConfig *tls.Config
// network wait for a new connection
waitNewConnection chan struct{}
response map[string]chan *AMIResponse
// Events for client parse
Events chan *AMIEvent
// Error Raise on logic
Error chan error
//NetError a network error
NetError chan error
}
// AMIResponse from action
type AMIResponse struct {
ID string
Status string
Params map[string]string
}
// AMIEvent it's a representation of Event readed
type AMIEvent struct {
//Identification of event Event: xxxx
ID string
Privilege []string
// Params of arguments received
Params map[string]string
}
func UseTLS(c *AMIClient) {
c.useTLS = true
}
func UseTLSConfig(config *tls.Config) func(*AMIClient) {
return func(c *AMIClient) {
c.tlsConfig = config
c.useTLS = true
}
}
func UnsecureTLS(c *AMIClient) {
c.unsecureTLS = true
}
// Login authenticate to AMI
func (client *AMIClient) Login(username, password string) error {
response, err := client.Action("Login", Params{"Username": username, "Secret": password})
if err != nil {
return err
}
if (*response).Status == "Error" {
return errors.New((*response).Params["Message"])
}
client.amiUser = username
client.amiPass = password
return nil
}
// Reconnect the session, autologin if a new network error it put on client.NetError
func (client *AMIClient) Reconnect() error {
client.conn.Close()
err := client.NewConn()
if err != nil {
client.NetError <- err
return err
}
client.waitNewConnection <- struct{}{}
if err := client.Login(client.amiUser, client.amiPass); err != nil {
return err
}
return nil
}
// AsyncAction return chan for wait response of action with parameter *ActionID* this can be helpful for
// massive actions,
func (client *AMIClient) AsyncAction(action string, params Params) (<-chan *AMIResponse, error) {
var output string
client.mutexAsyncAction.Lock()
defer client.mutexAsyncAction.Unlock()
output = fmt.Sprintf("Action: %s\r\n", strings.TrimSpace(action))
if params == nil {
params = Params{}
}
if _, ok := params["ActionID"]; !ok {
params["ActionID"] = fmt.Sprintf("%d", time.Now().UnixNano())
}
if _, ok := client.response[params["ActionID"]]; !ok {
client.response[params["ActionID"]] = make(chan *AMIResponse, 1)
}
for k, v := range params {
output = output + fmt.Sprintf("%s: %s\r\n", k, strings.TrimSpace(v))
}
if err := client.conn.PrintfLine("%s", output); err != nil {
return nil, err
}
return client.response[params["ActionID"]], nil
}
// Action send with params
func (client *AMIClient) Action(action string, params Params) (*AMIResponse, error) {
resp, err := client.AsyncAction(action, params)
if err != nil {
return nil, err
}
response := <-resp
return response, nil
}
// Run process socket waiting events and responses
func (client *AMIClient) Run() {
go func() {
for {
data, err := client.conn.ReadMIMEHeader()
if err != nil {
switch err {
case syscall.ECONNABORTED:
fallthrough
case syscall.ECONNRESET:
fallthrough
case syscall.ECONNREFUSED:
fallthrough
case io.EOF:
client.NetError <- err
<-client.waitNewConnection
default:
client.Error <- err
}
continue
}
if ev, err := newEvent(&data); err != nil {
if err != errNotEvent {
client.Error <- err
}
} else {
client.Events <- ev
}
//only handle valid responses
//@todo handle longs response
// see https://marcelog.github.io/articles/php_asterisk_manager_interface_protocol_tutorial_introduction.html
if response, err := newResponse(&data); err == nil {
client.notifyResponse(response)
}
}
}()
}
// Close the connection to AMI
func (client *AMIClient) Close() {
client.Action("Logoff", nil)
(client.connRaw).Close()
}
func (client *AMIClient) notifyResponse(response *AMIResponse) {
go func() {
client.mutexAsyncAction.RLock()
client.response[response.ID] <- response
close(client.response[response.ID])
client.mutexAsyncAction.RUnlock()
client.mutexAsyncAction.Lock()
delete(client.response, response.ID)
client.mutexAsyncAction.Unlock()
}()
}
//newResponse build a response for action
func newResponse(data *textproto.MIMEHeader) (*AMIResponse, error) {
if data.Get("Response") == "" {
return nil, errors.New("Not Response")
}
response := &AMIResponse{data.Get("Actionid"),
data.Get("Response"),
make(map[string]string)}
for k, v := range *data {
if k == "Response" {
continue
}
response.Params[k] = v[0]
}
return response, nil
}
//newEvent build event
func newEvent(data *textproto.MIMEHeader) (*AMIEvent, error) {
if data.Get("Event") == "" {
return nil, errNotEvent
}
ev := &AMIEvent{data.Get("Event"),
strings.Split(data.Get("Privilege"), ","),
make(map[string]string)}
for k, v := range *data {
if k == "Event" || k == "Privilege" {
continue
}
ev.Params[k] = v[0]
}
return ev, nil
}
// Dial create a new connection to AMI
func Dial(address string, options ...func(*AMIClient)) (*AMIClient, error) {
client := &AMIClient{
address: address,
amiUser: "",
amiPass: "",
mutexAsyncAction: new(sync.RWMutex),
waitNewConnection: make(chan struct{}),
response: make(map[string]chan *AMIResponse),
Events: make(chan *AMIEvent, 100),
Error: make(chan error, 1),
NetError: make(chan error, 1),
useTLS: false,
unsecureTLS: false,
tlsConfig: new(tls.Config),
}
for _, op := range options {
op(client)
}
err := client.NewConn()
if err != nil {
return nil, err
}
return client, nil
}
// NewConn create a new connection to AMI
func (client *AMIClient) NewConn() (err error) {
if client.useTLS {
client.tlsConfig.InsecureSkipVerify = client.unsecureTLS
client.connRaw, err = tls.Dial("tcp", client.address, client.tlsConfig)
} else {
client.connRaw, err = net.Dial("tcp", client.address)
}
if err != nil {
return err
}
client.conn = textproto.NewConn(client.connRaw)
label, err := client.conn.ReadLine()
if err != nil {
return err
}
if strings.Contains(label, "Asterisk Call Manager") != true {
return ErrNotAMI
}
return nil
}