forked from james-barrow/golang-ipc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver_all.go
executable file
·323 lines (231 loc) · 5.55 KB
/
server_all.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
package ipc
import (
"bufio"
"errors"
"time"
)
var (
defaultServerConfig = ServerConfig{
MaxMsgSize: defaultMaxMsgSize,
}
defaultClientConfig = ClientConfig{
RetryTimer: defaultRetryTimer,
}
)
// StartServer - starts the ipc server.
//
// ipcName = is the name of the unix socket or named pipe that will be created.
// timeout = number of seconds before the socket/pipe times out waiting for a connection/re-cconnection - if -1 or 0 it never times out.
//
func StartServer(ipcName string, config ServerConfig) (*Server, error) {
err := checkIpcName(ipcName)
if err != nil {
return nil, err
}
sc := &Server{
name: ipcName,
status: NotConnected,
received: make(chan *Message),
toWrite: make(chan *Message),
conf: config,
}
if sc.conf.Timeout <= 0 {
sc.conf.Timeout = defaultServerConfig.Timeout
}
if sc.conf.MaxMsgSize < minMsgSize {
sc.conf.MaxMsgSize = defaultServerConfig.MaxMsgSize
}
if sc.conf.SocketBasePath == "" {
sc.conf.SocketBasePath = defaultServerConfig.SocketBasePath
}
go startServer(sc)
return sc, err
}
func startServer(sc *Server) {
err := sc.run()
if err != nil {
sc.received <- &Message{err: err, MsgType: -2}
}
}
func (sc *Server) acceptLoop() {
for {
conn, err := sc.listen.Accept()
if err != nil {
break
}
if sc.status == Listening || sc.status == ReConnecting {
sc.conn = conn
err2 := sc.handshake()
if err2 != nil {
sc.received <- &Message{err: err2, MsgType: -2}
sc.status = Error
sc.listen.Close()
sc.conn.Close()
} else {
go sc.read()
go sc.write()
sc.status = Connected
sc.received <- &Message{Status: sc.status.String(), MsgType: -1}
sc.connChannel <- true
}
}
}
}
func (sc *Server) connectionTimer() error {
if sc.conf.Timeout != 0 {
ticker := time.NewTicker(sc.conf.Timeout)
defer ticker.Stop()
select {
case <-sc.connChannel:
return nil
case <-ticker.C:
sc.listen.Close()
return errors.New("Timed out waiting for client to connect")
}
}
select {
case <-sc.connChannel:
return nil
}
}
func (sc *Server) read() {
bLen := make([]byte, 4)
for {
res := sc.readData(bLen)
if res == false {
break
}
mLen := bytesToInt(bLen)
msgRecvd := make([]byte, mLen)
res = sc.readData(msgRecvd)
if res == false {
break
}
if sc.conf.Encryption {
msgFinal, err := decrypt(*sc.enc.cipher, msgRecvd)
if err != nil {
sc.received <- &Message{err: err, MsgType: -2}
continue
}
if bytesToInt(msgFinal[:4]) == 0 {
// type 0 = control message
} else {
sc.received <- &Message{Data: msgFinal[4:], MsgType: bytesToInt(msgFinal[:4])}
}
} else {
if bytesToInt(msgRecvd[:4]) == 0 {
// type 0 = control message
} else {
sc.received <- &Message{Data: msgRecvd[4:], MsgType: bytesToInt(msgRecvd[:4])}
}
}
}
}
func (sc *Server) readData(buff []byte) bool {
_, err := sc.conn.Read(buff)
if err != nil {
if sc.status == Closing {
sc.status = Closed
return false
}
go sc.reConnect()
return false
}
return true
}
func (sc *Server) reConnect() {
sc.status = ReConnecting
sc.received <- &Message{Status: sc.status.String(), MsgType: -1}
err := sc.connectionTimer()
if err != nil {
sc.status = Timeout
sc.received <- &Message{Status: sc.status.String(), MsgType: -1}
sc.received <- &Message{err: err, MsgType: -2}
}
}
// Read - blocking function that waits until an non multipart message is received
func (sc *Server) Read() (*Message, error) {
m, ok := (<-sc.received)
if ok == false {
return nil, errors.New("the receive channel has been closed")
}
if m.err != nil {
return nil, m.err
}
return m, nil
}
// Write - writes a non multipart message to the ipc connection.
// msgType - denotes the type of data being sent. 0 is a reserved type for internal messages and errors.
//
func (sc *Server) Write(msgType int, message []byte) error {
if msgType == 0 {
return errors.New("Message type 0 is reserved")
}
mlen := len(message)
if mlen > sc.conf.MaxMsgSize {
return errors.New("Message exceeds maximum message length")
}
if sc.status == Connected {
sc.toWrite <- &Message{MsgType: msgType, Data: message}
} else {
return errors.New(sc.status.String())
}
return nil
}
func (sc *Server) write() {
for {
m, ok := <-sc.toWrite
if ok == false {
break
}
toSend := intToBytes(m.MsgType)
writer := bufio.NewWriter(sc.conn)
if sc.conf.Encryption {
toSend = append(toSend, m.Data...)
toSendEnc, err := encrypt(*sc.enc.cipher, toSend)
if err != nil {
//return err
}
toSend = toSendEnc
} else {
toSend = append(toSend, m.Data...)
}
writer.Write(intToBytes(len(toSend)))
writer.Write(toSend)
err := writer.Flush()
if err != nil {
//return err
}
time.Sleep(2 * time.Millisecond)
}
}
// getStatus - get the current status of the connection
func (sc *Server) getStatus() Status {
return sc.status
}
// StatusCode - returns the current connection status
func (sc *Server) StatusCode() Status {
return sc.status
}
// Status - returns the current connection status as a string
func (sc *Server) Status() string {
return sc.status.String()
}
// Close - closes the connection
func (sc *Server) Close() {
sc.status = Closing
if sc.listen != nil {
sc.listen.Close()
}
if sc.conn != nil {
sc.conn.Close()
}
if sc.received != nil {
sc.received <- &Message{Status: sc.status.String(), MsgType: -1}
sc.received <- &Message{err: errors.New("Server has closed the connection"), MsgType: -2}
close(sc.received)
}
if sc.toWrite != nil {
close(sc.toWrite)
}
}