-
Notifications
You must be signed in to change notification settings - Fork 124
/
connection.go
231 lines (183 loc) · 5.06 KB
/
connection.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
// Copyright 2015 Nevio Vesic
// Please check out LICENSE file for more information about what you CAN and what you CANNOT do!
// Basically in short this is a free software for you to do whatever you want to do BUT copyright must be included!
// I didn't write all of this code so you could say it's yours.
// MIT License
package goesl
import (
"bufio"
"bytes"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
)
// Main connection against ESL - Gotta add more description here
type SocketConnection struct {
net.Conn
err chan error
m chan *Message
mtx sync.Mutex
}
// Dial - Will establish timedout dial against specified address. In this case, it will be freeswitch server
func (c *SocketConnection) Dial(network string, addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
}
// Send - Will send raw message to open net connection
func (c *SocketConnection) Send(cmd string) error {
if strings.Contains(cmd, "\r\n") {
return fmt.Errorf(EInvalidCommandProvided, cmd)
}
// lock mutex
c.mtx.Lock()
defer c.mtx.Unlock()
_, err := io.WriteString(c, cmd)
if err != nil {
return err
}
_, err = io.WriteString(c, "\r\n\r\n")
if err != nil {
return err
}
return nil
}
// SendMany - Will loop against passed commands and return 1st error if error happens
func (c *SocketConnection) SendMany(cmds []string) error {
for _, cmd := range cmds {
if err := c.Send(cmd); err != nil {
return err
}
}
return nil
}
// SendEvent - Will loop against passed event headers
func (c *SocketConnection) SendEvent(eventHeaders []string) error {
if len(eventHeaders) <= 0 {
return fmt.Errorf(ECouldNotSendEvent, len(eventHeaders))
}
// lock mutex to prevent event headers from conflicting
c.mtx.Lock()
defer c.mtx.Unlock()
_, err := io.WriteString(c, "sendevent ")
if err != nil {
return err
}
for _, eventHeader := range eventHeaders {
_, err := io.WriteString(c, eventHeader)
if err != nil {
return err
}
_, err = io.WriteString(c, "\r\n")
if err != nil {
return err
}
}
_, err = io.WriteString(c, "\r\n")
if err != nil {
return err
}
return nil
}
// Execute - Helper fuck to execute commands with its args and sync/async mode
func (c *SocketConnection) Execute(command, args string, sync bool) (m *Message, err error) {
return c.SendMsg(map[string]string{
"call-command": "execute",
"execute-app-name": command,
"execute-app-arg": args,
"event-lock": strconv.FormatBool(sync),
}, "", "")
}
// ExecuteUUID - Helper fuck to execute uuid specific commands with its args and sync/async mode
func (c *SocketConnection) ExecuteUUID(uuid string, command string, args string, sync bool) (m *Message, err error) {
return c.SendMsg(map[string]string{
"call-command": "execute",
"execute-app-name": command,
"execute-app-arg": args,
"event-lock": strconv.FormatBool(sync),
}, uuid, "")
}
// SendMsg - Basically this func will send message to the opened connection
func (c *SocketConnection) SendMsg(msg map[string]string, uuid, data string) (m *Message, err error) {
b := bytes.NewBufferString("sendmsg")
if uuid != "" {
if strings.Contains(uuid, "\r\n") {
return nil, fmt.Errorf(EInvalidCommandProvided, msg)
}
b.WriteString(" " + uuid)
}
b.WriteString("\n")
for k, v := range msg {
if strings.Contains(k, "\r\n") {
return nil, fmt.Errorf(EInvalidCommandProvided, msg)
}
if v != "" {
if strings.Contains(v, "\r\n") {
return nil, fmt.Errorf(EInvalidCommandProvided, msg)
}
b.WriteString(fmt.Sprintf("%s: %s\n", k, v))
}
}
b.WriteString("\n")
if msg["content-length"] != "" && data != "" {
b.WriteString(data)
}
// lock mutex
c.mtx.Lock()
_, err = b.WriteTo(c)
if err != nil {
c.mtx.Unlock()
return nil, err
}
c.mtx.Unlock()
select {
case err := <-c.err:
return nil, err
case m := <-c.m:
return m, nil
}
}
// OriginatorAdd - Will return originator address known as net.RemoteAddr()
// This will actually be a freeswitch address
func (c *SocketConnection) OriginatorAddr() net.Addr {
return c.RemoteAddr()
}
// ReadMessage - Will read message from channels and return them back accordingy.
// If error is received, error will be returned. If not, message will be returned back!
func (c *SocketConnection) ReadMessage() (*Message, error) {
Debug("Waiting for connection message to be received ...")
select {
case err := <-c.err:
return nil, err
case msg := <-c.m:
return msg, nil
}
}
// Handle - Will handle new messages and close connection when there are no messages left to process
func (c *SocketConnection) Handle() {
done := make(chan bool)
rbuf := bufio.NewReaderSize(c, ReadBufferSize)
go func() {
for {
msg, err := newMessage(rbuf, true)
if err != nil {
c.err <- err
done <- true
break
}
c.m <- msg
}
}()
<-done
// Closing the connection now as there's nothing left to do ...
c.Close()
}
// Close - Will close down net connection and return error if error happen
func (c *SocketConnection) Close() error {
if err := c.Conn.Close(); err != nil {
return err
}
return nil
}