forked from DanielKrawisz/bmd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpcserver.go
More file actions
264 lines (229 loc) · 6.98 KB
/
Copy pathrpcserver.go
File metadata and controls
264 lines (229 loc) · 6.98 KB
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
// Originally derived from: btcsuite/btcd/rpcserver.go
// Copyright (c) 2013-2015 The btcsuite developers.
// Copyright (c) 2015 Monetas.
// Copyright 2016 Daniel Krawisz.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
prand "math/rand"
"net"
"os"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcutil"
pb "github.com/DanielKrawisz/bmd/rpcproto"
"github.com/DanielKrawisz/bmutil/wire"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
)
const (
// rpcCounterObjectsSize is the number of objects that db.FetchObjectsFromCounter
// will fetch per query to the database. This is used when a client requests
// subscription to an object type from a specified counter value.
rpcCounterObjectsSize = 100
)
// rpcServer holds the items the rpc server may need to access (config,
// shutdown, main server, etc.)
type rpcServer struct {
server *server
rpcSrv *grpc.Server
listeners []net.Listener
limitauthsha [sha256.Size]byte
authsha [sha256.Size]byte
mutex sync.RWMutex
started int32
shutdown int32
wg sync.WaitGroup
// Conds for notifying listening clients about pending objects. Key is the
// string representation of the object type.
objConds map[string]*sync.Cond
quit chan int
}
// genCertPair generates a key/cert pair to the paths provided.
func genCertPair(certFile, keyFile string) error {
rpcLog.Infof("Generating TLS certificates...")
org := "bmd autogenerated cert"
validUntil := time.Now().Add(10 * 365 * 24 * time.Hour)
cert, key, err := btcutil.NewTLSCertPair(org, validUntil, nil)
if err != nil {
return err
}
// Write cert and key files.
if err = ioutil.WriteFile(certFile, cert, 0666); err != nil {
return err
}
if err = ioutil.WriteFile(keyFile, key, 0600); err != nil {
os.Remove(certFile)
return err
}
rpcLog.Infof("Done generating TLS certificates")
return nil
}
// restrictAuth restricts access of the client, returning an error if the client
// is not already authenticated.
func (s *rpcServer) restrictAuth(ctx context.Context) codes.Code {
md, ok := metadata.FromContext(ctx)
if !ok {
return codes.Unauthenticated
}
login, ok := md["authorization"]
if !ok {
return codes.Unauthenticated
}
authsha := sha256.Sum256([]byte(login[0]))
// Check for limited auth first as in environments with limited users, those
// are probably expected to have a higher volume of calls
limitcmp := subtle.ConstantTimeCompare(authsha[:], s.limitauthsha[:])
if limitcmp == 1 {
return codes.OK
}
// Check for admin-level auth
cmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])
if cmp == 1 {
return codes.OK
}
return codes.PermissionDenied
}
// restrictAdmin restricts access of the client, returning an error if the
// client is not already authenticated as an admin.
func (s *rpcServer) restrictAdmin(ctx context.Context) codes.Code {
md, ok := metadata.FromContext(ctx)
if !ok {
return codes.Unauthenticated
}
login, ok := md["authorization"]
if !ok {
return codes.Unauthenticated
}
authsha := sha256.Sum256([]byte(login[0]))
// Check for admin-level auth
cmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])
if cmp == 1 {
return codes.OK
}
return codes.PermissionDenied
}
// NotifyObject is used to notify the RPC server of any new objects so that it
// can send those onwards to the client.
func (s *rpcServer) NotifyObject(objType wire.ObjectType) {
s.objConds[objType.String()].Broadcast()
}
// newRPCServer returns a new instance of the rpcServer struct.
func newRPCServer(listenAddrs []string, s *server) (*rpcServer, error) {
// Setup TLS if not disabled.
listenFunc := net.Listen
var opts []grpc.ServerOption
if !cfg.DisableTLS {
if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
err := genCertPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
}
creds, err := credentials.NewServerTLSFromFile(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, fmt.Errorf("Failed to generate credentials %v", err)
}
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
rpc := rpcServer{
server: s,
rpcSrv: grpc.NewServer(opts...), // Create the underlying RPC server.
quit: make(chan int),
objConds: map[string]*sync.Cond{
wire.ObjectTypeGetPubKey.String(): sync.NewCond(&sync.Mutex{}),
wire.ObjectTypePubKey.String(): sync.NewCond(&sync.Mutex{}),
wire.ObjectTypeMsg.String(): sync.NewCond(&sync.Mutex{}),
wire.ObjectTypeBroadcast.String(): sync.NewCond(&sync.Mutex{}),
wire.ObjectType(999).String(): sync.NewCond(&sync.Mutex{}), // Unknown
},
}
pb.RegisterBmdServer(rpc.rpcSrv, &rpc)
if cfg.RPCUser != "" && cfg.RPCPass != "" {
login := base64.StdEncoding.EncodeToString([]byte(cfg.RPCUser + ":" +
cfg.RPCPass))
rpc.authsha = sha256.Sum256([]byte("Basic " + login))
}
if cfg.RPCLimitUser != "" && cfg.RPCLimitPass != "" {
login := base64.StdEncoding.EncodeToString([]byte(cfg.RPCLimitUser + ":" +
cfg.RPCLimitPass))
rpc.limitauthsha = sha256.Sum256([]byte("Basic " + login))
}
ipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)
if err != nil {
return nil, err
}
listeners := make([]net.Listener, 0,
len(ipv6ListenAddrs)+len(ipv4ListenAddrs))
for _, addr := range ipv4ListenAddrs {
listener, err := listenFunc("tcp4", addr)
if err != nil {
rpcLog.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
for _, addr := range ipv6ListenAddrs {
listener, err := listenFunc("tcp6", addr)
if err != nil {
rpcLog.Warnf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
if len(listeners) == 0 {
return nil, errors.New("RPC: No valid listen address")
}
rpc.listeners = listeners
return &rpc, nil
}
// Stop is used by server.go to stop the rpc listener.
func (s *rpcServer) Stop() error {
if atomic.AddInt32(&s.shutdown, 1) != 1 {
rpcLog.Infof("RPC server is already in the process of shutting down")
return nil
}
rpcLog.Warnf("RPC server shutting down")
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
rpcLog.Errorf("Problem shutting down rpc: %v", err)
return err
}
}
close(s.quit)
s.wg.Wait()
rpcLog.Infof("RPC server shutdown complete")
return nil
}
// Start is used by server.go to start the rpc listener.
func (s *rpcServer) Start() {
if atomic.AddInt32(&s.started, 1) != 1 {
return
}
rpcLog.Trace("Starting RPC server")
// Start listening on the listeners.
for _, listener := range s.listeners {
s.wg.Add(1)
go func(listener net.Listener) {
rpcLog.Infof("RPC server listening on %s", listener.Addr())
s.rpcSrv.Serve(listener)
rpcLog.Tracef("RPC listener done for %s", listener.Addr())
s.wg.Done()
}(listener)
}
}
func init() {
prand.Seed(time.Now().UnixNano())
}