github.com/luckypickle/go-ethereum-vet@v1.14.2/rpc/server.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package rpc 18 19 import ( 20 "context" 21 "fmt" 22 "reflect" 23 "runtime" 24 "strings" 25 "sync" 26 "sync/atomic" 27 28 mapset "github.com/deckarep/golang-set" 29 "github.com/luckypickle/go-ethereum-vet/log" 30 ) 31 32 const MetadataApi = "rpc" 33 34 // CodecOption specifies which type of messages this codec supports 35 type CodecOption int 36 37 const ( 38 // OptionMethodInvocation is an indication that the codec supports RPC method calls 39 OptionMethodInvocation CodecOption = 1 << iota 40 41 // OptionSubscriptions is an indication that the codec suports RPC notifications 42 OptionSubscriptions = 1 << iota // support pub sub 43 ) 44 45 // NewServer will create a new server instance with no registered handlers. 46 func NewServer() *Server { 47 server := &Server{ 48 services: make(serviceRegistry), 49 codecs: mapset.NewSet(), 50 run: 1, 51 } 52 53 // register a default service which will provide meta information about the RPC service such as the services and 54 // methods it offers. 55 rpcService := &RPCService{server} 56 server.RegisterName(MetadataApi, rpcService) 57 58 return server 59 } 60 61 // RPCService gives meta information about the server. 62 // e.g. gives information about the loaded modules. 63 type RPCService struct { 64 server *Server 65 } 66 67 // Modules returns the list of RPC services with their version number 68 func (s *RPCService) Modules() map[string]string { 69 modules := make(map[string]string) 70 for name := range s.server.services { 71 modules[name] = "1.0" 72 } 73 return modules 74 } 75 76 // RegisterName will create a service for the given rcvr type under the given name. When no methods on the given rcvr 77 // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is 78 // created and added to the service collection this server instance serves. 79 func (s *Server) RegisterName(name string, rcvr interface{}) error { 80 if s.services == nil { 81 s.services = make(serviceRegistry) 82 } 83 84 svc := new(service) 85 svc.typ = reflect.TypeOf(rcvr) 86 rcvrVal := reflect.ValueOf(rcvr) 87 88 if name == "" { 89 return fmt.Errorf("no service name for type %s", svc.typ.String()) 90 } 91 if !isExported(reflect.Indirect(rcvrVal).Type().Name()) { 92 return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name()) 93 } 94 95 methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ) 96 97 if len(methods) == 0 && len(subscriptions) == 0 { 98 return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) 99 } 100 101 // already a previous service register under given name, merge methods/subscriptions 102 if regsvc, present := s.services[name]; present { 103 for _, m := range methods { 104 regsvc.callbacks[formatName(m.method.Name)] = m 105 } 106 for _, s := range subscriptions { 107 regsvc.subscriptions[formatName(s.method.Name)] = s 108 } 109 return nil 110 } 111 112 svc.name = name 113 svc.callbacks, svc.subscriptions = methods, subscriptions 114 115 s.services[svc.name] = svc 116 return nil 117 } 118 119 // serveRequest will reads requests from the codec, calls the RPC callback and 120 // writes the response to the given codec. 121 // 122 // If singleShot is true it will process a single request, otherwise it will handle 123 // requests until the codec returns an error when reading a request (in most cases 124 // an EOF). It executes requests in parallel when singleShot is false. 125 func (s *Server) serveRequest(ctx context.Context, codec ServerCodec, singleShot bool, options CodecOption) error { 126 var pend sync.WaitGroup 127 128 defer func() { 129 if err := recover(); err != nil { 130 const size = 64 << 10 131 buf := make([]byte, size) 132 buf = buf[:runtime.Stack(buf, false)] 133 log.Error(string(buf)) 134 } 135 s.codecsMu.Lock() 136 s.codecs.Remove(codec) 137 s.codecsMu.Unlock() 138 }() 139 140 // ctx, cancel := context.WithCancel(context.Background()) 141 ctx, cancel := context.WithCancel(ctx) 142 defer cancel() 143 144 // if the codec supports notification include a notifier that callbacks can use 145 // to send notification to clients. It is tied to the codec/connection. If the 146 // connection is closed the notifier will stop and cancels all active subscriptions. 147 if options&OptionSubscriptions == OptionSubscriptions { 148 ctx = context.WithValue(ctx, notifierKey{}, newNotifier(codec)) 149 } 150 s.codecsMu.Lock() 151 if atomic.LoadInt32(&s.run) != 1 { // server stopped 152 s.codecsMu.Unlock() 153 return &shutdownError{} 154 } 155 s.codecs.Add(codec) 156 s.codecsMu.Unlock() 157 158 // test if the server is ordered to stop 159 for atomic.LoadInt32(&s.run) == 1 { 160 reqs, batch, err := s.readRequest(codec) 161 if err != nil { 162 // If a parsing error occurred, send an error 163 if err.Error() != "EOF" { 164 log.Debug(fmt.Sprintf("read error %v\n", err)) 165 codec.Write(codec.CreateErrorResponse(nil, err)) 166 } 167 // Error or end of stream, wait for requests and tear down 168 pend.Wait() 169 return nil 170 } 171 172 // check if server is ordered to shutdown and return an error 173 // telling the client that his request failed. 174 if atomic.LoadInt32(&s.run) != 1 { 175 err = &shutdownError{} 176 if batch { 177 resps := make([]interface{}, len(reqs)) 178 for i, r := range reqs { 179 resps[i] = codec.CreateErrorResponse(&r.id, err) 180 } 181 codec.Write(resps) 182 } else { 183 codec.Write(codec.CreateErrorResponse(&reqs[0].id, err)) 184 } 185 return nil 186 } 187 // If a single shot request is executing, run and return immediately 188 if singleShot { 189 if batch { 190 s.execBatch(ctx, codec, reqs) 191 } else { 192 s.exec(ctx, codec, reqs[0]) 193 } 194 return nil 195 } 196 // For multi-shot connections, start a goroutine to serve and loop back 197 pend.Add(1) 198 199 go func(reqs []*serverRequest, batch bool) { 200 defer pend.Done() 201 if batch { 202 s.execBatch(ctx, codec, reqs) 203 } else { 204 s.exec(ctx, codec, reqs[0]) 205 } 206 }(reqs, batch) 207 } 208 return nil 209 } 210 211 // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the 212 // response back using the given codec. It will block until the codec is closed or the server is 213 // stopped. In either case the codec is closed. 214 func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) { 215 defer codec.Close() 216 s.serveRequest(context.Background(), codec, false, options) 217 } 218 219 // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not 220 // close the codec unless a non-recoverable error has occurred. Note, this method will return after 221 // a single request has been processed! 222 func (s *Server) ServeSingleRequest(ctx context.Context, codec ServerCodec, options CodecOption) { 223 s.serveRequest(ctx, codec, true, options) 224 } 225 226 // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, 227 // close all codecs which will cancel pending requests/subscriptions. 228 func (s *Server) Stop() { 229 if atomic.CompareAndSwapInt32(&s.run, 1, 0) { 230 log.Debug("RPC Server shutdown initiatied") 231 s.codecsMu.Lock() 232 defer s.codecsMu.Unlock() 233 s.codecs.Each(func(c interface{}) bool { 234 c.(ServerCodec).Close() 235 return true 236 }) 237 } 238 } 239 240 // createSubscription will call the subscription callback and returns the subscription id or error. 241 func (s *Server) createSubscription(ctx context.Context, c ServerCodec, req *serverRequest) (ID, error) { 242 // subscription have as first argument the context following optional arguments 243 args := []reflect.Value{req.callb.rcvr, reflect.ValueOf(ctx)} 244 args = append(args, req.args...) 245 reply := req.callb.method.Func.Call(args) 246 247 if !reply[1].IsNil() { // subscription creation failed 248 return "", reply[1].Interface().(error) 249 } 250 251 return reply[0].Interface().(*Subscription).ID, nil 252 } 253 254 // handle executes a request and returns the response from the callback. 255 func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) (interface{}, func()) { 256 if req.err != nil { 257 return codec.CreateErrorResponse(&req.id, req.err), nil 258 } 259 260 if req.isUnsubscribe { // cancel subscription, first param must be the subscription id 261 if len(req.args) >= 1 && req.args[0].Kind() == reflect.String { 262 notifier, supported := NotifierFromContext(ctx) 263 if !supported { // interface doesn't support subscriptions (e.g. http) 264 return codec.CreateErrorResponse(&req.id, &callbackError{ErrNotificationsUnsupported.Error()}), nil 265 } 266 267 subid := ID(req.args[0].String()) 268 if err := notifier.unsubscribe(subid); err != nil { 269 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 270 } 271 272 return codec.CreateResponse(req.id, true), nil 273 } 274 return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as first argument"}), nil 275 } 276 277 if req.callb.isSubscribe { 278 subid, err := s.createSubscription(ctx, codec, req) 279 if err != nil { 280 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 281 } 282 283 // active the subscription after the sub id was successfully sent to the client 284 activateSub := func() { 285 notifier, _ := NotifierFromContext(ctx) 286 notifier.activate(subid, req.svcname) 287 } 288 289 return codec.CreateResponse(req.id, subid), activateSub 290 } 291 292 // regular RPC call, prepare arguments 293 if len(req.args) != len(req.callb.argTypes) { 294 rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d", 295 req.svcname, serviceMethodSeparator, req.callb.method.Name, 296 len(req.callb.argTypes), len(req.args))} 297 return codec.CreateErrorResponse(&req.id, rpcErr), nil 298 } 299 300 arguments := []reflect.Value{req.callb.rcvr} 301 if req.callb.hasCtx { 302 arguments = append(arguments, reflect.ValueOf(ctx)) 303 } 304 if len(req.args) > 0 { 305 arguments = append(arguments, req.args...) 306 } 307 308 // execute RPC method and return result 309 reply := req.callb.method.Func.Call(arguments) 310 if len(reply) == 0 { 311 return codec.CreateResponse(req.id, nil), nil 312 } 313 if req.callb.errPos >= 0 { // test if method returned an error 314 if !reply[req.callb.errPos].IsNil() { 315 e := reply[req.callb.errPos].Interface().(error) 316 res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()}) 317 return res, nil 318 } 319 } 320 return codec.CreateResponse(req.id, reply[0].Interface()), nil 321 } 322 323 // exec executes the given request and writes the result back using the codec. 324 func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) { 325 var response interface{} 326 var callback func() 327 if req.err != nil { 328 response = codec.CreateErrorResponse(&req.id, req.err) 329 } else { 330 response, callback = s.handle(ctx, codec, req) 331 } 332 333 if err := codec.Write(response); err != nil { 334 log.Error(fmt.Sprintf("%v\n", err)) 335 codec.Close() 336 } 337 338 // when request was a subscribe request this allows these subscriptions to be actived 339 if callback != nil { 340 callback() 341 } 342 } 343 344 // execBatch executes the given requests and writes the result back using the codec. 345 // It will only write the response back when the last request is processed. 346 func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) { 347 responses := make([]interface{}, len(requests)) 348 var callbacks []func() 349 for i, req := range requests { 350 if req.err != nil { 351 responses[i] = codec.CreateErrorResponse(&req.id, req.err) 352 } else { 353 var callback func() 354 if responses[i], callback = s.handle(ctx, codec, req); callback != nil { 355 callbacks = append(callbacks, callback) 356 } 357 } 358 } 359 360 if err := codec.Write(responses); err != nil { 361 log.Error(fmt.Sprintf("%v\n", err)) 362 codec.Close() 363 } 364 365 // when request holds one of more subscribe requests this allows these subscriptions to be activated 366 for _, c := range callbacks { 367 c() 368 } 369 } 370 371 // readRequest requests the next (batch) request from the codec. It will return the collection 372 // of requests, an indication if the request was a batch, the invalid request identifier and an 373 // error when the request could not be read/parsed. 374 func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, Error) { 375 reqs, batch, err := codec.ReadRequestHeaders() 376 if err != nil { 377 return nil, batch, err 378 } 379 380 requests := make([]*serverRequest, len(reqs)) 381 382 // verify requests 383 for i, r := range reqs { 384 var ok bool 385 var svc *service 386 387 if r.err != nil { 388 requests[i] = &serverRequest{id: r.id, err: r.err} 389 continue 390 } 391 392 if r.isPubSub && strings.HasSuffix(r.method, unsubscribeMethodSuffix) { 393 requests[i] = &serverRequest{id: r.id, isUnsubscribe: true} 394 argTypes := []reflect.Type{reflect.TypeOf("")} // expect subscription id as first arg 395 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 396 requests[i].args = args 397 } else { 398 requests[i].err = &invalidParamsError{err.Error()} 399 } 400 continue 401 } 402 403 if svc, ok = s.services[r.service]; !ok { // rpc method isn't available 404 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 405 continue 406 } 407 408 if r.isPubSub { // eth_subscribe, r.method contains the subscription method name 409 if callb, ok := svc.subscriptions[r.method]; ok { 410 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 411 if r.params != nil && len(callb.argTypes) > 0 { 412 argTypes := []reflect.Type{reflect.TypeOf("")} 413 argTypes = append(argTypes, callb.argTypes...) 414 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 415 requests[i].args = args[1:] // first one is service.method name which isn't an actual argument 416 } else { 417 requests[i].err = &invalidParamsError{err.Error()} 418 } 419 } 420 } else { 421 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 422 } 423 continue 424 } 425 426 if callb, ok := svc.callbacks[r.method]; ok { // lookup RPC method 427 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 428 if r.params != nil && len(callb.argTypes) > 0 { 429 if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil { 430 requests[i].args = args 431 } else { 432 requests[i].err = &invalidParamsError{err.Error()} 433 } 434 } 435 continue 436 } 437 438 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 439 } 440 441 return requests, batch, nil 442 }