server.go 5.66 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

17
package rpc
18 19

import (
20
	"context"
21
	"io"
22
	"sync/atomic"
23

24
	mapset "github.com/deckarep/golang-set"
25
	"github.com/ethereum/go-ethereum/log"
26 27
)

28
const MetadataApi = "rpc"
29
const EngineApi = "engine"
30

31 32 33
// CodecOption specifies which type of messages a codec supports.
//
// Deprecated: this option is no longer honored by Server.
34 35 36 37 38 39
type CodecOption int

const (
	// OptionMethodInvocation is an indication that the codec supports RPC method calls
	OptionMethodInvocation CodecOption = 1 << iota

40
	// OptionSubscriptions is an indication that the codec supports RPC notifications
41 42 43
	OptionSubscriptions = 1 << iota // support pub sub
)

44 45 46 47 48 49 50
// Server is an RPC server.
type Server struct {
	services serviceRegistry
	idgen    func() ID
	run      int32
	codecs   mapset.Set
}
51

52 53 54 55 56
// NewServer creates a new server instance with no registered handlers.
func NewServer() *Server {
	server := &Server{idgen: randomIDGenerator(), codecs: mapset.NewSet(), run: 1}
	// Register the default service providing meta information about the RPC service such
	// as the services and methods it offers.
57
	rpcService := &RPCService{server}
58
	server.RegisterName(MetadataApi, rpcService)
59 60 61
	return server
}

62 63 64 65 66 67
// RegisterName creates a service for the given receiver type under the given name. When no
// methods on the given receiver match the criteria to be either a RPC method or a
// subscription an error is returned. Otherwise a new service is created and added to the
// service collection this server provides to clients.
func (s *Server) RegisterName(name string, receiver interface{}) error {
	return s.services.registerName(name, receiver)
68 69
}

70 71 72 73 74 75
// ServeCodec reads incoming requests from codec, calls the appropriate callback and writes
// the response back using the given codec. It will block until the codec is closed or the
// server is stopped. In either case the codec is closed.
//
// Note that codec options are no longer supported.
func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) {
76
	defer codec.close()
77

78 79 80
	// Don't serve if server is stopped.
	if atomic.LoadInt32(&s.run) == 0 {
		return
81 82
	}

83 84 85
	// Add the codec to the set so it can be closed by Stop.
	s.codecs.Add(codec)
	defer s.codecs.Remove(codec)
86

87
	c := initClient(codec, s.idgen, &s.services)
88
	<-codec.closed()
89
	c.Close()
90 91
}

92 93 94 95 96 97 98
// serveSingleRequest reads and processes a single RPC request from the given codec. This
// is used to serve HTTP connections. Subscriptions and reverse calls are not allowed in
// this mode.
func (s *Server) serveSingleRequest(ctx context.Context, codec ServerCodec) {
	// Don't serve if server is stopped.
	if atomic.LoadInt32(&s.run) == 0 {
		return
99 100
	}

101 102 103
	h := newHandler(ctx, codec, s.idgen, &s.services)
	h.allowSubscribe = false
	defer h.close(io.EOF, nil)
104

105
	reqs, batch, err := codec.readBatch()
106 107
	if err != nil {
		if err != io.EOF {
108
			codec.writeJSON(ctx, errorMessage(&invalidMessageError{"parse error"}))
109
		}
110 111 112 113 114 115
		return
	}
	if batch {
		h.handleBatch(reqs)
	} else {
		h.handleMsg(reqs[0])
116
	}
117 118
}

119 120 121
// Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending
// requests to finish, then closes all codecs which will cancel pending requests and
// subscriptions.
122 123
func (s *Server) Stop() {
	if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
124
		log.Debug("RPC server shutting down")
125
		s.codecs.Each(func(c interface{}) bool {
126
			c.(ServerCodec).close()
127
			return true
128 129 130 131
		})
	}
}

132 133 134 135
// RPCService gives meta information about the server.
// e.g. gives information about the loaded modules.
type RPCService struct {
	server *Server
136 137
}

138 139 140 141
// Modules returns the list of RPC services with their version number
func (s *RPCService) Modules() map[string]string {
	s.server.services.mu.Lock()
	defer s.server.services.mu.Unlock()
142

143 144 145
	modules := make(map[string]string)
	for name := range s.server.services.services {
		modules[name] = "1.0"
146
	}
147
	return modules
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

// PeerInfo contains information about the remote end of the network connection.
//
// This is available within RPC method handlers through the context. Call
// PeerInfoFromContext to get information about the client connection related to
// the current method call.
type PeerInfo struct {
	// Transport is name of the protocol used by the client.
	// This can be "http", "ws" or "ipc".
	Transport string

	// Address of client. This will usually contain the IP address and port.
	RemoteAddr string

	// Addditional information for HTTP and WebSocket connections.
	HTTP struct {
		// Protocol version, i.e. "HTTP/1.1". This is not set for WebSocket.
		Version string
		// Header values sent by the client.
		UserAgent string
		Origin    string
		Host      string
	}
}

type peerInfoContextKey struct{}

// PeerInfoFromContext returns information about the client's network connection.
// Use this with the context passed to RPC method handler functions.
//
// The zero value is returned if no connection info is present in ctx.
func PeerInfoFromContext(ctx context.Context) PeerInfo {
	info, _ := ctx.Value(peerInfoContextKey{}).(PeerInfo)
	return info
}