-
Notifications
You must be signed in to change notification settings - Fork 18
/
server.go
425 lines (345 loc) · 10.4 KB
/
server.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package kmip
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import (
"context"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"runtime"
"sync"
"time"
"github.com/pkg/errors"
)
// Server implements core KMIP server
type Server struct {
// Listen address
Addr string
// TLS Configuration for the server
TLSConfig *tls.Config
// Log destination (if not set, log is discarded)
Log *log.Logger
// Supported version of KMIP, in the order of the preference
//
// If not set, defaults to DefaultSupportedVersions
SupportedVersions []ProtocolVersion
// Network read & write timeouts
//
// If set to zero, timeouts are not enforced
ReadTimeout time.Duration
WriteTimeout time.Duration
// SessionAuthHandler is called after TLS handshake
//
// This handler might additionally verify client TLS cert or perform
// any other kind of auth (say, by soure address)
SessionAuthHandler func(conn net.Conn) (sessionAuth interface{}, err error)
// RequestAuthHandler is called for any request which has Authentication field set
//
// Value returned from RequestAuthHandler is stored as RequestContext.RequestAuth, which
// can be used to authorize each batch item in the request
RequestAuthHandler func(sesssion *SessionContext, auth *Authentication) (requestAuth interface{}, err error)
l net.Listener
mu sync.Mutex
wg sync.WaitGroup
doneChan chan struct{}
handlers map[Enum]Handler
}
// Handler processes specific KMIP operation
type Handler func(req *RequestContext, item *RequestBatchItem) (resp interface{}, err error)
// SessionContext is initialized for each connection
type SessionContext struct {
// Unique session identificator
SessionID string
// Additional opaque data related to connection auth, as returned by Server.SessionAuthHandler
SessionAuth interface{}
}
// RequestContext covers batch of requests
type RequestContext struct {
SessionContext
// RequestAuth captures result of request authentication
RequestAuth interface{}
}
// ListenAndServe creates TLS listening socket and calls Serve
//
// Channel initializedCh will be closed when listener is initialized
// (or fails to be initialized)
func (s *Server) ListenAndServe(initializedCh chan struct{}) error {
addr := s.Addr
if addr == "" {
addr = ":5696"
}
l, err := tls.Listen("tcp", addr, s.TLSConfig)
if err != nil {
close(initializedCh)
return err
}
return s.Serve(l, initializedCh)
}
// Serve starts accepting and serving KMIP connection on a given listener
//
// Channel initializedCh will be closed when listener is initialized
// (or fails to be initialized)
func (s *Server) Serve(l net.Listener, initializedCh chan struct{}) error {
s.mu.Lock()
s.l = l
if s.Log == nil {
s.Log = log.New(ioutil.Discard, "", log.LstdFlags)
}
if len(s.SupportedVersions) == 0 {
s.SupportedVersions = append([]ProtocolVersion(nil), DefaultSupportedVersions...)
}
if s.handlers == nil {
s.initHandlers()
}
s.mu.Unlock()
close(initializedCh)
defer l.Close()
lastSession := uint32(0)
var tempDelay time.Duration
for {
conn, err := l.Accept()
if err != nil {
select {
case <-s.getDoneChan():
return nil
default:
}
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
s.Log.Printf("[ERROR] Accept error: %s, retrying in %s", err, tempDelay)
time.Sleep(tempDelay)
continue
}
return err
}
lastSession++
tempDelay = 0
s.wg.Add(1)
go s.serve(conn, fmt.Sprintf("%08x", lastSession))
}
}
// Shutdown performs graceful shutdown of KMIP server waiting for connections to be closed
//
// Context might be used to limit time to wait for draining complete
func (s *Server) Shutdown(ctx context.Context) error {
close(s.getDoneChan())
s.mu.Lock()
if s.l != nil {
s.l.Close()
s.l = nil
}
s.mu.Unlock()
waitGroupDone := make(chan struct{})
go func() {
s.wg.Wait()
close(waitGroupDone)
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-waitGroupDone:
return nil
}
}
// Handle register handler for operation
//
// Server provides default handler for DISCOVER_VERSIONS operation, any other
// operation should be specifically enabled via Handle
func (s *Server) Handle(operation Enum, handler Handler) {
if s.handlers == nil {
s.initHandlers()
}
s.handlers[operation] = handler
}
func (s *Server) initHandlers() {
s.handlers = make(map[Enum]Handler)
s.handlers[OPERATION_DISCOVER_VERSIONS] = s.handleDiscoverVersions
}
func (s *Server) getDoneChan() chan struct{} {
s.mu.Lock()
defer s.mu.Unlock()
if s.doneChan == nil {
s.doneChan = make(chan struct{})
}
return s.doneChan
}
func (s *Server) serve(conn net.Conn, session string) {
defer s.wg.Done()
defer func() {
s.Log.Printf("[INFO] [%s] Closed connection from %s", session, conn.RemoteAddr().String())
conn.Close()
}()
s.Log.Printf("[INFO] [%s] New connection from %s", session, conn.RemoteAddr().String())
sessionCtx := &SessionContext{
SessionID: session,
}
if tlsConn, ok := conn.(*tls.Conn); ok {
if s.ReadTimeout != 0 {
_ = conn.SetReadDeadline(time.Now().Add(s.ReadTimeout))
}
if s.WriteTimeout != 0 {
_ = conn.SetWriteDeadline(time.Now().Add(s.WriteTimeout))
}
if err := tlsConn.Handshake(); err != nil {
s.Log.Printf("[ERROR] [%s] Error in TLS handshake: %s", session, err)
return
}
}
s.mu.Lock()
sessionAuthHandler := s.SessionAuthHandler
s.mu.Unlock()
if sessionAuthHandler != nil {
var err error
sessionCtx.SessionAuth, err = sessionAuthHandler(conn)
if err != nil {
s.Log.Printf("[ERROR] [%s] Error in session auth handler: %s", session, err)
return
}
}
d := NewDecoder(conn)
e := NewEncoder(conn)
for {
var req = &Request{}
if s.ReadTimeout != 0 {
_ = conn.SetReadDeadline(time.Now().Add(s.ReadTimeout))
}
err := d.Decode(req)
if err == io.EOF {
break
}
if err != nil {
s.Log.Printf("[ERROR] [%s] Error decoding KMIP message: %s", session, err)
break
}
var resp *Response
resp, err = s.handleBatch(sessionCtx, req)
if err != nil {
s.Log.Printf("[ERROR] [%s] Fatal error handling batch: %s", session, err)
break
}
if s.WriteTimeout != 0 {
_ = conn.SetWriteDeadline(time.Now().Add(s.WriteTimeout))
}
err = e.Encode(resp)
if err != nil {
s.Log.Printf("[ERROR] [%s] Error encoding KMIP response: %s", session, err)
}
}
}
func (s *Server) handleBatch(session *SessionContext, req *Request) (resp *Response, err error) {
if int(req.Header.BatchCount) != len(req.BatchItems) {
err = errors.Errorf("request batch count doesn't match number of batch items: %d != %d", req.Header.BatchCount, len(req.BatchItems))
return
}
if req.Header.AsynchronousIndicator {
err = errors.New("asynchnronous requests are not supported")
return
}
resp = &Response{
Header: ResponseHeader{
Version: req.Header.Version,
TimeStamp: time.Now(),
ClientCorrelationValue: req.Header.ClientCorrelationValue,
BatchCount: req.Header.BatchCount,
},
BatchItems: make([]ResponseBatchItem, req.Header.BatchCount),
}
requestCtx := &RequestContext{
SessionContext: *session,
}
if req.Header.Authentication.CredentialType != 0 {
if s.RequestAuthHandler == nil {
err = errors.New("request has authentication set, but no auth handler configured")
return
}
requestCtx.RequestAuth, err = s.RequestAuthHandler(session, &req.Header.Authentication)
if err != nil {
err = errors.Wrap(err, "error running auth handler")
return
}
}
for i := range req.BatchItems {
resp.BatchItems[i].Operation = req.BatchItems[i].Operation
resp.BatchItems[i].UniqueID = append([]byte(nil), req.BatchItems[i].UniqueID...)
var (
batchResp interface{}
batchErr error
)
batchResp, batchErr = s.handleWrapped(requestCtx, &req.BatchItems[i])
if batchErr != nil {
s.Log.Printf("[WARN] [%s] Request failed, operation %v: %s", requestCtx.SessionID, operationMap[req.BatchItems[i].Operation], batchErr)
resp.BatchItems[i].ResultStatus = RESULT_STATUS_OPERATION_FAILED
// TODO: should we skip returning error message? or return it only for specific errors?
resp.BatchItems[i].ResultMessage = batchErr.Error()
if protoErr, ok := batchErr.(Error); ok {
resp.BatchItems[i].ResultReason = protoErr.ResultReason()
} else {
resp.BatchItems[i].ResultReason = RESULT_REASON_GENERAL_FAILURE
}
} else {
s.Log.Printf("[INFO] [%s] Request processed, operation %v", requestCtx.SessionID, operationMap[req.BatchItems[i].Operation])
resp.BatchItems[i].ResultStatus = RESULT_STATUS_SUCCESS
resp.BatchItems[i].ResponsePayload = batchResp
}
}
return
}
func (s *Server) handleWrapped(request *RequestContext, item *RequestBatchItem) (resp interface{}, err error) {
defer func() {
if p := recover(); p != nil {
err = errors.Errorf("panic: %s", p)
buf := make([]byte, 8192)
n := runtime.Stack(buf, false)
s.Log.Printf("[ERROR] [%s] Panic in request handler, operation %s: %s", request.SessionID, operationMap[item.Operation], string(buf[:n]))
}
}()
handler := s.handlers[item.Operation]
if handler == nil {
err = wrapError(errors.New("operation not supported"), RESULT_REASON_OPERATION_NOT_SUPPORTED)
return
}
resp, err = handler(request, item)
return
}
func (s *Server) handleDiscoverVersions(req *RequestContext, item *RequestBatchItem) (resp interface{}, err error) {
response := DiscoverVersionsResponse{}
request, ok := item.RequestPayload.(DiscoverVersionsRequest)
if !ok {
err = wrapError(errors.New("wrong request body"), RESULT_REASON_INVALID_MESSAGE)
return
}
if len(request.ProtocolVersions) == 0 {
// return all the versions
response.ProtocolVersions = append([]ProtocolVersion(nil), s.SupportedVersions...)
} else {
// find matching versions
for _, version := range request.ProtocolVersions {
for _, v := range s.SupportedVersions {
if version == v {
response.ProtocolVersions = append(response.ProtocolVersions, v)
break
}
}
}
}
resp = response
return
}
// DefaultSupportedVersions is a default list of supported KMIP versions
var DefaultSupportedVersions = []ProtocolVersion{
{Major: 1, Minor: 4},
{Major: 1, Minor: 3},
{Major: 1, Minor: 2},
{Major: 1, Minor: 1},
}