This repository has been archived by the owner on Sep 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lrpcclient.go
331 lines (268 loc) · 9.16 KB
/
lrpcclient.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
package lrpc
import (
"bytes"
"encoding/binary"
"fmt"
"math/rand"
"net"
"os"
"time"
"github.com/centrify/platform-go-sdk/internal/logging"
)
// type lrpc2Client represents a LRPC2 client session. It must implement the MessageClient interface
type lrpc2Client struct {
lrpc2HeaderV4
endpoint string // end point information
conn net.Conn // network connection
config *lrpc2ClientConfig // lrpc2 client config
maxMsgDataLen uint32 // maximum data size
sessionPid uint64 // session Pid
}
type lrpc2ClientConfig struct {
// LRPC2 client-side timeout when establishing connection (handshake)
ConnectTimeout time.Duration
// LRPC2 client-side timeout when reading data from server reply
ReceiveTimeout time.Duration
// LRPC2 client-side timeout when sending request to server
SendTimeout time.Duration
}
func newLrpc2ClientConfig() *lrpc2ClientConfig {
return &lrpc2ClientConfig{
ConnectTimeout: lrpc2ConnectTimeout,
ReceiveTimeout: lrpc2ReceiveTimeout,
SendTimeout: lrpc2SendTimeout,
}
}
// initLrpc2ClientSession init a new LRPC2 client session object.
func initLrpc2ClientSession(endpoint string, config *lrpc2ClientConfig) *lrpc2Client {
c := new(lrpc2Client)
c.magicNum = lrpc2MagicNum
c.headerLen = lrpc2HeaderLengthV4
c.version = lrpc2Version4
c.endpoint = endpoint
c.config = config
return c
}
// NewLrpc2ClientSession create a new LRPC2 client session object.
func NewLrpc2ClientSession(endpoint string) MessageClient {
config := newLrpc2ClientConfig()
c := initLrpc2ClientSession(endpoint, config)
if config == nil || c == nil {
logging.Errorf("LRPC Client: Cannot init client session for endpoint %s", endpoint)
return nil
}
// seed random number
rand.Seed(time.Now().UnixNano())
return c
}
func (c *lrpc2Client) IsNamedMessagesSupported() bool {
return false
}
func (c *lrpc2Client) doHandShake() error {
var err error
// Note that the connection timeout is for the whole handshake. So no
// need to set again for every read/write operation.
now := time.Now()
err = c.conn.SetDeadline(now.Add(c.config.ConnectTimeout))
if err != nil {
logging.Infof("Failed to set timeout for LRPC2 connection [%p]: %v", c.conn, err)
return err
}
logging.Tracef("LRPC2 client: Handshaking for LRPC2 connection [%p] with timeout %v...", c.conn, c.config.ConnectTimeout)
var reqbytes = make([]byte, 0, lrpc2HandshakeRequestSize)
var req = bytes.NewBuffer(reqbytes)
err = binary.Write(req, lrpc2ByteOrder, uint32(lrpc2Version4))
if err != nil {
logging.Errorf("LRPC2 client: Internal error. Failed to write LRPC version information to buffer: %v", err)
return err
}
_, err = c.conn.Write(req.Bytes())
if err != nil {
logging.Errorf("LRPC2 client: Internal error. Failed to send LRPC version information to server: %v", err)
return err
}
logging.Trace("LRPC2 client: Sent handshake request, waiting for reply")
bytesReply := make([]byte, lrpc2HandshakeReplyV4Size)
_, err = c.conn.Read(bytesReply)
if err != nil {
logging.Debugf("LRPC2 client: Failed to receive handshake reply: %v", err)
return err
}
var answer uint32
var maxMsgDataLen uint32
reply := bytes.NewBuffer(bytesReply)
err = binary.Read(reply, lrpc2ByteOrder, &answer)
if err != nil {
logging.Debugf("LRPC2 client: Failed to read answer from handshake reply: %v", err)
return err
}
if answer == lrpc2Nack {
message := "LRPC2 handshake rejected"
logging.Debugf("LRPC2 client: %s", message)
return fmt.Errorf(message)
}
err = binary.Read(reply, lrpc2ByteOrder, &maxMsgDataLen)
if err != nil {
logging.Debugf("LRPC2 client: Failed to read mesasge body size limit from handshake reply: %v", err)
return err
}
c.maxMsgDataLen = maxMsgDataLen
c.sequenceNum = rand.Uint32()
c.pid = uint64(os.Getpid())
c.sessionPid = c.pid
logging.Tracef("LRPC2 client handshake completed. MaxMsgDataLen: %d, seqNum: %d PID: %d",
c.maxMsgDataLen, c.sequenceNum, c.pid)
return nil
}
func (c *lrpc2Client) Connect() error {
logging.Tracef("LRPC2 client: Connecting to LRPC server %s...", c.endpoint)
conn, err := ConnectToServer(c.endpoint)
if err != nil {
logging.Debugf("LRPC2 client: cannot connect to %s: %v", c.endpoint, err)
return err
}
c.conn = conn
err = c.doHandShake()
if err != nil {
errClose := conn.Close()
if errClose != nil {
logging.Errorf("LRPC2 client: Failed to close LRPC connection [%p] after handshake failure: %v",
conn, errClose)
}
return err
}
logging.Trace("LRPC2 client: Handshake completed successfully")
return nil
}
func (c *lrpc2Client) WriteRequest(cmd interface{}, args []interface{}) error {
var err error
now := time.Now()
err = c.conn.SetDeadline(now.Add(c.config.SendTimeout))
if err != nil {
logging.Infof("Failed to set timeout for LRPC2 connection [%p]: %v", c.conn, err)
return err
}
logging.Tracef("LRPC2 client: Sending request to LRPC2 connection [%p] with timeout %v...", c.conn, c.config.SendTimeout)
defer c.setupNextRequest(c.sequenceNum + 1)
// note that the cmd may be specified as an int, uint, uint16, uint32
// make sure that it can fit into a uint16 value
var iReq uint16
switch cmd.(type) {
case int:
v := cmd.(int)
iReq = uint16(v)
if uint64(iReq) != uint64(v) {
logging.Errorf("LRPC2 client: Command value %v of type %T does not fit into uint16.", cmd, cmd)
return ErrLrpcServerCommandOutOfRange
}
case uint:
v := cmd.(uint)
iReq = uint16(v)
if uint64(iReq) != uint64(v) {
logging.Errorf("LRPC2 client: Command value %v of type %T does not fit into uint16.", cmd, cmd)
return ErrLrpcServerCommandOutOfRange
}
case uint16:
iReq = cmd.(uint16)
case uint32:
v := cmd.(uint32)
iReq = uint16(v)
if uint64(iReq) != uint64(v) {
logging.Errorf("LRPC2 client: Command value %v of type %T does not fit into uint16.", cmd, cmd)
return ErrLrpcServerCommandOutOfRange
}
default:
// LRPC2 only support messages by ID
logging.Errorf("LRPC2 client: Sending command by name [%v] (type %T) is not supported.", cmd, cmd)
return ErrLrpc2NameNotSupported
}
// LRPC2 expects the command to be type uint16
msgData, err := encode(iReq, args)
if err != nil {
return err
}
// check if size is supported
if uint64(msgData.Len()) > uint64(c.maxMsgDataLen) {
return ErrLrpc2MsgTooLong
}
// allocate a big byte array to store the full message
c.msgDataLen = uint32(msgData.Len())
bytesMsg := make([]byte, 0, c.HeaderLen()+int(c.msgDataLen))
msg := bytes.NewBuffer(bytesMsg)
// set up message header
c.timestamp = uint64(time.Now().Unix())
err = c.encodeHeader(msg)
if err != nil {
return err
}
// Add real data
err = binary.Write(msg, lrpc2ByteOrder, msgData.Bytes())
if err != nil {
logging.Errorf("LRPC client: Cannot write message content to out buffer: %v", err)
return err
}
// send data to remote
_, err = c.conn.Write(msg.Bytes())
logging.Tracef("LRPC client: message sent. sequence number: %d", c.sequenceNum)
return err
}
// ReadResponse() reads the response for the request just sent....
func (c *lrpc2Client) ReadResponse() ([]interface{}, error) {
var err error
now := time.Now()
err = c.conn.SetDeadline(now.Add(c.config.ReceiveTimeout))
if err != nil {
logging.Infof("Failed to set timeout for LRPC2 connection [%p]: %v", c.conn, err)
return nil, err
}
logging.Tracef("LRPC2 client: Receiving reply from LRPC2 connection [%p] with timeout %v...", c.conn, c.config.ReceiveTimeout)
logging.Tracef("LRPC client: Entering ReadResponse for request ID: %d", c.sequenceNum)
expectSeq := c.sequenceNum - 1
bytesMsgHeader := make([]byte, c.HeaderLen())
_, err = c.conn.Read(bytesMsgHeader)
if err != nil {
logging.Errorf("LRPC client: Error in reading response header: %v", err)
return nil, err
}
msgHeader := bytes.NewBuffer(bytesMsgHeader)
err = c.decodeHeader(msgHeader)
if err != nil {
logging.Errorf("LRPC client: Error in decoding response header: %v", err)
return nil, err
}
// verify header
err = c.verifyHeader()
if err != nil {
logging.Errorf("LRPC client: Error in verifying header: %v", err)
return nil, err
}
// verify sequence number
if c.sequenceNum != expectSeq {
logging.Errorf("LRPC client: Expect response sequence number: %d, got %d", expectSeq, c.sequenceNum)
return nil, ErrLrpc2SeqNumMismatch
}
logging.Tracef("LRPC client: Reading message data from LRPC connection [%p]. Expected size: %d bytes", c.conn, c.msgDataLen)
bytesMsgData := make([]byte, c.msgDataLen)
_, err = c.conn.Read(bytesMsgData)
if err != nil {
logging.Errorf("LRPC client: Error in reading message data from LRPC connection [%p]: %v", c.conn, err)
return nil, err
}
msgData := bytes.NewBuffer(bytesMsgData)
logging.Tracef("LRPC client: Received %d bytes of message data from LRPC connection [%p] ", c.msgDataLen, c.conn)
_, rest, err := decode(msgData)
if err != nil {
logging.Errorf("LRPC client: Error in decoding response: %v", err)
return nil, err
}
logging.Tracef("LRPC client: Return %d values", len(rest))
return rest, nil
}
// setupNextRequest() resets the header and context for the next request
// seqNum: next sequence number
func (c *lrpc2Client) setupNextRequest(seqNum uint32) {
c.sequenceNum = seqNum
}
func (c *lrpc2Client) Close() error {
return c.conn.Close()
}