blob: 3516796cecbc2f2579aaf385e2aae6fdb45cf840 [file] [log] [blame]
Jiri Simsad7616c92015-03-24 23:44:30 -07001// Copyright 2015 The Vanadium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07005package rpc
Jiri Simsa5293dcb2014-05-10 09:56:38 -07006
7import (
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08008 "errors"
Jiri Simsa5293dcb2014-05-10 09:56:38 -07009 "fmt"
10 "io"
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -070011 "net"
Asim Shankarb54d7642014-06-05 13:08:04 -070012 "reflect"
Jiri Simsa5293dcb2014-05-10 09:56:38 -070013 "strings"
14 "sync"
15 "time"
16
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -070017 "v.io/x/lib/netstate"
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -070018 "v.io/x/lib/pubsub"
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -070019 "v.io/x/lib/vlog"
20
Jiri Simsa6ac95222015-02-23 16:11:49 -080021 "v.io/v23/context"
Todd Wang5082a552015-04-02 10:56:11 -070022 "v.io/v23/namespace"
Jiri Simsa6ac95222015-02-23 16:11:49 -080023 "v.io/v23/naming"
24 "v.io/v23/options"
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070025 "v.io/v23/rpc"
Jiri Simsa6ac95222015-02-23 16:11:49 -080026 "v.io/v23/security"
Todd Wang387d8a42015-03-30 17:09:05 -070027 "v.io/v23/security/access"
Jiri Simsa6ac95222015-02-23 16:11:49 -080028 "v.io/v23/vdl"
29 "v.io/v23/verror"
Jiri Simsa6ac95222015-02-23 16:11:49 -080030 "v.io/v23/vom"
31 "v.io/v23/vtrace"
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -070032
Jiri Simsaffceefa2015-02-28 11:03:34 -080033 "v.io/x/ref/lib/stats"
Matt Rosencrantz86ba1a12015-03-09 13:19:02 -070034 "v.io/x/ref/profiles/internal/lib/publisher"
Matt Rosencrantzdbc1be22015-02-28 15:15:49 -080035 inaming "v.io/x/ref/profiles/internal/naming"
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -070036 "v.io/x/ref/profiles/internal/rpc/stream"
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070037 "v.io/x/ref/profiles/internal/rpc/stream/vc"
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070038)
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -080039
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070040var (
41 // These errors are intended to be used as arguments to higher
42 // level errors and hence {1}{2} is omitted from their format
43 // strings to avoid repeating these n-times in the final error
44 // message visible to the user.
45 errResponseEncoding = reg(".errResponseEncoding", "failed to encode RPC response {3} <-> {4}{:5}")
46 errResultEncoding = reg(".errResultEncoding", "failed to encode result #{3} [{4}]{:5}")
47 errFailedToResolveToEndpoint = reg(".errFailedToResolveToEndpoint", "failed to resolve {3} to an endpoint")
48 errFailedToResolveProxy = reg(".errFailedToResolveProxy", "failed to resolve proxy {3}{:4}")
49 errFailedToListenForProxy = reg(".errFailedToListenForProxy", "failed to listen on {3}{:4}")
50 errInternalTypeConversion = reg(".errInternalTypeConversion", "failed to convert {3} to v.io/x/ref/profiles/internal/naming.Endpoint")
51 errFailedToParseIP = reg(".errFailedToParseIP", "failed to parse {3} as an IP host")
Jiri Simsa5293dcb2014-05-10 09:56:38 -070052)
53
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080054// state for each requested listen address
55type listenState struct {
56 protocol, address string
57 ln stream.Listener
58 lep naming.Endpoint
59 lnerr, eperr error
60 roaming bool
61 // We keep track of all of the endpoints, the port and a copy of
62 // the original listen endpoint for use with roaming network changes.
63 ieps []*inaming.Endpoint // list of currently active eps
64 port string // port to use for creating new eps
65 protoIEP inaming.Endpoint // endpoint to use as template for new eps (includes rid, versions etc)
66}
67
68// state for each requested proxy
69type proxyState struct {
70 endpoint naming.Endpoint
Mike Burrowsdc6b3602015-02-05 15:52:12 -080071 err error
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080072}
73
74type dhcpState struct {
75 name string
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -070076 publisher *pubsub.Publisher
77 stream *pubsub.Stream
78 ch chan pubsub.Setting // channel to receive dhcp settings over
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080079 err error // error status.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070080 watchers map[chan<- rpc.NetworkChange]struct{}
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080081}
82
Jiri Simsa5293dcb2014-05-10 09:56:38 -070083type server struct {
84 sync.Mutex
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080085 // context used by the server to make internal RPCs, error messages etc.
86 ctx *context.T
Matt Rosencrantz1094d062015-01-30 06:43:12 -080087 cancel context.CancelFunc // function to cancel the above context.
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080088 state serverState // track state of the server.
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -080089 streamMgr stream.Manager // stream manager to listen for new flows.
90 publisher publisher.Publisher // publisher to publish mounttable mounts.
91 listenerOpts []stream.ListenerOpt // listener opts for Listen.
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080092 dhcpState *dhcpState // dhcpState, nil if not using dhcp
Suharsh Sivakumar59c423c2015-03-11 14:06:03 -070093 principal security.Principal
Suharsh Sivakumare5e5dcc2015-03-18 14:29:31 -070094 blessings security.Blessings
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -080095
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080096 // maps that contain state on listeners.
97 listenState map[*listenState]struct{}
98 listeners map[stream.Listener]struct{}
99
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800100 // state of proxies keyed by the name of the proxy
101 proxies map[string]proxyState
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800102
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800103 // all endpoints generated and returned by this server
104 endpoints []naming.Endpoint
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800105
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700106 disp rpc.Dispatcher // dispatcher to serve RPCs
107 dispReserved rpc.Dispatcher // dispatcher for reserved methods
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800108 active sync.WaitGroup // active goroutines we've spawned.
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800109 stoppedChan chan struct{} // closed when the server has been stopped.
110 preferredProtocols []string // protocols to use when resolving proxy name to endpoint.
Jungho Ahn25545d32015-01-26 15:14:14 -0800111 // We cache the IP networks on the device since it is not that cheap to read
112 // network interfaces through os syscall.
113 // TODO(jhahn): Add monitoring the network interface changes.
114 ipNets []*net.IPNet
Todd Wang5082a552015-04-02 10:56:11 -0700115 ns namespace.T
Jungho Ahn25545d32015-01-26 15:14:14 -0800116 servesMountTable bool
Robin Thellend89e95232015-03-24 13:48:48 -0700117 isLeaf bool
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800118
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700119 // TODO(cnicolaou): add roaming stats to rpcStats
120 stats *rpcStats // stats for this server.
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700121}
122
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800123type serverState int
124
125const (
126 initialized serverState = iota
127 listening
128 serving
129 publishing
130 stopping
131 stopped
132)
133
134// Simple state machine for the server implementation.
135type next map[serverState]bool
136type transitions map[serverState]next
137
138var (
139 states = transitions{
140 initialized: next{listening: true, stopping: true},
141 listening: next{listening: true, serving: true, stopping: true},
142 serving: next{publishing: true, stopping: true},
143 publishing: next{publishing: true, stopping: true},
144 stopping: next{},
145 stopped: next{},
146 }
147
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700148 externalStates = map[serverState]rpc.ServerState{
149 initialized: rpc.ServerInit,
150 listening: rpc.ServerActive,
151 serving: rpc.ServerActive,
152 publishing: rpc.ServerActive,
153 stopping: rpc.ServerStopping,
154 stopped: rpc.ServerStopped,
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800155 }
156)
157
158func (s *server) allowed(next serverState, method string) error {
159 if states[s.state][next] {
160 s.state = next
161 return nil
162 }
Jiri Simsa074bf362015-02-17 09:29:45 -0800163 return verror.New(verror.ErrBadState, s.ctx, fmt.Sprintf("%s called out of order or more than once", method))
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800164}
165
166func (s *server) isStopState() bool {
167 return s.state == stopping || s.state == stopped
168}
169
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700170var _ rpc.Server = (*server)(nil)
Benjamin Prosnitzfdfbf7b2014-10-08 09:47:21 -0700171
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -0700172func InternalNewServer(
173 ctx *context.T,
174 streamMgr stream.Manager,
175 ns namespace.T,
176 client rpc.Client,
177 principal security.Principal,
178 opts ...rpc.ServerOpt) (rpc.Server, error) {
Matt Rosencrantz1094d062015-01-30 06:43:12 -0800179 ctx, cancel := context.WithRootCancel(ctx)
Todd Wangad492042015-04-17 15:58:40 -0700180 ctx, _ = vtrace.WithNewSpan(ctx, "NewServer")
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700181 statsPrefix := naming.Join("rpc", "server", "routing-id", streamMgr.RoutingID().String())
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700182 s := &server{
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800183 ctx: ctx,
184 cancel: cancel,
185 streamMgr: streamMgr,
Suharsh Sivakumar59c423c2015-03-11 14:06:03 -0700186 principal: principal,
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800187 publisher: publisher.New(ctx, ns, publishPeriod),
188 listenState: make(map[*listenState]struct{}),
189 listeners: make(map[stream.Listener]struct{}),
190 proxies: make(map[string]proxyState),
191 stoppedChan: make(chan struct{}),
192 ipNets: ipNetworks(),
193 ns: ns,
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700194 stats: newRPCStats(statsPrefix),
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700195 }
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700196 var (
197 dischargeExpiryBuffer = vc.DefaultServerDischargeExpiryBuffer
198 securityLevel options.SecurityLevel
199 )
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700200 for _, opt := range opts {
Bogdan Caprita187269b2014-05-13 19:59:46 -0700201 switch opt := opt.(type) {
202 case stream.ListenerOpt:
203 // Collect all ServerOpts that are also ListenerOpts.
204 s.listenerOpts = append(s.listenerOpts, opt)
Bogdan Capritae7376312014-11-10 13:13:17 -0800205 switch opt := opt.(type) {
Suharsh Sivakumar08918582015-03-03 15:16:36 -0800206 case vc.DischargeExpiryBuffer:
207 dischargeExpiryBuffer = time.Duration(opt)
Bogdan Capritae7376312014-11-10 13:13:17 -0800208 }
Suharsh Sivakumare5e5dcc2015-03-18 14:29:31 -0700209 case options.ServerBlessings:
210 s.blessings = opt.Blessings
Asim Shankarcc044212014-10-15 23:25:26 -0700211 case options.ServesMountTable:
Cosmos Nicolaoue6e87f12014-06-03 14:29:10 -0700212 s.servesMountTable = bool(opt)
Suharsh Sivakumard7a65192015-01-27 22:57:15 -0800213 case ReservedNameDispatcher:
Todd Wang5739dda2014-11-16 22:44:02 -0800214 s.dispReserved = opt.Dispatcher
Nicolas LaCasse55a10f32014-11-26 13:25:53 -0800215 case PreferredServerResolveProtocols:
216 s.preferredProtocols = []string(opt)
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700217 case options.SecurityLevel:
218 securityLevel = opt
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700219 }
220 }
Suharsh Sivakumare5e5dcc2015-03-18 14:29:31 -0700221 if s.blessings.IsZero() && principal != nil {
222 s.blessings = principal.BlessingStore().Default()
223 }
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700224 if securityLevel == options.SecurityNone {
225 s.principal = nil
226 s.blessings = security.Blessings{}
227 s.dispReserved = nil
228 }
Suharsh Sivakumar08918582015-03-03 15:16:36 -0800229 // Make dischargeExpiryBuffer shorter than the VC discharge buffer to ensure we have fetched
230 // the discharges by the time the VC asks for them.`
231 dc := InternalNewDischargeClient(ctx, client, dischargeExpiryBuffer-(5*time.Second))
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -0800232 s.listenerOpts = append(s.listenerOpts, dc)
Benjamin Prosnitz9284a002015-02-23 14:57:25 -0800233 s.listenerOpts = append(s.listenerOpts, vc.DialContext{ctx})
Bogdan Capritae7376312014-11-10 13:13:17 -0800234 blessingsStatsName := naming.Join(statsPrefix, "security", "blessings")
Asim Shankar2bf7b1e2015-02-27 00:45:12 -0800235 // TODO(caprita): revist printing the blessings with %s, and
236 // instead expose them as a list.
Suharsh Sivakumare5e5dcc2015-03-18 14:29:31 -0700237 stats.NewString(blessingsStatsName).Set(fmt.Sprintf("%s", s.blessings))
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700238 if principal != nil {
Bogdan Capritae7376312014-11-10 13:13:17 -0800239 stats.NewStringFunc(blessingsStatsName, func() string {
240 return fmt.Sprintf("%s (default)", principal.BlessingStore().Default())
241 })
242 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700243 return s, nil
244}
245
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700246func (s *server) Status() rpc.ServerStatus {
247 status := rpc.ServerStatus{}
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -0700248 defer vlog.LogCall()()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700249 s.Lock()
250 defer s.Unlock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800251 status.State = externalStates[s.state]
252 status.ServesMountTable = s.servesMountTable
253 status.Mounts = s.publisher.Status()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800254 status.Endpoints = []naming.Endpoint{}
255 for ls, _ := range s.listenState {
256 if ls.eperr != nil {
257 status.Errors = append(status.Errors, ls.eperr)
258 }
259 if ls.lnerr != nil {
260 status.Errors = append(status.Errors, ls.lnerr)
261 }
262 for _, iep := range ls.ieps {
263 status.Endpoints = append(status.Endpoints, iep)
264 }
265 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700266 status.Proxies = make([]rpc.ProxyStatus, 0, len(s.proxies))
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800267 for k, v := range s.proxies {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700268 status.Proxies = append(status.Proxies, rpc.ProxyStatus{k, v.endpoint, v.err})
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700269 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800270 return status
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700271}
272
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700273func (s *server) WatchNetwork(ch chan<- rpc.NetworkChange) {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800274 defer vlog.LogCall()()
275 s.Lock()
276 defer s.Unlock()
277 if s.dhcpState != nil {
278 s.dhcpState.watchers[ch] = struct{}{}
279 }
280}
281
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700282func (s *server) UnwatchNetwork(ch chan<- rpc.NetworkChange) {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800283 defer vlog.LogCall()()
284 s.Lock()
285 defer s.Unlock()
286 if s.dhcpState != nil {
287 delete(s.dhcpState.watchers, ch)
288 }
289}
290
Robin Thellend92b65a42014-12-17 14:30:16 -0800291// resolveToEndpoint resolves an object name or address to an endpoint.
292func (s *server) resolveToEndpoint(address string) (string, error) {
Asim Shankaraae31802015-01-22 11:59:42 -0800293 var resolved *naming.MountEntry
294 var err error
Asim Shankardee311d2014-08-01 17:41:31 -0700295 if s.ns != nil {
Asim Shankaraae31802015-01-22 11:59:42 -0800296 if resolved, err = s.ns.Resolve(s.ctx, address); err != nil {
Asim Shankardee311d2014-08-01 17:41:31 -0700297 return "", err
298 }
299 } else {
Asim Shankaraae31802015-01-22 11:59:42 -0800300 // Fake a namespace resolution
301 resolved = &naming.MountEntry{Servers: []naming.MountedServer{
302 {Server: address},
303 }}
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700304 }
Nicolas LaCasse55a10f32014-11-26 13:25:53 -0800305 // An empty set of protocols means all protocols...
Jungho Ahn25545d32015-01-26 15:14:14 -0800306 if resolved.Servers, err = filterAndOrderServers(resolved.Servers, s.preferredProtocols, s.ipNets); err != nil {
Nicolas LaCasse55a10f32014-11-26 13:25:53 -0800307 return "", err
308 }
Asim Shankaraae31802015-01-22 11:59:42 -0800309 for _, n := range resolved.Names() {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700310 address, suffix := naming.SplitAddressName(n)
David Why Use Two When One Will Do Presottoadf0ca12014-11-13 10:49:01 -0800311 if suffix != "" {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700312 continue
313 }
Asim Shankaraae31802015-01-22 11:59:42 -0800314 if ep, err := inaming.NewEndpoint(address); err == nil {
315 return ep.String(), nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700316 }
317 }
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700318 return "", verror.New(errFailedToResolveToEndpoint, s.ctx, address)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700319}
320
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800321// createEndpoints creates appropriate inaming.Endpoint instances for
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800322// all of the externally accessible network addresses that can be used
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800323// to reach this server.
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700324func (s *server) createEndpoints(lep naming.Endpoint, chooser netstate.AddressChooser) ([]*inaming.Endpoint, string, bool, error) {
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800325 iep, ok := lep.(*inaming.Endpoint)
326 if !ok {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700327 return nil, "", false, verror.New(errInternalTypeConversion, nil, fmt.Sprintf("%T", lep))
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800328 }
329 if !strings.HasPrefix(iep.Protocol, "tcp") &&
330 !strings.HasPrefix(iep.Protocol, "ws") {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800331 // If not tcp, ws, or wsh, just return the endpoint we were given.
332 return []*inaming.Endpoint{iep}, "", false, nil
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800333 }
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800334 host, port, err := net.SplitHostPort(iep.Address)
335 if err != nil {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800336 return nil, "", false, err
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800337 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700338 addrs, unspecified, err := netstate.PossibleAddresses(iep.Protocol, host, chooser)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800339 if err != nil {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800340 return nil, port, false, err
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800341 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700342
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800343 ieps := make([]*inaming.Endpoint, 0, len(addrs))
344 for _, addr := range addrs {
345 n, err := inaming.NewEndpoint(lep.String())
346 if err != nil {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800347 return nil, port, false, err
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800348 }
349 n.IsMountTable = s.servesMountTable
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700350 n.Address = net.JoinHostPort(addr.String(), port)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800351 ieps = append(ieps, n)
352 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800353 return ieps, port, unspecified, nil
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800354}
355
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700356func (s *server) Listen(listenSpec rpc.ListenSpec) ([]naming.Endpoint, error) {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -0700357 defer vlog.LogCall()()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800358 useProxy := len(listenSpec.Proxy) > 0
359 if !useProxy && len(listenSpec.Addrs) == 0 {
Jiri Simsa074bf362015-02-17 09:29:45 -0800360 return nil, verror.New(verror.ErrBadArg, s.ctx, "ListenSpec contains no proxy or addresses to listen on")
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800361 }
362
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700363 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800364 defer s.Unlock()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800365
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800366 if err := s.allowed(listening, "Listen"); err != nil {
367 return nil, err
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700368 }
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700369
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800370 // Start the proxy as early as possible, ignore duplicate requests
371 // for the same proxy.
372 if _, inuse := s.proxies[listenSpec.Proxy]; useProxy && !inuse {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800373 // We have a goroutine for listening on proxy connections.
Cosmos Nicolaoueef1fab2014-11-11 18:23:41 -0800374 s.active.Add(1)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800375 go func() {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800376 s.proxyListenLoop(listenSpec.Proxy)
377 s.active.Done()
378 }()
379 }
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700380
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800381 roaming := false
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800382 lnState := make([]*listenState, 0, len(listenSpec.Addrs))
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800383 for _, addr := range listenSpec.Addrs {
384 if len(addr.Address) > 0 {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800385 // Listen if we have a local address to listen on.
386 ls := &listenState{
387 protocol: addr.Protocol,
388 address: addr.Address,
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800389 }
Suharsh Sivakumare5e5dcc2015-03-18 14:29:31 -0700390 ls.ln, ls.lep, ls.lnerr = s.streamMgr.Listen(addr.Protocol, addr.Address, s.principal, s.blessings, s.listenerOpts...)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800391 lnState = append(lnState, ls)
392 if ls.lnerr != nil {
Asim Shankar7171a252015-03-07 14:41:40 -0800393 vlog.VI(2).Infof("Listen(%q, %q, ...) failed: %v", addr.Protocol, addr.Address, ls.lnerr)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800394 continue
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800395 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800396 ls.ieps, ls.port, ls.roaming, ls.eperr = s.createEndpoints(ls.lep, listenSpec.AddressChooser)
397 if ls.roaming && ls.eperr == nil {
398 ls.protoIEP = *ls.lep.(*inaming.Endpoint)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800399 roaming = true
400 }
401 }
402 }
403
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800404 found := false
405 for _, ls := range lnState {
406 if ls.ln != nil {
407 found = true
408 break
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800409 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800410 }
411 if !found && !useProxy {
Jiri Simsa074bf362015-02-17 09:29:45 -0800412 return nil, verror.New(verror.ErrBadArg, s.ctx, "failed to create any listeners")
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800413 }
414
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800415 if roaming && s.dhcpState == nil && listenSpec.StreamPublisher != nil {
416 // Create a dhcp listener if we haven't already done so.
417 dhcp := &dhcpState{
418 name: listenSpec.StreamName,
419 publisher: listenSpec.StreamPublisher,
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700420 watchers: make(map[chan<- rpc.NetworkChange]struct{}),
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800421 }
422 s.dhcpState = dhcp
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -0700423 dhcp.ch = make(chan pubsub.Setting, 10)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800424 dhcp.stream, dhcp.err = dhcp.publisher.ForkStream(dhcp.name, dhcp.ch)
425 if dhcp.err == nil {
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800426 // We have a goroutine to listen for dhcp changes.
427 s.active.Add(1)
428 go func() {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800429 s.dhcpLoop(dhcp.ch)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800430 s.active.Done()
431 }()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800432 }
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800433 }
434
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800435 eps := make([]naming.Endpoint, 0, 10)
436 for _, ls := range lnState {
437 s.listenState[ls] = struct{}{}
438 if ls.ln != nil {
439 // We have a goroutine per listener to accept new flows.
440 // Each flow is served from its own goroutine.
441 s.active.Add(1)
442 go func(ln stream.Listener, ep naming.Endpoint) {
443 s.listenLoop(ln, ep)
444 s.active.Done()
445 }(ls.ln, ls.lep)
446 }
447
448 for _, iep := range ls.ieps {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800449 eps = append(eps, iep)
450 }
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800451 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800452
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800453 return eps, nil
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700454}
455
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800456func (s *server) reconnectAndPublishProxy(proxy string) (*inaming.Endpoint, stream.Listener, error) {
Robin Thellend92b65a42014-12-17 14:30:16 -0800457 resolved, err := s.resolveToEndpoint(proxy)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800458 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700459 return nil, nil, verror.New(errFailedToResolveProxy, s.ctx, proxy, err)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800460 }
Suharsh Sivakumare5e5dcc2015-03-18 14:29:31 -0700461 ln, ep, err := s.streamMgr.Listen(inaming.Network, resolved, s.principal, s.blessings, s.listenerOpts...)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800462 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700463 return nil, nil, verror.New(errFailedToListenForProxy, s.ctx, resolved, err)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800464 }
465 iep, ok := ep.(*inaming.Endpoint)
466 if !ok {
467 ln.Close()
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700468 return nil, nil, verror.New(errInternalTypeConversion, s.ctx, fmt.Sprintf("%T", ep))
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800469 }
470 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800471 s.proxies[proxy] = proxyState{iep, nil}
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800472 s.Unlock()
Robin Thellende22920e2015-02-05 17:15:50 -0800473 iep.IsMountTable = s.servesMountTable
Robin Thellendb457df92015-03-30 09:42:15 -0700474 iep.IsLeaf = s.isLeaf
Robin Thellend89e95232015-03-24 13:48:48 -0700475 s.publisher.AddServer(iep.String())
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800476 return iep, ln, nil
477}
478
479func (s *server) proxyListenLoop(proxy string) {
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700480 const (
481 min = 5 * time.Millisecond
482 max = 5 * time.Minute
483 )
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800484
485 iep, ln, err := s.reconnectAndPublishProxy(proxy)
486 if err != nil {
Matt Rosencrantz7e16af42015-04-17 11:48:56 -0700487 vlog.Errorf("Failed to connect to proxy: %s", err)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800488 }
489 // the initial connection maybe have failed, but we enter the retry
490 // loop anyway so that we will continue to try and connect to the
491 // proxy.
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800492 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800493 if s.isStopState() {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800494 s.Unlock()
495 return
496 }
497 s.Unlock()
498
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700499 for {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800500 if ln != nil && iep != nil {
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800501 err := s.listenLoop(ln, iep)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800502 // The listener is done, so:
503 // (1) Unpublish its name
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800504 s.publisher.RemoveServer(iep.String())
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800505 s.Lock()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800506 if err != nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800507 s.proxies[proxy] = proxyState{iep, verror.New(verror.ErrNoServers, s.ctx, err)}
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800508 } else {
Asim Shankar7171a252015-03-07 14:41:40 -0800509 // err will be nil if we're stopping.
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800510 s.proxies[proxy] = proxyState{iep, nil}
511 s.Unlock()
512 return
513 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800514 s.Unlock()
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800515 }
516
517 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800518 if s.isStopState() {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800519 s.Unlock()
520 return
521 }
522 s.Unlock()
523
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700524 // (2) Reconnect to the proxy unless the server has been stopped
525 backoff := min
526 ln = nil
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800527 for {
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700528 select {
529 case <-time.After(backoff):
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700530 if backoff = backoff * 2; backoff > max {
531 backoff = max
532 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700533 case <-s.stoppedChan:
534 return
535 }
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800536 // (3) reconnect, publish new address
537 if iep, ln, err = s.reconnectAndPublishProxy(proxy); err != nil {
Matt Rosencrantz7e16af42015-04-17 11:48:56 -0700538 vlog.Errorf("Failed to reconnect to proxy %q: %s", proxy, err)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800539 } else {
540 vlog.VI(1).Infof("Reconnected to proxy %q, %s", proxy, iep)
541 break
542 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700543 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700544 }
545}
546
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800547// addListener adds the supplied listener taking care to
548// check to see if we're already stopping. It returns true
549// if the listener was added.
550func (s *server) addListener(ln stream.Listener) bool {
551 s.Lock()
552 defer s.Unlock()
553 if s.isStopState() {
554 return false
555 }
556 s.listeners[ln] = struct{}{}
557 return true
558}
559
560// rmListener removes the supplied listener taking care to
561// check if we're already stopping. It returns true if the
562// listener was removed.
563func (s *server) rmListener(ln stream.Listener) bool {
564 s.Lock()
565 defer s.Unlock()
566 if s.isStopState() {
567 return false
568 }
569 delete(s.listeners, ln)
570 return true
571}
572
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800573func (s *server) listenLoop(ln stream.Listener, ep naming.Endpoint) error {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700574 defer vlog.VI(1).Infof("rpc: Stopped listening on %s", ep)
Cosmos Nicolaoueef1fab2014-11-11 18:23:41 -0800575 var calls sync.WaitGroup
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800576
577 if !s.addListener(ln) {
578 // We're stopping.
579 return nil
580 }
581
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700582 defer func() {
Cosmos Nicolaoueef1fab2014-11-11 18:23:41 -0800583 calls.Wait()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800584 s.rmListener(ln)
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700585 }()
586 for {
587 flow, err := ln.Accept()
588 if err != nil {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700589 vlog.VI(10).Infof("rpc: Accept on %v failed: %v", ep, err)
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800590 return err
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700591 }
Cosmos Nicolaoueef1fab2014-11-11 18:23:41 -0800592 calls.Add(1)
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700593 go func(flow stream.Flow) {
Todd Wang34ed4c62014-11-26 15:15:52 -0800594 defer calls.Done()
595 fs, err := newFlowServer(flow, s)
596 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700597 vlog.VI(1).Infof("newFlowServer on %v failed: %v", ep, err)
Todd Wang34ed4c62014-11-26 15:15:52 -0800598 return
599 }
600 if err := fs.serve(); err != nil {
Todd Wang5739dda2014-11-16 22:44:02 -0800601 // TODO(caprita): Logging errors here is too spammy. For example, "not
602 // authorized" errors shouldn't be logged as server errors.
Cosmos Nicolaou93dd88b2015-02-19 15:10:53 -0800603 // TODO(cnicolaou): revisit this when verror2 transition is
604 // done.
Cosmos Nicolaou1534b3f2014-12-10 15:30:00 -0800605 if err != io.EOF {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700606 vlog.VI(2).Infof("Flow.serve on %v failed: %v", ep, err)
Cosmos Nicolaou1534b3f2014-12-10 15:30:00 -0800607 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700608 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700609 }(flow)
610 }
611}
612
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -0700613func (s *server) dhcpLoop(ch chan pubsub.Setting) {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700614 defer vlog.VI(1).Infof("rpc: Stopped listen for dhcp changes")
615 vlog.VI(2).Infof("rpc: dhcp loop")
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800616 for setting := range ch {
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700617 if setting == nil {
618 return
619 }
620 switch v := setting.Value().(type) {
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700621 case []net.Addr:
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700622 s.Lock()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800623 if s.isStopState() {
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700624 s.Unlock()
625 return
626 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800627 var err error
628 var changed []naming.Endpoint
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700629 switch setting.Name() {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700630 case rpc.NewAddrsSetting:
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800631 changed = s.addAddresses(v)
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700632 case rpc.RmAddrsSetting:
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800633 changed, err = s.removeAddresses(v)
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700634 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700635 change := rpc.NetworkChange{
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800636 Time: time.Now(),
637 State: externalStates[s.state],
638 Setting: setting,
639 Changed: changed,
640 Error: err,
641 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700642 vlog.VI(2).Infof("rpc: dhcp: change %v", change)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800643 for ch, _ := range s.dhcpState.watchers {
644 select {
645 case ch <- change:
646 default:
647 }
648 }
649 s.Unlock()
650 default:
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700651 vlog.Errorf("rpc: dhcpLoop: unhandled setting type %T", v)
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700652 }
653 }
654}
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800655
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700656func getHost(address net.Addr) string {
657 host, _, err := net.SplitHostPort(address.String())
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800658 if err == nil {
659 return host
660 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700661 return address.String()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800662
663}
664
665// Remove all endpoints that have the same host address as the supplied
666// address parameter.
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700667func (s *server) removeAddresses(addrs []net.Addr) ([]naming.Endpoint, error) {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800668 var removed []naming.Endpoint
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700669 for _, address := range addrs {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800670 host := getHost(address)
671 for ls, _ := range s.listenState {
672 if ls != nil && ls.roaming && len(ls.ieps) > 0 {
673 remaining := make([]*inaming.Endpoint, 0, len(ls.ieps))
674 for _, iep := range ls.ieps {
675 lnHost, _, err := net.SplitHostPort(iep.Address)
676 if err != nil {
677 lnHost = iep.Address
678 }
679 if lnHost == host {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700680 vlog.VI(2).Infof("rpc: dhcp removing: %s", iep)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800681 removed = append(removed, iep)
682 s.publisher.RemoveServer(iep.String())
683 continue
684 }
685 remaining = append(remaining, iep)
686 }
687 ls.ieps = remaining
688 }
689 }
690 }
691 return removed, nil
692}
693
694// Add new endpoints for the new address. There is no way to know with
695// 100% confidence which new endpoints to publish without shutting down
696// all network connections and reinitializing everything from scratch.
697// Instead, we find all roaming listeners with at least one endpoint
698// and create a new endpoint with the same port as the existing ones
699// but with the new address supplied to us to by the dhcp code. As
700// an additional safeguard we reject the new address if it is not
701// externally accessible.
702// This places the onus on the dhcp/roaming code that sends us addresses
703// to ensure that those addresses are externally reachable.
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700704func (s *server) addAddresses(addrs []net.Addr) []naming.Endpoint {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800705 var added []naming.Endpoint
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700706 vlog.Infof("HERE WITH %v -> %v", addrs, netstate.ConvertToAddresses(addrs))
707 for _, address := range netstate.ConvertToAddresses(addrs) {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800708 if !netstate.IsAccessibleIP(address) {
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700709 vlog.Infof("RETURN A %v", added)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800710 return added
711 }
712 host := getHost(address)
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700713 vlog.Infof("LISTEN ST: %v", s.listenState)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800714 for ls, _ := range s.listenState {
715 if ls != nil && ls.roaming {
716 niep := ls.protoIEP
717 niep.Address = net.JoinHostPort(host, ls.port)
Robin Thellendb457df92015-03-30 09:42:15 -0700718 niep.IsMountTable = s.servesMountTable
719 niep.IsLeaf = s.isLeaf
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800720 ls.ieps = append(ls.ieps, &niep)
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700721 vlog.VI(2).Infof("rpc: dhcp adding: %s", niep)
Robin Thellend89e95232015-03-24 13:48:48 -0700722 s.publisher.AddServer(niep.String())
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800723 added = append(added, &niep)
724 }
725 }
726 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700727 vlog.Infof("RETURN B %v", added)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800728 return added
729}
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700730
Bogdan Caprita7590a6d2015-01-08 13:43:40 -0800731type leafDispatcher struct {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700732 invoker rpc.Invoker
Bogdan Caprita7590a6d2015-01-08 13:43:40 -0800733 auth security.Authorizer
734}
735
736func (d leafDispatcher) Lookup(suffix string) (interface{}, security.Authorizer, error) {
737 if suffix != "" {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700738 return nil, nil, verror.New(verror.ErrUnknownSuffix, nil, suffix)
Bogdan Caprita7590a6d2015-01-08 13:43:40 -0800739 }
740 return d.invoker, d.auth, nil
741}
742
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800743func (s *server) Serve(name string, obj interface{}, authorizer security.Authorizer) error {
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800744 defer vlog.LogCall()()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800745 if obj == nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800746 return verror.New(verror.ErrBadArg, s.ctx, "nil object")
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800747 }
Bogdan Caprita9592d9f2015-01-08 22:15:16 -0800748 invoker, err := objectToInvoker(obj)
749 if err != nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800750 return verror.New(verror.ErrBadArg, s.ctx, fmt.Sprintf("bad object: %v", err))
Cosmos Nicolaou61c96c72014-11-03 11:57:56 -0800751 }
Robin Thellendb457df92015-03-30 09:42:15 -0700752 s.setLeaf(true)
Bogdan Caprita9592d9f2015-01-08 22:15:16 -0800753 return s.ServeDispatcher(name, &leafDispatcher{invoker, authorizer})
Cosmos Nicolaou61c96c72014-11-03 11:57:56 -0800754}
755
Robin Thellendb457df92015-03-30 09:42:15 -0700756func (s *server) setLeaf(value bool) {
757 s.Lock()
758 defer s.Unlock()
759 s.isLeaf = value
760 for ls, _ := range s.listenState {
761 for i := range ls.ieps {
762 ls.ieps[i].IsLeaf = s.isLeaf
763 }
764 }
765}
766
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700767func (s *server) ServeDispatcher(name string, disp rpc.Dispatcher) error {
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800768 defer vlog.LogCall()()
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800769 if disp == nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800770 return verror.New(verror.ErrBadArg, s.ctx, "nil dispatcher")
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700771 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800772 s.Lock()
773 defer s.Unlock()
774 if err := s.allowed(serving, "Serve or ServeDispatcher"); err != nil {
775 return err
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700776 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800777 vtrace.GetSpan(s.ctx).Annotate("Serving under name: " + name)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800778 s.disp = disp
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700779 if len(name) > 0 {
Robin Thellendb457df92015-03-30 09:42:15 -0700780 for ls, _ := range s.listenState {
781 for _, iep := range ls.ieps {
782 s.publisher.AddServer(iep.String())
783 }
784 }
Robin Thellend89e95232015-03-24 13:48:48 -0700785 s.publisher.AddName(name, s.servesMountTable, s.isLeaf)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700786 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700787 return nil
788}
789
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800790func (s *server) AddName(name string) error {
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800791 defer vlog.LogCall()()
Ali Ghassemi3c6db7b2014-11-10 17:20:26 -0800792 if len(name) == 0 {
Jiri Simsa074bf362015-02-17 09:29:45 -0800793 return verror.New(verror.ErrBadArg, s.ctx, "name is empty")
Ali Ghassemi3c6db7b2014-11-10 17:20:26 -0800794 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800795 s.Lock()
796 defer s.Unlock()
797 if err := s.allowed(publishing, "AddName"); err != nil {
798 return err
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800799 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800800 vtrace.GetSpan(s.ctx).Annotate("Serving under name: " + name)
Robin Thellend89e95232015-03-24 13:48:48 -0700801 s.publisher.AddName(name, s.servesMountTable, s.isLeaf)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800802 return nil
803}
804
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800805func (s *server) RemoveName(name string) {
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800806 defer vlog.LogCall()()
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800807 s.Lock()
808 defer s.Unlock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800809 if err := s.allowed(publishing, "RemoveName"); err != nil {
810 return
811 }
Matt Rosencrantz5f98d942015-01-08 13:48:30 -0800812 vtrace.GetSpan(s.ctx).Annotate("Removed name: " + name)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800813 s.publisher.RemoveName(name)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800814}
815
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700816func (s *server) Stop() error {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -0700817 defer vlog.LogCall()()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700818 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800819 if s.isStopState() {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700820 s.Unlock()
821 return nil
822 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800823 s.state = stopping
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700824 close(s.stoppedChan)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700825 s.Unlock()
826
Robin Thellenddf428232014-10-06 12:50:44 -0700827 // Delete the stats object.
828 s.stats.stop()
829
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700830 // Note, It's safe to Stop/WaitForStop on the publisher outside of the
831 // server lock, since publisher is safe for concurrent access.
832
833 // Stop the publisher, which triggers unmounting of published names.
834 s.publisher.Stop()
835 // Wait for the publisher to be done unmounting before we can proceed to
836 // close the listeners (to minimize the number of mounted names pointing
837 // to endpoint that are no longer serving).
838 //
839 // TODO(caprita): See if make sense to fail fast on rejecting
840 // connections once listeners are closed, and parallelize the publisher
841 // and listener shutdown.
842 s.publisher.WaitForStop()
843
844 s.Lock()
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800845
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700846 // Close all listeners. No new flows will be accepted, while in-flight
847 // flows will continue until they terminate naturally.
848 nListeners := len(s.listeners)
849 errCh := make(chan error, nListeners)
Cosmos Nicolaoubc743142014-10-06 21:27:18 -0700850
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800851 for ln, _ := range s.listeners {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700852 go func(ln stream.Listener) {
853 errCh <- ln.Close()
854 }(ln)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800855 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800856
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -0700857 drain := func(ch chan pubsub.Setting) {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800858 for {
859 select {
860 case v := <-ch:
861 if v == nil {
862 return
863 }
864 default:
865 close(ch)
866 return
867 }
868 }
869 }
870
871 if dhcp := s.dhcpState; dhcp != nil {
Cosmos Nicolaouaceb8d92015-02-05 20:44:02 -0800872 // TODO(cnicolaou,caprita): investigate not having to close and drain
873 // the channel here. It's a little awkward right now since we have to
874 // be careful to not close the channel in two places, i.e. here and
875 // and from the publisher's Shutdown method.
876 if err := dhcp.publisher.CloseFork(dhcp.name, dhcp.ch); err == nil {
877 drain(dhcp.ch)
878 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700879 }
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800880
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700881 s.Unlock()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800882
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700883 var firstErr error
884 for i := 0; i < nListeners; i++ {
885 if err := <-errCh; err != nil && firstErr == nil {
886 firstErr = err
887 }
888 }
889 // At this point, we are guaranteed that no new requests are going to be
890 // accepted.
891
892 // Wait for the publisher and active listener + flows to finish.
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800893 done := make(chan struct{}, 1)
894 go func() { s.active.Wait(); done <- struct{}{} }()
895
896 select {
897 case <-done:
898 case <-time.After(5 * time.Minute):
899 vlog.Errorf("Listener Close Error: %v", firstErr)
Bogdan Caprita2d04f0e2015-03-13 15:39:13 -0700900 vlog.Errorf("Timedout waiting for goroutines to stop: listeners: %d (currently: %d)", nListeners, len(s.listeners))
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800901 for ln, _ := range s.listeners {
902 vlog.Errorf("Listener: %p", ln)
903 }
904 for ls, _ := range s.listenState {
905 vlog.Errorf("ListenState: %v", ls)
906 }
907 <-done
908 }
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800909
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700910 s.Lock()
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800911 defer s.Unlock()
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700912 s.disp = nil
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800913 if firstErr != nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800914 return verror.New(verror.ErrInternal, s.ctx, firstErr)
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800915 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800916 s.state = stopped
Matt Rosencrantz1094d062015-01-30 06:43:12 -0800917 s.cancel()
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800918 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700919}
920
921// flowServer implements the RPC server-side protocol for a single RPC, over a
922// flow that's already connected to the client.
923type flowServer struct {
Todd Wang54feabe2015-04-15 23:38:26 -0700924 ctx *context.T // context associated with the RPC
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700925 server *server // rpc.Server that this flow server belongs to
926 disp rpc.Dispatcher // rpc.Dispatcher that will serve RPCs on this flow
Todd Wang3425a902015-01-21 18:43:59 -0800927 dec *vom.Decoder // to decode requests and args from the client
928 enc *vom.Encoder // to encode responses and results to the client
Todd Wang5739dda2014-11-16 22:44:02 -0800929 flow stream.Flow // underlying flow
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700930
Asim Shankar220a0152014-10-30 21:21:09 -0700931 // Fields filled in during the server invocation.
Suharsh Sivakumar380bf342015-02-27 15:38:27 -0800932 clientBlessings security.Blessings
933 ackBlessings bool
934 grantedBlessings security.Blessings
935 method, suffix string
936 tags []*vdl.Value
937 discharges map[string]security.Discharge
938 starttime time.Time
939 endStreamArgs bool // are the stream args at EOF?
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700940}
941
Todd Wang54feabe2015-04-15 23:38:26 -0700942var (
943 _ rpc.StreamServerCall = (*flowServer)(nil)
944 _ security.Call = (*flowServer)(nil)
945)
Benjamin Prosnitzfdfbf7b2014-10-08 09:47:21 -0700946
Todd Wang34ed4c62014-11-26 15:15:52 -0800947func newFlowServer(flow stream.Flow, server *server) (*flowServer, error) {
Cosmos Nicolaoudcba93d2014-07-30 11:09:26 -0700948 server.Lock()
949 disp := server.disp
950 server.Unlock()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -0700951
Todd Wang34ed4c62014-11-26 15:15:52 -0800952 fs := &flowServer{
Todd Wang54feabe2015-04-15 23:38:26 -0700953 ctx: server.ctx,
Todd Wang34ed4c62014-11-26 15:15:52 -0800954 server: server,
955 disp: disp,
Todd Wang5739dda2014-11-16 22:44:02 -0800956 flow: flow,
957 discharges: make(map[string]security.Discharge),
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700958 }
Todd Wangf519f8f2015-01-21 10:07:41 -0800959 var err error
Jungho Ahncfc89622015-04-24 11:27:23 -0700960 typeenc := flow.VCDataCache().Get(vc.TypeEncoderKey{})
961 if typeenc == nil {
Jungho Ahn60408fa2015-03-27 15:28:22 -0700962 if fs.enc, err = vom.NewEncoder(flow); err != nil {
963 flow.Close()
964 return nil, err
965 }
Jungho Ahncfc89622015-04-24 11:27:23 -0700966 if fs.dec, err = vom.NewDecoder(flow); err != nil {
Jungho Ahn60408fa2015-03-27 15:28:22 -0700967 flow.Close()
968 return nil, err
969 }
Jungho Ahncfc89622015-04-24 11:27:23 -0700970 } else {
Jungho Ahn60408fa2015-03-27 15:28:22 -0700971 if fs.enc, err = vom.NewEncoderWithTypeEncoder(flow, typeenc.(*vom.TypeEncoder)); err != nil {
972 flow.Close()
973 return nil, err
974 }
Jungho Ahncfc89622015-04-24 11:27:23 -0700975 typedec := flow.VCDataCache().Get(vc.TypeDecoderKey{})
976 if fs.dec, err = vom.NewDecoderWithTypeDecoder(flow, typedec.(*vom.TypeDecoder)); err != nil {
977 flow.Close()
978 return nil, err
979 }
Todd Wang34ed4c62014-11-26 15:15:52 -0800980 }
981 return fs, nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700982}
983
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -0700984// authorizeVtrace works by simulating a call to __debug/vtrace.Trace. That
985// rpc is essentially equivalent in power to the data we are attempting to
986// attach here.
987func (fs *flowServer) authorizeVtrace() error {
988 // Set up a context as though we were calling __debug/vtrace.
989 params := &security.CallParams{}
Todd Wang4264e4b2015-04-16 22:43:40 -0700990 params.Copy(fs)
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -0700991 params.Method = "Trace"
992 params.MethodTags = []*vdl.Value{vdl.ValueOf(access.Debug)}
993 params.Suffix = "__debug/vtrace"
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -0700994
995 var auth security.Authorizer
996 if fs.server.dispReserved != nil {
997 _, auth, _ = fs.server.dispReserved.Lookup(params.Suffix)
998 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700999 return authorize(fs.ctx, security.NewCall(params), auth)
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001000}
1001
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001002func (fs *flowServer) serve() error {
1003 defer fs.flow.Close()
Matt Rosencrantz86897932014-10-02 09:34:34 -07001004
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001005 results, err := fs.processRequest()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001006
Todd Wang54feabe2015-04-15 23:38:26 -07001007 vtrace.GetSpan(fs.ctx).Finish()
Matt Rosencrantz1fa32772014-10-28 11:31:46 -07001008
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001009 var traceResponse vtrace.Response
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001010 // Check if the caller is permitted to view vtrace data.
1011 if fs.authorizeVtrace() == nil {
Todd Wang54feabe2015-04-15 23:38:26 -07001012 traceResponse = vtrace.GetResponse(fs.ctx)
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001013 }
1014
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001015 // Respond to the client with the response header and positional results.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001016 response := rpc.Response{
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001017 Error: err,
1018 EndStreamResults: true,
1019 NumPosResults: uint64(len(results)),
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001020 TraceResponse: traceResponse,
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001021 AckBlessings: fs.ackBlessings,
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001022 }
1023 if err := fs.enc.Encode(response); err != nil {
Cosmos Nicolaou1534b3f2014-12-10 15:30:00 -08001024 if err == io.EOF {
1025 return err
1026 }
Todd Wang54feabe2015-04-15 23:38:26 -07001027 return verror.New(errResponseEncoding, fs.ctx, fs.LocalEndpoint().String(), fs.RemoteEndpoint().String(), err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001028 }
1029 if response.Error != nil {
1030 return response.Error
1031 }
1032 for ix, res := range results {
Todd Wangf519f8f2015-01-21 10:07:41 -08001033 if err := fs.enc.Encode(res); err != nil {
Cosmos Nicolaou1534b3f2014-12-10 15:30:00 -08001034 if err == io.EOF {
1035 return err
1036 }
Todd Wang54feabe2015-04-15 23:38:26 -07001037 return verror.New(errResultEncoding, fs.ctx, ix, fmt.Sprintf("%T=%v", res, res), err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001038 }
1039 }
1040 // TODO(ashankar): Should unread data from the flow be drained?
1041 //
1042 // Reason to do so:
Suharsh Sivakumar8646ba62015-03-18 15:22:28 -07001043 // The common stream.Flow implementation (v.io/x/ref/profiles/internal/rpc/stream/vc/reader.go)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001044 // uses iobuf.Slices backed by an iobuf.Pool. If the stream is not drained, these
1045 // slices will not be returned to the pool leading to possibly increased memory usage.
1046 //
1047 // Reason to not do so:
1048 // Draining here will conflict with any Reads on the flow in a separate goroutine
1049 // (for example, see TestStreamReadTerminatedByServer in full_test.go).
1050 //
1051 // For now, go with the reason to not do so as having unread data in the stream
1052 // should be a rare case.
1053 return nil
1054}
1055
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001056func (fs *flowServer) readRPCRequest() (*rpc.Request, error) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001057 // Set a default timeout before reading from the flow. Without this timeout,
1058 // a client that sends no request or a partial request will retain the flow
1059 // indefinitely (and lock up server resources).
Matt Rosencrantz86897932014-10-02 09:34:34 -07001060 initTimer := newTimer(defaultCallTimeout)
1061 defer initTimer.Stop()
1062 fs.flow.SetDeadline(initTimer.C)
1063
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001064 // Decode the initial request.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001065 var req rpc.Request
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001066 if err := fs.dec.Decode(&req); err != nil {
Todd Wang54feabe2015-04-15 23:38:26 -07001067 return nil, verror.New(verror.ErrBadProtocol, fs.ctx, newErrBadRequest(fs.ctx, err))
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001068 }
Matt Rosencrantz86897932014-10-02 09:34:34 -07001069 return &req, nil
1070}
1071
Todd Wang9548d852015-02-10 16:15:59 -08001072func (fs *flowServer) processRequest() ([]interface{}, error) {
Asim Shankar0cad0832014-11-04 01:27:38 -08001073 fs.starttime = time.Now()
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001074 req, err := fs.readRPCRequest()
Todd Wang9548d852015-02-10 16:15:59 -08001075 if err != nil {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001076 // We don't know what the rpc call was supposed to be, but we'll create
Matt Rosencrantz1fa32772014-10-28 11:31:46 -07001077 // a placeholder span so we can capture annotations.
Todd Wangad492042015-04-17 15:58:40 -07001078 fs.ctx, _ = vtrace.WithNewSpan(fs.ctx, fmt.Sprintf("\"%s\".UNKNOWN", fs.suffix))
Todd Wang9548d852015-02-10 16:15:59 -08001079 return nil, err
Matt Rosencrantz86897932014-10-02 09:34:34 -07001080 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001081 fs.method = req.Method
Todd Wang5739dda2014-11-16 22:44:02 -08001082 fs.suffix = strings.TrimLeft(req.Suffix, "/")
Matt Rosencrantz86897932014-10-02 09:34:34 -07001083
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001084 // TODO(mattr): Currently this allows users to trigger trace collection
1085 // on the server even if they will not be allowed to collect the
Matt Rosencrantz3197d6c2014-11-06 09:53:22 -08001086 // results later. This might be considered a DOS vector.
Todd Wang54feabe2015-04-15 23:38:26 -07001087 spanName := fmt.Sprintf("\"%s\".%s", fs.suffix, fs.method)
Todd Wangad492042015-04-17 15:58:40 -07001088 fs.ctx, _ = vtrace.WithContinuedTrace(fs.ctx, spanName, req.TraceRequest)
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001089
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001090 var cancel context.CancelFunc
Todd Wangf6a06882015-02-27 17:38:01 -08001091 if !req.Deadline.IsZero() {
Todd Wang54feabe2015-04-15 23:38:26 -07001092 fs.ctx, cancel = context.WithDeadline(fs.ctx, req.Deadline.Time)
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001093 } else {
Todd Wang54feabe2015-04-15 23:38:26 -07001094 fs.ctx, cancel = context.WithCancel(fs.ctx)
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001095 }
Todd Wang54feabe2015-04-15 23:38:26 -07001096 fs.flow.SetDeadline(fs.ctx.Done())
Todd Wang5739dda2014-11-16 22:44:02 -08001097 go fs.cancelContextOnClose(cancel)
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001098
Todd Wang5739dda2014-11-16 22:44:02 -08001099 // Initialize security: blessings, discharges, etc.
Todd Wang9548d852015-02-10 16:15:59 -08001100 if err := fs.initSecurity(req); err != nil {
1101 return nil, err
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001102 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001103 // Lookup the invoker.
Matt Rosencrantz311378b2015-03-25 15:26:12 -07001104 invoker, auth, err := fs.lookup(fs.suffix, fs.method)
Todd Wangebb3b012015-02-09 21:59:05 -08001105 if err != nil {
Todd Wang9548d852015-02-10 16:15:59 -08001106 return nil, err
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001107 }
Matt Rosencrantz311378b2015-03-25 15:26:12 -07001108
1109 // Note that we strip the reserved prefix when calling the invoker so
1110 // that __Glob will call Glob. Note that we've already assigned a
1111 // special invoker so that we never call the wrong method by mistake.
1112 strippedMethod := naming.StripReserved(fs.method)
1113
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001114 // Prepare invoker and decode args.
1115 numArgs := int(req.NumPosArgs)
Matt Rosencrantz311378b2015-03-25 15:26:12 -07001116 argptrs, tags, err := invoker.Prepare(strippedMethod, numArgs)
Asim Shankar0cad0832014-11-04 01:27:38 -08001117 fs.tags = tags
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001118 if err != nil {
Todd Wang9548d852015-02-10 16:15:59 -08001119 return nil, err
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001120 }
Todd Wang9548d852015-02-10 16:15:59 -08001121 if called, want := req.NumPosArgs, uint64(len(argptrs)); called != want {
Todd Wang54feabe2015-04-15 23:38:26 -07001122 return nil, newErrBadNumInputArgs(fs.ctx, fs.suffix, fs.method, called, want)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001123 }
1124 for ix, argptr := range argptrs {
1125 if err := fs.dec.Decode(argptr); err != nil {
Todd Wang54feabe2015-04-15 23:38:26 -07001126 return nil, newErrBadInputArg(fs.ctx, fs.suffix, fs.method, uint64(ix), err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001127 }
1128 }
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001129
Todd Wang5739dda2014-11-16 22:44:02 -08001130 // Check application's authorization policy.
Todd Wang4264e4b2015-04-16 22:43:40 -07001131 if err := authorize(fs.ctx, fs, auth); err != nil {
Todd Wang9548d852015-02-10 16:15:59 -08001132 return nil, err
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001133 }
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001134
Todd Wang5739dda2014-11-16 22:44:02 -08001135 // Invoke the method.
Todd Wang54feabe2015-04-15 23:38:26 -07001136 results, err := invoker.Invoke(fs.ctx, fs, strippedMethod, argptrs)
Robin Thellendb16d7162014-11-07 13:47:26 -08001137 fs.server.stats.record(fs.method, time.Since(fs.starttime))
Todd Wang9548d852015-02-10 16:15:59 -08001138 return results, err
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001139}
1140
Todd Wang5739dda2014-11-16 22:44:02 -08001141func (fs *flowServer) cancelContextOnClose(cancel context.CancelFunc) {
1142 // Ensure that the context gets cancelled if the flow is closed
1143 // due to a network error, or client cancellation.
1144 select {
1145 case <-fs.flow.Closed():
1146 // Here we remove the contexts channel as a deadline to the flow.
1147 // We do this to ensure clients get a consistent error when they read/write
1148 // after the flow is closed. Since the flow is already closed, it doesn't
1149 // matter that the context is also cancelled.
1150 fs.flow.SetDeadline(nil)
1151 cancel()
Todd Wang54feabe2015-04-15 23:38:26 -07001152 case <-fs.ctx.Done():
Robin Thellendc26c32e2014-10-06 17:44:04 -07001153 }
Todd Wang5739dda2014-11-16 22:44:02 -08001154}
1155
1156// lookup returns the invoker and authorizer responsible for serving the given
1157// name and method. The suffix is stripped of any leading slashes. If it begins
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001158// with rpc.DebugKeyword, we use the internal debug dispatcher to look up the
Todd Wang5739dda2014-11-16 22:44:02 -08001159// invoker. Otherwise, and we use the server's dispatcher. The suffix and method
1160// value may be modified to match the actual suffix and method to use.
Matt Rosencrantz311378b2015-03-25 15:26:12 -07001161func (fs *flowServer) lookup(suffix string, method string) (rpc.Invoker, security.Authorizer, error) {
1162 if naming.IsReserved(method) {
Asim Shankar149b4972015-04-23 13:29:58 -07001163 return reservedInvoker(fs.disp, fs.server.dispReserved), security.AllowEveryone(), nil
Todd Wang5739dda2014-11-16 22:44:02 -08001164 }
1165 disp := fs.disp
1166 if naming.IsReserved(suffix) {
1167 disp = fs.server.dispReserved
Robin Thellendd24f0842014-09-23 10:27:29 -07001168 }
1169 if disp != nil {
Robin Thellenda02fe8f2014-11-19 09:58:29 -08001170 obj, auth, err := disp.Lookup(suffix)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001171 switch {
1172 case err != nil:
Todd Wang9548d852015-02-10 16:15:59 -08001173 return nil, nil, err
Todd Wang5739dda2014-11-16 22:44:02 -08001174 case obj != nil:
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08001175 invoker, err := objectToInvoker(obj)
1176 if err != nil {
Todd Wang54feabe2015-04-15 23:38:26 -07001177 return nil, nil, verror.New(verror.ErrInternal, fs.ctx, "invalid received object", err)
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08001178 }
1179 return invoker, auth, nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001180 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001181 }
Todd Wang54feabe2015-04-15 23:38:26 -07001182 return nil, nil, verror.New(verror.ErrUnknownSuffix, fs.ctx, suffix)
Todd Wang5739dda2014-11-16 22:44:02 -08001183}
1184
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001185func objectToInvoker(obj interface{}) (rpc.Invoker, error) {
Todd Wang5739dda2014-11-16 22:44:02 -08001186 if obj == nil {
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08001187 return nil, errors.New("nil object")
Todd Wang5739dda2014-11-16 22:44:02 -08001188 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001189 if invoker, ok := obj.(rpc.Invoker); ok {
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08001190 return invoker, nil
Todd Wang5739dda2014-11-16 22:44:02 -08001191 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001192 return rpc.ReflectInvoker(obj)
Todd Wang5739dda2014-11-16 22:44:02 -08001193}
1194
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001195func (fs *flowServer) initSecurity(req *rpc.Request) error {
Ankurb905dae2015-03-04 12:38:20 -08001196 // LocalPrincipal is nil which means we are operating under
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -07001197 // SecurityNone.
Todd Wang54feabe2015-04-15 23:38:26 -07001198 if fs.LocalPrincipal() == nil {
Ankurb905dae2015-03-04 12:38:20 -08001199 return nil
1200 }
1201
Todd Wang5739dda2014-11-16 22:44:02 -08001202 // If additional credentials are provided, make them available in the context
Todd Wang5739dda2014-11-16 22:44:02 -08001203 // Detect unusable blessings now, rather then discovering they are unusable on
1204 // first use.
1205 //
1206 // TODO(ashankar,ataly): Potential confused deputy attack: The client provides
1207 // the server's identity as the blessing. Figure out what we want to do about
1208 // this - should servers be able to assume that a blessing is something that
1209 // does not have the authorizations that the server's own identity has?
Todd Wang54feabe2015-04-15 23:38:26 -07001210 if got, want := req.GrantedBlessings.PublicKey(), fs.LocalPrincipal().PublicKey(); got != nil && !reflect.DeepEqual(got, want) {
1211 return verror.New(verror.ErrNoAccess, fs.ctx, fmt.Sprintf("blessing granted not bound to this server(%v vs %v)", got, want))
Todd Wang5739dda2014-11-16 22:44:02 -08001212 }
Asim Shankarb07ec692015-02-27 23:40:44 -08001213 fs.grantedBlessings = req.GrantedBlessings
Ankurb905dae2015-03-04 12:38:20 -08001214
Asim Shankarb07ec692015-02-27 23:40:44 -08001215 var err error
1216 if fs.clientBlessings, err = serverDecodeBlessings(fs.flow.VCDataCache(), req.Blessings, fs.server.stats); err != nil {
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001217 // When the server can't access the blessings cache, the client is not following
1218 // protocol, so the server closes the VCs corresponding to the client endpoint.
1219 // TODO(suharshs,toddw): Figure out a way to only shutdown the current VC, instead
1220 // of all VCs connected to the RemoteEndpoint.
1221 fs.server.streamMgr.ShutdownEndpoint(fs.RemoteEndpoint())
Todd Wang54feabe2015-04-15 23:38:26 -07001222 return verror.New(verror.ErrBadProtocol, fs.ctx, newErrBadBlessingsCache(fs.ctx, err))
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001223 }
Ankurb905dae2015-03-04 12:38:20 -08001224 // Verify that the blessings sent by the client in the request have the same public
1225 // key as those sent by the client during VC establishment.
1226 if got, want := fs.clientBlessings.PublicKey(), fs.flow.RemoteBlessings().PublicKey(); got != nil && !reflect.DeepEqual(got, want) {
Todd Wang54feabe2015-04-15 23:38:26 -07001227 return verror.New(verror.ErrNoAccess, fs.ctx, fmt.Sprintf("blessings sent with the request are bound to a different public key (%v) from the blessing used during VC establishment (%v)", got, want))
Ankurb905dae2015-03-04 12:38:20 -08001228 }
Asim Shankar2bf7b1e2015-02-27 00:45:12 -08001229 fs.ackBlessings = true
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001230
Asim Shankar3ad0b8a2015-02-25 00:37:21 -08001231 for _, d := range req.Discharges {
Asim Shankar08642822015-03-02 21:21:09 -08001232 fs.discharges[d.ID()] = d
Todd Wang5739dda2014-11-16 22:44:02 -08001233 }
1234 return nil
Robin Thellendc26c32e2014-10-06 17:44:04 -07001235}
1236
Todd Wang4264e4b2015-04-16 22:43:40 -07001237func authorize(ctx *context.T, call security.Call, auth security.Authorizer) error {
Matt Rosencrantz9dce9b22015-03-02 10:48:37 -08001238 if call.LocalPrincipal() == nil {
Todd Wang5739dda2014-11-16 22:44:02 -08001239 // LocalPrincipal is nil means that the server wanted to avoid
1240 // authentication, and thus wanted to skip authorization as well.
1241 return nil
1242 }
Asim Shankar8f05c222014-10-06 22:08:19 -07001243 if auth == nil {
Asim Shankare4a8c092015-04-01 18:43:39 -07001244 auth = security.DefaultAuthorizer()
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001245 }
Todd Wang4264e4b2015-04-16 22:43:40 -07001246 if err := auth.Authorize(ctx, call); err != nil {
Asim Shankara5457f02014-10-24 23:23:07 -07001247 // TODO(ataly, ashankar): For privacy reasons, should we hide the authorizer error?
Matt Rosencrantz250558f2015-03-17 11:37:31 -07001248 return verror.New(verror.ErrNoAccess, ctx, newErrBadAuth(ctx, call.Suffix(), call.Method(), err))
Asim Shankara5457f02014-10-24 23:23:07 -07001249 }
1250 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001251}
1252
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001253// Send implements the rpc.Stream method.
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001254func (fs *flowServer) Send(item interface{}) error {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001255 defer vlog.LogCall()()
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001256 // The empty response header indicates what follows is a streaming result.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001257 if err := fs.enc.Encode(rpc.Response{}); err != nil {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001258 return err
1259 }
1260 return fs.enc.Encode(item)
1261}
1262
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001263// Recv implements the rpc.Stream method.
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001264func (fs *flowServer) Recv(itemptr interface{}) error {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001265 defer vlog.LogCall()()
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001266 var req rpc.Request
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001267 if err := fs.dec.Decode(&req); err != nil {
1268 return err
1269 }
1270 if req.EndStreamArgs {
1271 fs.endStreamArgs = true
1272 return io.EOF
1273 }
1274 return fs.dec.Decode(itemptr)
1275}
1276
Todd Wang54feabe2015-04-15 23:38:26 -07001277// Implementations of rpc.ServerCall and security.Call methods.
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001278
Todd Wang54feabe2015-04-15 23:38:26 -07001279func (fs *flowServer) Security() security.Call {
1280 //nologcall
1281 return fs
1282}
Ankuredd74ee2015-03-04 16:38:45 -08001283func (fs *flowServer) LocalDischarges() map[string]security.Discharge {
1284 //nologcall
1285 return fs.flow.LocalDischarges()
1286}
Asim Shankar2519cc12014-11-10 21:16:53 -08001287func (fs *flowServer) RemoteDischarges() map[string]security.Discharge {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001288 //nologcall
1289 return fs.discharges
1290}
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001291func (fs *flowServer) Server() rpc.Server {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001292 //nologcall
1293 return fs.server
1294}
Asim Shankar0cad0832014-11-04 01:27:38 -08001295func (fs *flowServer) Timestamp() time.Time {
1296 //nologcall
1297 return fs.starttime
1298}
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001299func (fs *flowServer) Method() string {
1300 //nologcall
1301 return fs.method
1302}
Todd Wangb31da592015-02-20 12:50:39 -08001303func (fs *flowServer) MethodTags() []*vdl.Value {
Asim Shankar0cad0832014-11-04 01:27:38 -08001304 //nologcall
1305 return fs.tags
1306}
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001307func (fs *flowServer) Suffix() string {
1308 //nologcall
1309 return fs.suffix
1310}
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001311func (fs *flowServer) LocalPrincipal() security.Principal {
1312 //nologcall
Asim Shankar8f05c222014-10-06 22:08:19 -07001313 return fs.flow.LocalPrincipal()
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001314}
1315func (fs *flowServer) LocalBlessings() security.Blessings {
1316 //nologcall
Asim Shankar8f05c222014-10-06 22:08:19 -07001317 return fs.flow.LocalBlessings()
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001318}
1319func (fs *flowServer) RemoteBlessings() security.Blessings {
1320 //nologcall
Asim Shankar2bf7b1e2015-02-27 00:45:12 -08001321 if !fs.clientBlessings.IsZero() {
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001322 return fs.clientBlessings
1323 }
Asim Shankar8f05c222014-10-06 22:08:19 -07001324 return fs.flow.RemoteBlessings()
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001325}
Suharsh Sivakumar380bf342015-02-27 15:38:27 -08001326func (fs *flowServer) GrantedBlessings() security.Blessings {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001327 //nologcall
Suharsh Sivakumar380bf342015-02-27 15:38:27 -08001328 return fs.grantedBlessings
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001329}
1330func (fs *flowServer) LocalEndpoint() naming.Endpoint {
1331 //nologcall
1332 return fs.flow.LocalEndpoint()
1333}
1334func (fs *flowServer) RemoteEndpoint() naming.Endpoint {
1335 //nologcall
1336 return fs.flow.RemoteEndpoint()
1337}