blob: f93c7f428b8ef977d17f78717610e75d099715d1 [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 Nicolaouaa87e292015-04-21 22:15:50 -070018
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -070019 "v.io/v23"
Jiri Simsa6ac95222015-02-23 16:11:49 -080020 "v.io/v23/context"
Matt Rosencrantz88be1182015-04-27 13:45:43 -070021 "v.io/v23/i18n"
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
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -070033 "v.io/x/ref/lib/apilog"
Jiri Simsa574ec4b2015-08-11 09:31:37 -070034 "v.io/x/ref/lib/pubsub"
Jiri Simsaffceefa2015-02-28 11:03:34 -080035 "v.io/x/ref/lib/stats"
Suharsh Sivakumardcc11d72015-05-11 12:19:20 -070036 "v.io/x/ref/runtime/internal/lib/publisher"
37 inaming "v.io/x/ref/runtime/internal/naming"
38 "v.io/x/ref/runtime/internal/rpc/stream"
39 "v.io/x/ref/runtime/internal/rpc/stream/manager"
40 "v.io/x/ref/runtime/internal/rpc/stream/vc"
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070041)
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -080042
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070043var (
44 // These errors are intended to be used as arguments to higher
45 // level errors and hence {1}{2} is omitted from their format
46 // strings to avoid repeating these n-times in the final error
47 // message visible to the user.
48 errResponseEncoding = reg(".errResponseEncoding", "failed to encode RPC response {3} <-> {4}{:5}")
49 errResultEncoding = reg(".errResultEncoding", "failed to encode result #{3} [{4}]{:5}")
50 errFailedToResolveToEndpoint = reg(".errFailedToResolveToEndpoint", "failed to resolve {3} to an endpoint")
51 errFailedToResolveProxy = reg(".errFailedToResolveProxy", "failed to resolve proxy {3}{:4}")
52 errFailedToListenForProxy = reg(".errFailedToListenForProxy", "failed to listen on {3}{:4}")
Suharsh Sivakumardcc11d72015-05-11 12:19:20 -070053 errInternalTypeConversion = reg(".errInternalTypeConversion", "failed to convert {3} to v.io/x/ref/runtime/internal/naming.Endpoint")
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070054 errFailedToParseIP = reg(".errFailedToParseIP", "failed to parse {3} as an IP host")
Ali Ghassemibac34032015-04-30 18:27:57 -070055 errUnexpectedSuffix = reg(".errUnexpectedSuffix", "suffix {3} was not expected because either server has the option IsLeaf set to true or it served an object and not a dispatcher")
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -070056 errNoListeners = reg(".errNoListeners", "failed to ceate any listeners{:3}")
Jiri Simsa5293dcb2014-05-10 09:56:38 -070057)
58
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080059// state for each requested listen address
60type listenState struct {
61 protocol, address string
62 ln stream.Listener
63 lep naming.Endpoint
64 lnerr, eperr error
65 roaming bool
66 // We keep track of all of the endpoints, the port and a copy of
67 // the original listen endpoint for use with roaming network changes.
68 ieps []*inaming.Endpoint // list of currently active eps
69 port string // port to use for creating new eps
70 protoIEP inaming.Endpoint // endpoint to use as template for new eps (includes rid, versions etc)
71}
72
73// state for each requested proxy
74type proxyState struct {
75 endpoint naming.Endpoint
Mike Burrowsdc6b3602015-02-05 15:52:12 -080076 err error
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080077}
78
79type dhcpState struct {
80 name string
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -070081 publisher *pubsub.Publisher
82 stream *pubsub.Stream
83 ch chan pubsub.Setting // channel to receive dhcp settings over
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080084 err error // error status.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070085 watchers map[chan<- rpc.NetworkChange]struct{}
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080086}
87
Jiri Simsa5293dcb2014-05-10 09:56:38 -070088type server struct {
89 sync.Mutex
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -080090 // context used by the server to make internal RPCs, error messages etc.
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -070091 ctx *context.T
92 cancel context.CancelFunc // function to cancel the above context.
93 state serverState // track state of the server.
94 streamMgr stream.Manager // stream manager to listen for new flows.
95 publisher publisher.Publisher // publisher to publish mounttable mounts.
Asim Shankar99b18a72015-04-25 23:19:28 -070096 dc vc.DischargeClient // fetches discharges of blessings
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -070097 listenerOpts []stream.ListenerOpt // listener opts for Listen.
98 settingsPublisher *pubsub.Publisher // pubsub publisher for dhcp
99 settingsName string // pubwsub stream name for dhcp
100 dhcpState *dhcpState // dhcpState, nil if not using dhcp
101 principal security.Principal
102 blessings security.Blessings
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800103
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800104 // maps that contain state on listeners.
105 listenState map[*listenState]struct{}
106 listeners map[stream.Listener]struct{}
107
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800108 // state of proxies keyed by the name of the proxy
109 proxies map[string]proxyState
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800110
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700111 disp rpc.Dispatcher // dispatcher to serve RPCs
112 dispReserved rpc.Dispatcher // dispatcher for reserved methods
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800113 active sync.WaitGroup // active goroutines we've spawned.
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800114 stoppedChan chan struct{} // closed when the server has been stopped.
115 preferredProtocols []string // protocols to use when resolving proxy name to endpoint.
Jungho Ahn25545d32015-01-26 15:14:14 -0800116 // We cache the IP networks on the device since it is not that cheap to read
117 // network interfaces through os syscall.
118 // TODO(jhahn): Add monitoring the network interface changes.
119 ipNets []*net.IPNet
Todd Wang5082a552015-04-02 10:56:11 -0700120 ns namespace.T
Jungho Ahn25545d32015-01-26 15:14:14 -0800121 servesMountTable bool
Robin Thellend89e95232015-03-24 13:48:48 -0700122 isLeaf bool
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800123
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700124 // TODO(cnicolaou): add roaming stats to rpcStats
125 stats *rpcStats // stats for this server.
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700126}
127
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800128type serverState int
129
130const (
131 initialized serverState = iota
132 listening
133 serving
134 publishing
135 stopping
136 stopped
137)
138
139// Simple state machine for the server implementation.
140type next map[serverState]bool
141type transitions map[serverState]next
142
143var (
144 states = transitions{
145 initialized: next{listening: true, stopping: true},
146 listening: next{listening: true, serving: true, stopping: true},
147 serving: next{publishing: true, stopping: true},
148 publishing: next{publishing: true, stopping: true},
149 stopping: next{},
150 stopped: next{},
151 }
152
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700153 externalStates = map[serverState]rpc.ServerState{
154 initialized: rpc.ServerInit,
155 listening: rpc.ServerActive,
156 serving: rpc.ServerActive,
157 publishing: rpc.ServerActive,
158 stopping: rpc.ServerStopping,
159 stopped: rpc.ServerStopped,
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800160 }
161)
162
163func (s *server) allowed(next serverState, method string) error {
164 if states[s.state][next] {
165 s.state = next
166 return nil
167 }
Jiri Simsa074bf362015-02-17 09:29:45 -0800168 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 -0800169}
170
171func (s *server) isStopState() bool {
172 return s.state == stopping || s.state == stopped
173}
174
Matt Rosencrantz98d6d7c2015-09-04 12:34:08 -0700175var _ rpc.DeprecatedServer = (*server)(nil)
Benjamin Prosnitzfdfbf7b2014-10-08 09:47:21 -0700176
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -0700177func InternalNewServer(
178 ctx *context.T,
179 streamMgr stream.Manager,
180 ns namespace.T,
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -0700181 settingsPublisher *pubsub.Publisher,
182 settingsName string,
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -0700183 client rpc.Client,
Matt Rosencrantz98d6d7c2015-09-04 12:34:08 -0700184 opts ...rpc.ServerOpt) (rpc.DeprecatedServer, error) {
Matt Rosencrantz1094d062015-01-30 06:43:12 -0800185 ctx, cancel := context.WithRootCancel(ctx)
Todd Wangad492042015-04-17 15:58:40 -0700186 ctx, _ = vtrace.WithNewSpan(ctx, "NewServer")
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700187 statsPrefix := naming.Join("rpc", "server", "routing-id", streamMgr.RoutingID().String())
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700188 s := &server{
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700189 ctx: ctx,
190 cancel: cancel,
191 streamMgr: streamMgr,
192 publisher: publisher.New(ctx, ns, publishPeriod),
193 listenState: make(map[*listenState]struct{}),
194 listeners: make(map[stream.Listener]struct{}),
195 proxies: make(map[string]proxyState),
196 stoppedChan: make(chan struct{}),
197
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -0700198 ns: ns,
199 stats: newRPCStats(statsPrefix),
200 settingsPublisher: settingsPublisher,
201 settingsName: settingsName,
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700202 }
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700203 var (
204 dischargeExpiryBuffer = vc.DefaultServerDischargeExpiryBuffer
205 securityLevel options.SecurityLevel
206 )
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700207 ipNets, err := ipNetworks()
208 if err != nil {
209 return nil, err
210 }
211 s.ipNets = ipNets
212
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700213 for _, opt := range opts {
Bogdan Caprita187269b2014-05-13 19:59:46 -0700214 switch opt := opt.(type) {
215 case stream.ListenerOpt:
216 // Collect all ServerOpts that are also ListenerOpts.
217 s.listenerOpts = append(s.listenerOpts, opt)
Bogdan Capritae7376312014-11-10 13:13:17 -0800218 switch opt := opt.(type) {
Suharsh Sivakumar08918582015-03-03 15:16:36 -0800219 case vc.DischargeExpiryBuffer:
220 dischargeExpiryBuffer = time.Duration(opt)
Bogdan Capritae7376312014-11-10 13:13:17 -0800221 }
Suharsh Sivakumare5e5dcc2015-03-18 14:29:31 -0700222 case options.ServerBlessings:
223 s.blessings = opt.Blessings
Asim Shankarcc044212014-10-15 23:25:26 -0700224 case options.ServesMountTable:
Cosmos Nicolaoue6e87f12014-06-03 14:29:10 -0700225 s.servesMountTable = bool(opt)
Ali Ghassemibac34032015-04-30 18:27:57 -0700226 case options.IsLeaf:
227 s.isLeaf = bool(opt)
Suharsh Sivakumard7a65192015-01-27 22:57:15 -0800228 case ReservedNameDispatcher:
Todd Wang5739dda2014-11-16 22:44:02 -0800229 s.dispReserved = opt.Dispatcher
Nicolas LaCasse55a10f32014-11-26 13:25:53 -0800230 case PreferredServerResolveProtocols:
231 s.preferredProtocols = []string(opt)
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700232 case options.SecurityLevel:
233 securityLevel = opt
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700234
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700235 }
236 }
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700237
238 authenticateVC := true
239
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700240 if securityLevel == options.SecurityNone {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700241 authenticateVC = false
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700242 s.blessings = security.Blessings{}
243 s.dispReserved = nil
244 }
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700245 if authenticateVC {
246 s.principal = v23.GetPrincipal(ctx)
247 if s.blessings.IsZero() && s.principal != nil {
248 s.blessings = s.principal.BlessingStore().Default()
249 }
250 }
251
Suharsh Sivakumar08918582015-03-03 15:16:36 -0800252 // Make dischargeExpiryBuffer shorter than the VC discharge buffer to ensure we have fetched
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700253 // the discharges by the time the VC asks for them.
Asim Shankar99b18a72015-04-25 23:19:28 -0700254 s.dc = InternalNewDischargeClient(ctx, client, dischargeExpiryBuffer-(5*time.Second))
255 s.listenerOpts = append(s.listenerOpts, s.dc)
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700256 s.listenerOpts = append(s.listenerOpts, stream.AuthenticatedVC(authenticateVC))
Bogdan Capritae7376312014-11-10 13:13:17 -0800257 blessingsStatsName := naming.Join(statsPrefix, "security", "blessings")
Asim Shankar2bf7b1e2015-02-27 00:45:12 -0800258 // TODO(caprita): revist printing the blessings with %s, and
259 // instead expose them as a list.
Suharsh Sivakumare5e5dcc2015-03-18 14:29:31 -0700260 stats.NewString(blessingsStatsName).Set(fmt.Sprintf("%s", s.blessings))
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700261 if s.principal != nil {
Bogdan Capritae7376312014-11-10 13:13:17 -0800262 stats.NewStringFunc(blessingsStatsName, func() string {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700263 return fmt.Sprintf("%s (default)", s.principal.BlessingStore().Default())
Bogdan Capritae7376312014-11-10 13:13:17 -0800264 })
265 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700266 return s, nil
267}
268
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700269func (s *server) Status() rpc.ServerStatus {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700270 defer apilog.LogCall(nil)(nil) // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700271 status := rpc.ServerStatus{}
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700272 s.Lock()
273 defer s.Unlock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800274 status.State = externalStates[s.state]
275 status.ServesMountTable = s.servesMountTable
276 status.Mounts = s.publisher.Status()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800277 status.Endpoints = []naming.Endpoint{}
278 for ls, _ := range s.listenState {
279 if ls.eperr != nil {
280 status.Errors = append(status.Errors, ls.eperr)
281 }
282 if ls.lnerr != nil {
283 status.Errors = append(status.Errors, ls.lnerr)
284 }
285 for _, iep := range ls.ieps {
286 status.Endpoints = append(status.Endpoints, iep)
287 }
288 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700289 status.Proxies = make([]rpc.ProxyStatus, 0, len(s.proxies))
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800290 for k, v := range s.proxies {
Jiri Simsad9a7b3c2015-08-12 16:38:27 -0700291 status.Proxies = append(status.Proxies, rpc.ProxyStatus{
292 Proxy: k,
293 Endpoint: v.endpoint,
294 Error: v.err,
295 })
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700296 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800297 return status
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700298}
299
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700300func (s *server) WatchNetwork(ch chan<- rpc.NetworkChange) {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700301 defer apilog.LogCallf(nil, "ch=")(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800302 s.Lock()
303 defer s.Unlock()
304 if s.dhcpState != nil {
305 s.dhcpState.watchers[ch] = struct{}{}
306 }
307}
308
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700309func (s *server) UnwatchNetwork(ch chan<- rpc.NetworkChange) {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700310 defer apilog.LogCallf(nil, "ch=")(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800311 s.Lock()
312 defer s.Unlock()
313 if s.dhcpState != nil {
314 delete(s.dhcpState.watchers, ch)
315 }
316}
317
Robin Thellend92b65a42014-12-17 14:30:16 -0800318// resolveToEndpoint resolves an object name or address to an endpoint.
319func (s *server) resolveToEndpoint(address string) (string, error) {
Asim Shankaraae31802015-01-22 11:59:42 -0800320 var resolved *naming.MountEntry
321 var err error
Asim Shankardee311d2014-08-01 17:41:31 -0700322 if s.ns != nil {
Asim Shankaraae31802015-01-22 11:59:42 -0800323 if resolved, err = s.ns.Resolve(s.ctx, address); err != nil {
Asim Shankardee311d2014-08-01 17:41:31 -0700324 return "", err
325 }
326 } else {
Asim Shankaraae31802015-01-22 11:59:42 -0800327 // Fake a namespace resolution
328 resolved = &naming.MountEntry{Servers: []naming.MountedServer{
329 {Server: address},
330 }}
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700331 }
Nicolas LaCasse55a10f32014-11-26 13:25:53 -0800332 // An empty set of protocols means all protocols...
Jungho Ahn25545d32015-01-26 15:14:14 -0800333 if resolved.Servers, err = filterAndOrderServers(resolved.Servers, s.preferredProtocols, s.ipNets); err != nil {
Nicolas LaCasse55a10f32014-11-26 13:25:53 -0800334 return "", err
335 }
Asim Shankaraae31802015-01-22 11:59:42 -0800336 for _, n := range resolved.Names() {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700337 address, suffix := naming.SplitAddressName(n)
David Why Use Two When One Will Do Presottoadf0ca12014-11-13 10:49:01 -0800338 if suffix != "" {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700339 continue
340 }
Asim Shankaraae31802015-01-22 11:59:42 -0800341 if ep, err := inaming.NewEndpoint(address); err == nil {
342 return ep.String(), nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700343 }
344 }
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700345 return "", verror.New(errFailedToResolveToEndpoint, s.ctx, address)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700346}
347
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800348// createEndpoints creates appropriate inaming.Endpoint instances for
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800349// all of the externally accessible network addresses that can be used
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800350// to reach this server.
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700351func (s *server) createEndpoints(lep naming.Endpoint, chooser netstate.AddressChooser) ([]*inaming.Endpoint, string, bool, error) {
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800352 iep, ok := lep.(*inaming.Endpoint)
353 if !ok {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700354 return nil, "", false, verror.New(errInternalTypeConversion, nil, fmt.Sprintf("%T", lep))
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800355 }
356 if !strings.HasPrefix(iep.Protocol, "tcp") &&
357 !strings.HasPrefix(iep.Protocol, "ws") {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800358 // If not tcp, ws, or wsh, just return the endpoint we were given.
359 return []*inaming.Endpoint{iep}, "", false, nil
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800360 }
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800361 host, port, err := net.SplitHostPort(iep.Address)
362 if err != nil {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800363 return nil, "", false, err
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800364 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700365 addrs, unspecified, err := netstate.PossibleAddresses(iep.Protocol, host, chooser)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800366 if err != nil {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800367 return nil, port, false, err
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800368 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700369
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800370 ieps := make([]*inaming.Endpoint, 0, len(addrs))
371 for _, addr := range addrs {
372 n, err := inaming.NewEndpoint(lep.String())
373 if err != nil {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800374 return nil, port, false, err
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800375 }
376 n.IsMountTable = s.servesMountTable
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700377 n.Address = net.JoinHostPort(addr.String(), port)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800378 ieps = append(ieps, n)
379 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800380 return ieps, port, unspecified, nil
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800381}
382
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700383func (s *server) Listen(listenSpec rpc.ListenSpec) ([]naming.Endpoint, error) {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700384 defer apilog.LogCallf(nil, "listenSpec=")(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800385 useProxy := len(listenSpec.Proxy) > 0
386 if !useProxy && len(listenSpec.Addrs) == 0 {
Jiri Simsa074bf362015-02-17 09:29:45 -0800387 return nil, verror.New(verror.ErrBadArg, s.ctx, "ListenSpec contains no proxy or addresses to listen on")
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800388 }
389
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700390 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800391 defer s.Unlock()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800392
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800393 if err := s.allowed(listening, "Listen"); err != nil {
394 return nil, err
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700395 }
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700396
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800397 // Start the proxy as early as possible, ignore duplicate requests
398 // for the same proxy.
399 if _, inuse := s.proxies[listenSpec.Proxy]; useProxy && !inuse {
Asim Shankar6b1c8b02015-04-26 22:09:45 -0700400 // Pre-emptively fetch discharges on the blessings (they will be cached
401 // within s.dc for future calls).
402 // This shouldn't be required, but is a hack to reduce flakiness in
403 // JavaScript browser integration tests.
404 // See https://v.io/i/392
405 s.dc.PrepareDischarges(s.ctx, s.blessings.ThirdPartyCaveats(), security.DischargeImpetus{})
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800406 // We have a goroutine for listening on proxy connections.
Cosmos Nicolaoueef1fab2014-11-11 18:23:41 -0800407 s.active.Add(1)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800408 go func() {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800409 s.proxyListenLoop(listenSpec.Proxy)
410 s.active.Done()
411 }()
412 }
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700413
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800414 roaming := false
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800415 lnState := make([]*listenState, 0, len(listenSpec.Addrs))
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800416 for _, addr := range listenSpec.Addrs {
417 if len(addr.Address) > 0 {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800418 // Listen if we have a local address to listen on.
419 ls := &listenState{
420 protocol: addr.Protocol,
421 address: addr.Address,
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800422 }
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700423 ls.ln, ls.lep, ls.lnerr = s.streamMgr.Listen(s.ctx, addr.Protocol, addr.Address, s.blessings, s.listenerOpts...)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800424 lnState = append(lnState, ls)
425 if ls.lnerr != nil {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700426 s.ctx.VI(2).Infof("Listen(%q, %q, ...) failed: %v", addr.Protocol, addr.Address, ls.lnerr)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800427 continue
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800428 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800429 ls.ieps, ls.port, ls.roaming, ls.eperr = s.createEndpoints(ls.lep, listenSpec.AddressChooser)
430 if ls.roaming && ls.eperr == nil {
431 ls.protoIEP = *ls.lep.(*inaming.Endpoint)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800432 roaming = true
433 }
434 }
435 }
436
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800437 found := false
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700438 var lastErr error
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800439 for _, ls := range lnState {
440 if ls.ln != nil {
441 found = true
442 break
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800443 }
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700444 if ls.lnerr != nil {
445 lastErr = ls.lnerr
446 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800447 }
448 if !found && !useProxy {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700449 return nil, verror.New(verror.ErrBadArg, s.ctx, verror.New(errNoListeners, s.ctx, lastErr))
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800450 }
451
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -0700452 if roaming && s.dhcpState == nil && s.settingsPublisher != nil {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800453 // Create a dhcp listener if we haven't already done so.
454 dhcp := &dhcpState{
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -0700455 name: s.settingsName,
456 publisher: s.settingsPublisher,
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700457 watchers: make(map[chan<- rpc.NetworkChange]struct{}),
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800458 }
459 s.dhcpState = dhcp
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -0700460 dhcp.ch = make(chan pubsub.Setting, 10)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800461 dhcp.stream, dhcp.err = dhcp.publisher.ForkStream(dhcp.name, dhcp.ch)
462 if dhcp.err == nil {
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800463 // We have a goroutine to listen for dhcp changes.
464 s.active.Add(1)
465 go func() {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800466 s.dhcpLoop(dhcp.ch)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800467 s.active.Done()
468 }()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800469 }
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800470 }
471
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800472 eps := make([]naming.Endpoint, 0, 10)
473 for _, ls := range lnState {
474 s.listenState[ls] = struct{}{}
475 if ls.ln != nil {
476 // We have a goroutine per listener to accept new flows.
477 // Each flow is served from its own goroutine.
478 s.active.Add(1)
479 go func(ln stream.Listener, ep naming.Endpoint) {
480 s.listenLoop(ln, ep)
481 s.active.Done()
482 }(ls.ln, ls.lep)
483 }
484
485 for _, iep := range ls.ieps {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800486 eps = append(eps, iep)
487 }
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800488 }
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800489
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800490 return eps, nil
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700491}
492
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800493func (s *server) reconnectAndPublishProxy(proxy string) (*inaming.Endpoint, stream.Listener, error) {
Robin Thellend92b65a42014-12-17 14:30:16 -0800494 resolved, err := s.resolveToEndpoint(proxy)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800495 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700496 return nil, nil, verror.New(errFailedToResolveProxy, s.ctx, proxy, err)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800497 }
Asim Shankar99b18a72015-04-25 23:19:28 -0700498 opts := append([]stream.ListenerOpt{proxyAuth{s}}, s.listenerOpts...)
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700499 ln, ep, err := s.streamMgr.Listen(s.ctx, inaming.Network, resolved, s.blessings, opts...)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800500 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700501 return nil, nil, verror.New(errFailedToListenForProxy, s.ctx, resolved, err)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800502 }
503 iep, ok := ep.(*inaming.Endpoint)
504 if !ok {
505 ln.Close()
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700506 return nil, nil, verror.New(errInternalTypeConversion, s.ctx, fmt.Sprintf("%T", ep))
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800507 }
508 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800509 s.proxies[proxy] = proxyState{iep, nil}
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800510 s.Unlock()
Robin Thellende22920e2015-02-05 17:15:50 -0800511 iep.IsMountTable = s.servesMountTable
Robin Thellendb457df92015-03-30 09:42:15 -0700512 iep.IsLeaf = s.isLeaf
Robin Thellend89e95232015-03-24 13:48:48 -0700513 s.publisher.AddServer(iep.String())
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800514 return iep, ln, nil
515}
516
517func (s *server) proxyListenLoop(proxy string) {
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700518 const (
519 min = 5 * time.Millisecond
520 max = 5 * time.Minute
521 )
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800522
523 iep, ln, err := s.reconnectAndPublishProxy(proxy)
524 if err != nil {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700525 s.ctx.Errorf("Failed to connect to proxy: %s", err)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800526 }
527 // the initial connection maybe have failed, but we enter the retry
528 // loop anyway so that we will continue to try and connect to the
529 // proxy.
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800530 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800531 if s.isStopState() {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800532 s.Unlock()
533 return
534 }
535 s.Unlock()
536
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700537 for {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800538 if ln != nil && iep != nil {
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800539 err := s.listenLoop(ln, iep)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800540 // The listener is done, so:
541 // (1) Unpublish its name
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800542 s.publisher.RemoveServer(iep.String())
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800543 s.Lock()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800544 if err != nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800545 s.proxies[proxy] = proxyState{iep, verror.New(verror.ErrNoServers, s.ctx, err)}
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800546 } else {
Asim Shankar7171a252015-03-07 14:41:40 -0800547 // err will be nil if we're stopping.
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800548 s.proxies[proxy] = proxyState{iep, nil}
549 s.Unlock()
550 return
551 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800552 s.Unlock()
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800553 }
554
555 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800556 if s.isStopState() {
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800557 s.Unlock()
558 return
559 }
560 s.Unlock()
561
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700562 // (2) Reconnect to the proxy unless the server has been stopped
563 backoff := min
564 ln = nil
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800565 for {
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700566 select {
567 case <-time.After(backoff):
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700568 if backoff = backoff * 2; backoff > max {
569 backoff = max
570 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700571 case <-s.stoppedChan:
572 return
573 }
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800574 // (3) reconnect, publish new address
575 if iep, ln, err = s.reconnectAndPublishProxy(proxy); err != nil {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700576 s.ctx.Errorf("Failed to reconnect to proxy %q: %s", proxy, err)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800577 } else {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700578 s.ctx.VI(1).Infof("Reconnected to proxy %q, %s", proxy, iep)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800579 break
580 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700581 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700582 }
583}
584
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800585// addListener adds the supplied listener taking care to
586// check to see if we're already stopping. It returns true
587// if the listener was added.
588func (s *server) addListener(ln stream.Listener) bool {
589 s.Lock()
590 defer s.Unlock()
591 if s.isStopState() {
592 return false
593 }
594 s.listeners[ln] = struct{}{}
595 return true
596}
597
598// rmListener removes the supplied listener taking care to
599// check if we're already stopping. It returns true if the
600// listener was removed.
601func (s *server) rmListener(ln stream.Listener) bool {
602 s.Lock()
603 defer s.Unlock()
604 if s.isStopState() {
605 return false
606 }
607 delete(s.listeners, ln)
608 return true
609}
610
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800611func (s *server) listenLoop(ln stream.Listener, ep naming.Endpoint) error {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700612 defer s.ctx.VI(1).Infof("rpc: Stopped listening on %s", ep)
Cosmos Nicolaoueef1fab2014-11-11 18:23:41 -0800613 var calls sync.WaitGroup
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800614
615 if !s.addListener(ln) {
616 // We're stopping.
617 return nil
618 }
619
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700620 defer func() {
Cosmos Nicolaoueef1fab2014-11-11 18:23:41 -0800621 calls.Wait()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800622 s.rmListener(ln)
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700623 }()
624 for {
625 flow, err := ln.Accept()
626 if err != nil {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700627 s.ctx.VI(10).Infof("rpc: Accept on %v failed: %v", ep, err)
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800628 return err
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700629 }
Cosmos Nicolaoueef1fab2014-11-11 18:23:41 -0800630 calls.Add(1)
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700631 go func(flow stream.Flow) {
Todd Wang34ed4c62014-11-26 15:15:52 -0800632 defer calls.Done()
633 fs, err := newFlowServer(flow, s)
634 if err != nil {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700635 s.ctx.VI(1).Infof("newFlowServer on %v failed: %v", ep, err)
Todd Wang34ed4c62014-11-26 15:15:52 -0800636 return
637 }
638 if err := fs.serve(); err != nil {
Todd Wang5739dda2014-11-16 22:44:02 -0800639 // TODO(caprita): Logging errors here is too spammy. For example, "not
640 // authorized" errors shouldn't be logged as server errors.
Cosmos Nicolaou93dd88b2015-02-19 15:10:53 -0800641 // TODO(cnicolaou): revisit this when verror2 transition is
642 // done.
Cosmos Nicolaou1534b3f2014-12-10 15:30:00 -0800643 if err != io.EOF {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700644 s.ctx.VI(2).Infof("Flow.serve on %v failed: %v", ep, err)
Cosmos Nicolaou1534b3f2014-12-10 15:30:00 -0800645 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700646 }
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700647 }(flow)
648 }
649}
650
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -0700651func (s *server) dhcpLoop(ch chan pubsub.Setting) {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700652 defer s.ctx.VI(1).Infof("rpc: Stopped listen for dhcp changes")
653 s.ctx.VI(2).Infof("rpc: dhcp loop")
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800654 for setting := range ch {
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700655 if setting == nil {
656 return
657 }
658 switch v := setting.Value().(type) {
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700659 case []net.Addr:
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700660 s.Lock()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800661 if s.isStopState() {
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700662 s.Unlock()
663 return
664 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700665 change := rpc.NetworkChange{
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -0700666 Time: time.Now(),
667 State: externalStates[s.state],
668 }
669 switch setting.Name() {
670 case NewAddrsSetting:
671 change.Changed = s.addAddresses(v)
672 change.AddedAddrs = v
673 case RmAddrsSetting:
674 change.Changed, change.Error = s.removeAddresses(v)
675 change.RemovedAddrs = v
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800676 }
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700677 s.ctx.VI(2).Infof("rpc: dhcp: change %v", change)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800678 for ch, _ := range s.dhcpState.watchers {
679 select {
680 case ch <- change:
681 default:
682 }
683 }
684 s.Unlock()
685 default:
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700686 s.ctx.Errorf("rpc: dhcpLoop: unhandled setting type %T", v)
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700687 }
688 }
689}
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800690
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700691func getHost(address net.Addr) string {
692 host, _, err := net.SplitHostPort(address.String())
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800693 if err == nil {
694 return host
695 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700696 return address.String()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800697
698}
699
700// Remove all endpoints that have the same host address as the supplied
701// address parameter.
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700702func (s *server) removeAddresses(addrs []net.Addr) ([]naming.Endpoint, error) {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800703 var removed []naming.Endpoint
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700704 for _, address := range addrs {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800705 host := getHost(address)
706 for ls, _ := range s.listenState {
707 if ls != nil && ls.roaming && len(ls.ieps) > 0 {
708 remaining := make([]*inaming.Endpoint, 0, len(ls.ieps))
709 for _, iep := range ls.ieps {
710 lnHost, _, err := net.SplitHostPort(iep.Address)
711 if err != nil {
712 lnHost = iep.Address
713 }
714 if lnHost == host {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700715 s.ctx.VI(2).Infof("rpc: dhcp removing: %s", iep)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800716 removed = append(removed, iep)
717 s.publisher.RemoveServer(iep.String())
718 continue
719 }
720 remaining = append(remaining, iep)
721 }
722 ls.ieps = remaining
723 }
724 }
725 }
726 return removed, nil
727}
728
729// Add new endpoints for the new address. There is no way to know with
730// 100% confidence which new endpoints to publish without shutting down
731// all network connections and reinitializing everything from scratch.
732// Instead, we find all roaming listeners with at least one endpoint
733// and create a new endpoint with the same port as the existing ones
734// but with the new address supplied to us to by the dhcp code. As
735// an additional safeguard we reject the new address if it is not
736// externally accessible.
737// This places the onus on the dhcp/roaming code that sends us addresses
738// to ensure that those addresses are externally reachable.
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700739func (s *server) addAddresses(addrs []net.Addr) []naming.Endpoint {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800740 var added []naming.Endpoint
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -0700741 for _, address := range netstate.ConvertToAddresses(addrs) {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800742 if !netstate.IsAccessibleIP(address) {
743 return added
744 }
745 host := getHost(address)
746 for ls, _ := range s.listenState {
747 if ls != nil && ls.roaming {
748 niep := ls.protoIEP
749 niep.Address = net.JoinHostPort(host, ls.port)
Robin Thellendb457df92015-03-30 09:42:15 -0700750 niep.IsMountTable = s.servesMountTable
751 niep.IsLeaf = s.isLeaf
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800752 ls.ieps = append(ls.ieps, &niep)
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700753 s.ctx.VI(2).Infof("rpc: dhcp adding: %s", niep)
Robin Thellend89e95232015-03-24 13:48:48 -0700754 s.publisher.AddServer(niep.String())
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800755 added = append(added, &niep)
756 }
757 }
758 }
759 return added
760}
Cosmos Nicolaouef323db2014-09-07 22:13:28 -0700761
Bogdan Caprita7590a6d2015-01-08 13:43:40 -0800762type leafDispatcher struct {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700763 invoker rpc.Invoker
Bogdan Caprita7590a6d2015-01-08 13:43:40 -0800764 auth security.Authorizer
765}
766
Cosmos Nicolaou5a3125a2015-07-10 11:19:20 -0700767func (d leafDispatcher) Lookup(ctx *context.T, suffix string) (interface{}, security.Authorizer, error) {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700768 defer apilog.LogCallf(nil, "suffix=%.10s...", suffix)(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Bogdan Caprita7590a6d2015-01-08 13:43:40 -0800769 if suffix != "" {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700770 return nil, nil, verror.New(verror.ErrUnknownSuffix, nil, suffix)
Bogdan Caprita7590a6d2015-01-08 13:43:40 -0800771 }
772 return d.invoker, d.auth, nil
773}
774
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800775func (s *server) Serve(name string, obj interface{}, authorizer security.Authorizer) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700776 defer apilog.LogCallf(nil, "name=%.10s...,obj=,authorizer=", name)(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800777 if obj == nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800778 return verror.New(verror.ErrBadArg, s.ctx, "nil object")
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800779 }
Bogdan Caprita9592d9f2015-01-08 22:15:16 -0800780 invoker, err := objectToInvoker(obj)
781 if err != nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800782 return verror.New(verror.ErrBadArg, s.ctx, fmt.Sprintf("bad object: %v", err))
Cosmos Nicolaou61c96c72014-11-03 11:57:56 -0800783 }
Robin Thellendb457df92015-03-30 09:42:15 -0700784 s.setLeaf(true)
Bogdan Caprita9592d9f2015-01-08 22:15:16 -0800785 return s.ServeDispatcher(name, &leafDispatcher{invoker, authorizer})
Cosmos Nicolaou61c96c72014-11-03 11:57:56 -0800786}
787
Robin Thellendb457df92015-03-30 09:42:15 -0700788func (s *server) setLeaf(value bool) {
789 s.Lock()
790 defer s.Unlock()
791 s.isLeaf = value
792 for ls, _ := range s.listenState {
793 for i := range ls.ieps {
794 ls.ieps[i].IsLeaf = s.isLeaf
795 }
796 }
797}
798
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700799func (s *server) ServeDispatcher(name string, disp rpc.Dispatcher) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700800 defer apilog.LogCallf(nil, "name=%.10s...,disp=", name)(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800801 if disp == nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800802 return verror.New(verror.ErrBadArg, s.ctx, "nil dispatcher")
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700803 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800804 s.Lock()
805 defer s.Unlock()
806 if err := s.allowed(serving, "Serve or ServeDispatcher"); err != nil {
807 return err
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700808 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800809 vtrace.GetSpan(s.ctx).Annotate("Serving under name: " + name)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800810 s.disp = disp
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700811 if len(name) > 0 {
Robin Thellendb457df92015-03-30 09:42:15 -0700812 for ls, _ := range s.listenState {
813 for _, iep := range ls.ieps {
814 s.publisher.AddServer(iep.String())
815 }
816 }
Robin Thellend89e95232015-03-24 13:48:48 -0700817 s.publisher.AddName(name, s.servesMountTable, s.isLeaf)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700818 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700819 return nil
820}
821
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800822func (s *server) AddName(name string) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700823 defer apilog.LogCallf(nil, "name=%.10s...", name)(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Ali Ghassemi3c6db7b2014-11-10 17:20:26 -0800824 if len(name) == 0 {
Jiri Simsa074bf362015-02-17 09:29:45 -0800825 return verror.New(verror.ErrBadArg, s.ctx, "name is empty")
Ali Ghassemi3c6db7b2014-11-10 17:20:26 -0800826 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800827 s.Lock()
828 defer s.Unlock()
829 if err := s.allowed(publishing, "AddName"); err != nil {
830 return err
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800831 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800832 vtrace.GetSpan(s.ctx).Annotate("Serving under name: " + name)
Robin Thellend89e95232015-03-24 13:48:48 -0700833 s.publisher.AddName(name, s.servesMountTable, s.isLeaf)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800834 return nil
835}
836
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800837func (s *server) RemoveName(name string) {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700838 defer apilog.LogCallf(nil, "name=%.10s...", name)(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800839 s.Lock()
840 defer s.Unlock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800841 if err := s.allowed(publishing, "RemoveName"); err != nil {
842 return
843 }
Matt Rosencrantz5f98d942015-01-08 13:48:30 -0800844 vtrace.GetSpan(s.ctx).Annotate("Removed name: " + name)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800845 s.publisher.RemoveName(name)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800846}
847
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700848func (s *server) Stop() error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700849 defer apilog.LogCall(nil)(nil) // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Bogdan Caprita0ca02162015-04-30 11:21:44 -0700850 serverDebug := fmt.Sprintf("Dispatcher: %T, Status:[%v]", s.disp, s.Status())
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700851 s.ctx.VI(1).Infof("Stop: %s", serverDebug)
852 defer s.ctx.VI(1).Infof("Stop done: %s", serverDebug)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700853 s.Lock()
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800854 if s.isStopState() {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700855 s.Unlock()
856 return nil
857 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800858 s.state = stopping
Asim Shankar0ea02ab2014-06-09 11:39:24 -0700859 close(s.stoppedChan)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700860 s.Unlock()
861
Robin Thellenddf428232014-10-06 12:50:44 -0700862 // Delete the stats object.
863 s.stats.stop()
864
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700865 // Note, It's safe to Stop/WaitForStop on the publisher outside of the
866 // server lock, since publisher is safe for concurrent access.
867
868 // Stop the publisher, which triggers unmounting of published names.
869 s.publisher.Stop()
870 // Wait for the publisher to be done unmounting before we can proceed to
871 // close the listeners (to minimize the number of mounted names pointing
872 // to endpoint that are no longer serving).
873 //
874 // TODO(caprita): See if make sense to fail fast on rejecting
875 // connections once listeners are closed, and parallelize the publisher
876 // and listener shutdown.
877 s.publisher.WaitForStop()
878
879 s.Lock()
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800880
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700881 // Close all listeners. No new flows will be accepted, while in-flight
882 // flows will continue until they terminate naturally.
883 nListeners := len(s.listeners)
884 errCh := make(chan error, nListeners)
Cosmos Nicolaoubc743142014-10-06 21:27:18 -0700885
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800886 for ln, _ := range s.listeners {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700887 go func(ln stream.Listener) {
888 errCh <- ln.Close()
889 }(ln)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800890 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800891
Cosmos Nicolaou11c0ca12015-04-23 16:23:43 -0700892 drain := func(ch chan pubsub.Setting) {
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800893 for {
894 select {
895 case v := <-ch:
896 if v == nil {
897 return
898 }
899 default:
900 close(ch)
901 return
902 }
903 }
904 }
905
906 if dhcp := s.dhcpState; dhcp != nil {
Cosmos Nicolaouaceb8d92015-02-05 20:44:02 -0800907 // TODO(cnicolaou,caprita): investigate not having to close and drain
908 // the channel here. It's a little awkward right now since we have to
909 // be careful to not close the channel in two places, i.e. here and
910 // and from the publisher's Shutdown method.
911 if err := dhcp.publisher.CloseFork(dhcp.name, dhcp.ch); err == nil {
912 drain(dhcp.ch)
913 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700914 }
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800915
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700916 s.Unlock()
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800917
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700918 var firstErr error
919 for i := 0; i < nListeners; i++ {
920 if err := <-errCh; err != nil && firstErr == nil {
921 firstErr = err
922 }
923 }
924 // At this point, we are guaranteed that no new requests are going to be
925 // accepted.
926
927 // Wait for the publisher and active listener + flows to finish.
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800928 done := make(chan struct{}, 1)
929 go func() { s.active.Wait(); done <- struct{}{} }()
930
931 select {
932 case <-done:
Bogdan Caprita0ca02162015-04-30 11:21:44 -0700933 case <-time.After(5 * time.Second):
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700934 s.ctx.Errorf("%s: Listener Close Error: %v", serverDebug, firstErr)
935 s.ctx.Errorf("%s: Timedout waiting for goroutines to stop: listeners: %d (currently: %d)", serverDebug, nListeners, len(s.listeners))
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800936 for ln, _ := range s.listeners {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700937 s.ctx.Errorf("%s: Listener: %v", serverDebug, ln)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800938 }
939 for ls, _ := range s.listenState {
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700940 s.ctx.Errorf("%s: ListenState: %v", serverDebug, ls)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800941 }
942 <-done
Cosmos Nicolaoue9c622d2015-07-10 11:09:42 -0700943 s.ctx.Infof("%s: Done waiting.", serverDebug)
Cosmos Nicolaou1b3594d2015-02-01 10:05:03 -0800944 }
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800945
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700946 s.Lock()
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800947 defer s.Unlock()
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700948 s.disp = nil
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800949 if firstErr != nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800950 return verror.New(verror.ErrInternal, s.ctx, firstErr)
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800951 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800952 s.state = stopped
Matt Rosencrantz1094d062015-01-30 06:43:12 -0800953 s.cancel()
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800954 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700955}
956
957// flowServer implements the RPC server-side protocol for a single RPC, over a
958// flow that's already connected to the client.
959type flowServer struct {
Todd Wang54feabe2015-04-15 23:38:26 -0700960 ctx *context.T // context associated with the RPC
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700961 server *server // rpc.Server that this flow server belongs to
962 disp rpc.Dispatcher // rpc.Dispatcher that will serve RPCs on this flow
Todd Wang3425a902015-01-21 18:43:59 -0800963 dec *vom.Decoder // to decode requests and args from the client
964 enc *vom.Encoder // to encode responses and results to the client
Todd Wang5739dda2014-11-16 22:44:02 -0800965 flow stream.Flow // underlying flow
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700966
Asim Shankar220a0152014-10-30 21:21:09 -0700967 // Fields filled in during the server invocation.
Suharsh Sivakumar380bf342015-02-27 15:38:27 -0800968 clientBlessings security.Blessings
969 ackBlessings bool
970 grantedBlessings security.Blessings
971 method, suffix string
972 tags []*vdl.Value
973 discharges map[string]security.Discharge
974 starttime time.Time
975 endStreamArgs bool // are the stream args at EOF?
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700976}
977
Todd Wang54feabe2015-04-15 23:38:26 -0700978var (
979 _ rpc.StreamServerCall = (*flowServer)(nil)
980 _ security.Call = (*flowServer)(nil)
981)
Benjamin Prosnitzfdfbf7b2014-10-08 09:47:21 -0700982
Todd Wang34ed4c62014-11-26 15:15:52 -0800983func newFlowServer(flow stream.Flow, server *server) (*flowServer, error) {
Cosmos Nicolaoudcba93d2014-07-30 11:09:26 -0700984 server.Lock()
985 disp := server.disp
986 server.Unlock()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -0700987
Todd Wang34ed4c62014-11-26 15:15:52 -0800988 fs := &flowServer{
Todd Wang54feabe2015-04-15 23:38:26 -0700989 ctx: server.ctx,
Todd Wang34ed4c62014-11-26 15:15:52 -0800990 server: server,
991 disp: disp,
Todd Wang5739dda2014-11-16 22:44:02 -0800992 flow: flow,
993 discharges: make(map[string]security.Discharge),
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700994 }
Jungho Ahncfc89622015-04-24 11:27:23 -0700995 typeenc := flow.VCDataCache().Get(vc.TypeEncoderKey{})
996 if typeenc == nil {
Jungho Ahn5d1fe972015-04-27 17:51:32 -0700997 fs.enc = vom.NewEncoder(flow)
998 fs.dec = vom.NewDecoder(flow)
Jungho Ahncfc89622015-04-24 11:27:23 -0700999 } else {
Jungho Ahn5d1fe972015-04-27 17:51:32 -07001000 fs.enc = vom.NewEncoderWithTypeEncoder(flow, typeenc.(*vom.TypeEncoder))
Jungho Ahncfc89622015-04-24 11:27:23 -07001001 typedec := flow.VCDataCache().Get(vc.TypeDecoderKey{})
Jungho Ahn5d1fe972015-04-27 17:51:32 -07001002 fs.dec = vom.NewDecoderWithTypeDecoder(flow, typedec.(*vom.TypeDecoder))
Todd Wang34ed4c62014-11-26 15:15:52 -08001003 }
1004 return fs, nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001005}
1006
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001007// authorizeVtrace works by simulating a call to __debug/vtrace.Trace. That
1008// rpc is essentially equivalent in power to the data we are attempting to
1009// attach here.
Cosmos Nicolaou5a3125a2015-07-10 11:19:20 -07001010func (fs *flowServer) authorizeVtrace(ctx *context.T) error {
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001011 // Set up a context as though we were calling __debug/vtrace.
1012 params := &security.CallParams{}
Todd Wang4264e4b2015-04-16 22:43:40 -07001013 params.Copy(fs)
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001014 params.Method = "Trace"
1015 params.MethodTags = []*vdl.Value{vdl.ValueOf(access.Debug)}
1016 params.Suffix = "__debug/vtrace"
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001017
1018 var auth security.Authorizer
1019 if fs.server.dispReserved != nil {
Cosmos Nicolaou5a3125a2015-07-10 11:19:20 -07001020 _, auth, _ = fs.server.dispReserved.Lookup(ctx, params.Suffix)
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001021 }
Todd Wang4264e4b2015-04-16 22:43:40 -07001022 return authorize(fs.ctx, security.NewCall(params), auth)
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001023}
1024
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001025func (fs *flowServer) serve() error {
1026 defer fs.flow.Close()
Matt Rosencrantz86897932014-10-02 09:34:34 -07001027
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001028 results, err := fs.processRequest()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001029
Todd Wang54feabe2015-04-15 23:38:26 -07001030 vtrace.GetSpan(fs.ctx).Finish()
Matt Rosencrantz1fa32772014-10-28 11:31:46 -07001031
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001032 var traceResponse vtrace.Response
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001033 // Check if the caller is permitted to view vtrace data.
Cosmos Nicolaou5a3125a2015-07-10 11:19:20 -07001034 if fs.authorizeVtrace(fs.ctx) == nil {
Todd Wang54feabe2015-04-15 23:38:26 -07001035 traceResponse = vtrace.GetResponse(fs.ctx)
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001036 }
1037
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001038 // Respond to the client with the response header and positional results.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001039 response := rpc.Response{
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001040 Error: err,
1041 EndStreamResults: true,
1042 NumPosResults: uint64(len(results)),
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001043 TraceResponse: traceResponse,
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001044 AckBlessings: fs.ackBlessings,
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001045 }
1046 if err := fs.enc.Encode(response); err != nil {
Cosmos Nicolaou1534b3f2014-12-10 15:30:00 -08001047 if err == io.EOF {
1048 return err
1049 }
Todd Wang54feabe2015-04-15 23:38:26 -07001050 return verror.New(errResponseEncoding, fs.ctx, fs.LocalEndpoint().String(), fs.RemoteEndpoint().String(), err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001051 }
1052 if response.Error != nil {
1053 return response.Error
1054 }
1055 for ix, res := range results {
Todd Wangf519f8f2015-01-21 10:07:41 -08001056 if err := fs.enc.Encode(res); err != nil {
Cosmos Nicolaou1534b3f2014-12-10 15:30:00 -08001057 if err == io.EOF {
1058 return err
1059 }
Todd Wang54feabe2015-04-15 23:38:26 -07001060 return verror.New(errResultEncoding, fs.ctx, ix, fmt.Sprintf("%T=%v", res, res), err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001061 }
1062 }
1063 // TODO(ashankar): Should unread data from the flow be drained?
1064 //
1065 // Reason to do so:
Suharsh Sivakumardcc11d72015-05-11 12:19:20 -07001066 // The common stream.Flow implementation (v.io/x/ref/runtime/internal/rpc/stream/vc/reader.go)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001067 // uses iobuf.Slices backed by an iobuf.Pool. If the stream is not drained, these
1068 // slices will not be returned to the pool leading to possibly increased memory usage.
1069 //
1070 // Reason to not do so:
1071 // Draining here will conflict with any Reads on the flow in a separate goroutine
1072 // (for example, see TestStreamReadTerminatedByServer in full_test.go).
1073 //
1074 // For now, go with the reason to not do so as having unread data in the stream
1075 // should be a rare case.
1076 return nil
1077}
1078
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001079func (fs *flowServer) readRPCRequest() (*rpc.Request, error) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001080 // Set a default timeout before reading from the flow. Without this timeout,
1081 // a client that sends no request or a partial request will retain the flow
1082 // indefinitely (and lock up server resources).
Matt Rosencrantz86897932014-10-02 09:34:34 -07001083 initTimer := newTimer(defaultCallTimeout)
1084 defer initTimer.Stop()
1085 fs.flow.SetDeadline(initTimer.C)
1086
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001087 // Decode the initial request.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001088 var req rpc.Request
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001089 if err := fs.dec.Decode(&req); err != nil {
Todd Wang54feabe2015-04-15 23:38:26 -07001090 return nil, verror.New(verror.ErrBadProtocol, fs.ctx, newErrBadRequest(fs.ctx, err))
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001091 }
Matt Rosencrantz86897932014-10-02 09:34:34 -07001092 return &req, nil
1093}
1094
Todd Wang9548d852015-02-10 16:15:59 -08001095func (fs *flowServer) processRequest() ([]interface{}, error) {
Asim Shankar0cad0832014-11-04 01:27:38 -08001096 fs.starttime = time.Now()
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001097 req, err := fs.readRPCRequest()
Todd Wang9548d852015-02-10 16:15:59 -08001098 if err != nil {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001099 // We don't know what the rpc call was supposed to be, but we'll create
Matt Rosencrantz1fa32772014-10-28 11:31:46 -07001100 // a placeholder span so we can capture annotations.
Todd Wangad492042015-04-17 15:58:40 -07001101 fs.ctx, _ = vtrace.WithNewSpan(fs.ctx, fmt.Sprintf("\"%s\".UNKNOWN", fs.suffix))
Todd Wang9548d852015-02-10 16:15:59 -08001102 return nil, err
Matt Rosencrantz86897932014-10-02 09:34:34 -07001103 }
Suharsh Sivakumarc095fc22015-06-29 16:00:18 -07001104 // We must call fs.drainDecoderArgs for any error that occurs
1105 // after this point, and before we actually decode the arguments.
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001106 fs.method = req.Method
Todd Wang5739dda2014-11-16 22:44:02 -08001107 fs.suffix = strings.TrimLeft(req.Suffix, "/")
Matt Rosencrantz86897932014-10-02 09:34:34 -07001108
Matt Rosencrantz88be1182015-04-27 13:45:43 -07001109 if req.Language != "" {
1110 fs.ctx = i18n.WithLangID(fs.ctx, i18n.LangID(req.Language))
1111 }
1112
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001113 // TODO(mattr): Currently this allows users to trigger trace collection
1114 // on the server even if they will not be allowed to collect the
Matt Rosencrantz3197d6c2014-11-06 09:53:22 -08001115 // results later. This might be considered a DOS vector.
Todd Wang54feabe2015-04-15 23:38:26 -07001116 spanName := fmt.Sprintf("\"%s\".%s", fs.suffix, fs.method)
Todd Wangad492042015-04-17 15:58:40 -07001117 fs.ctx, _ = vtrace.WithContinuedTrace(fs.ctx, spanName, req.TraceRequest)
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001118
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001119 var cancel context.CancelFunc
Todd Wangf6a06882015-02-27 17:38:01 -08001120 if !req.Deadline.IsZero() {
Todd Wang54feabe2015-04-15 23:38:26 -07001121 fs.ctx, cancel = context.WithDeadline(fs.ctx, req.Deadline.Time)
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001122 } else {
Todd Wang54feabe2015-04-15 23:38:26 -07001123 fs.ctx, cancel = context.WithCancel(fs.ctx)
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001124 }
Todd Wang54feabe2015-04-15 23:38:26 -07001125 fs.flow.SetDeadline(fs.ctx.Done())
Todd Wang5739dda2014-11-16 22:44:02 -08001126 go fs.cancelContextOnClose(cancel)
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001127
Todd Wang5739dda2014-11-16 22:44:02 -08001128 // Initialize security: blessings, discharges, etc.
Todd Wang9548d852015-02-10 16:15:59 -08001129 if err := fs.initSecurity(req); err != nil {
Suharsh Sivakumarc095fc22015-06-29 16:00:18 -07001130 fs.drainDecoderArgs(int(req.NumPosArgs))
Todd Wang9548d852015-02-10 16:15:59 -08001131 return nil, err
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001132 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001133 // Lookup the invoker.
Matt Rosencrantz311378b2015-03-25 15:26:12 -07001134 invoker, auth, err := fs.lookup(fs.suffix, fs.method)
Todd Wangebb3b012015-02-09 21:59:05 -08001135 if err != nil {
Suharsh Sivakumarc095fc22015-06-29 16:00:18 -07001136 fs.drainDecoderArgs(int(req.NumPosArgs))
Todd Wang9548d852015-02-10 16:15:59 -08001137 return nil, err
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001138 }
Matt Rosencrantz311378b2015-03-25 15:26:12 -07001139
1140 // Note that we strip the reserved prefix when calling the invoker so
1141 // that __Glob will call Glob. Note that we've already assigned a
1142 // special invoker so that we never call the wrong method by mistake.
1143 strippedMethod := naming.StripReserved(fs.method)
1144
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001145 // Prepare invoker and decode args.
1146 numArgs := int(req.NumPosArgs)
Cosmos Nicolaou5a3125a2015-07-10 11:19:20 -07001147 argptrs, tags, err := invoker.Prepare(fs.ctx, strippedMethod, numArgs)
Asim Shankar0cad0832014-11-04 01:27:38 -08001148 fs.tags = tags
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001149 if err != nil {
Suharsh Sivakumarc095fc22015-06-29 16:00:18 -07001150 fs.drainDecoderArgs(numArgs)
Todd Wang9548d852015-02-10 16:15:59 -08001151 return nil, err
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001152 }
Todd Wang9548d852015-02-10 16:15:59 -08001153 if called, want := req.NumPosArgs, uint64(len(argptrs)); called != want {
Suharsh Sivakumarc095fc22015-06-29 16:00:18 -07001154 fs.drainDecoderArgs(numArgs)
1155 return nil, newErrBadNumInputArgs(fs.ctx, fs.suffix, fs.method, called, want)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001156 }
1157 for ix, argptr := range argptrs {
1158 if err := fs.dec.Decode(argptr); err != nil {
Todd Wang54feabe2015-04-15 23:38:26 -07001159 return nil, newErrBadInputArg(fs.ctx, fs.suffix, fs.method, uint64(ix), err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001160 }
1161 }
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001162
Todd Wang5739dda2014-11-16 22:44:02 -08001163 // Check application's authorization policy.
Todd Wang4264e4b2015-04-16 22:43:40 -07001164 if err := authorize(fs.ctx, fs, auth); err != nil {
Todd Wang9548d852015-02-10 16:15:59 -08001165 return nil, err
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001166 }
Matt Rosencrantzbf0d9d92015-04-08 12:43:14 -07001167
Todd Wang5739dda2014-11-16 22:44:02 -08001168 // Invoke the method.
Todd Wang54feabe2015-04-15 23:38:26 -07001169 results, err := invoker.Invoke(fs.ctx, fs, strippedMethod, argptrs)
Robin Thellendb16d7162014-11-07 13:47:26 -08001170 fs.server.stats.record(fs.method, time.Since(fs.starttime))
Todd Wang9548d852015-02-10 16:15:59 -08001171 return results, err
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001172}
1173
Suharsh Sivakumarc095fc22015-06-29 16:00:18 -07001174// drainDecoderArgs drains the next n arguments encoded onto the flows decoder.
1175// This is needed to ensure that the client is able to encode all of its args
1176// before the server closes its flow. This guarantees that the client will
1177// consistently get the server's error response.
1178// TODO(suharshs): Figure out a better way to solve this race condition without
1179// unnecessarily reading all arguments.
1180func (fs *flowServer) drainDecoderArgs(n int) error {
1181 for i := 0; i < n; i++ {
1182 if err := fs.dec.Ignore(); err != nil {
1183 return err
1184 }
1185 }
1186 return nil
1187}
1188
Todd Wang5739dda2014-11-16 22:44:02 -08001189func (fs *flowServer) cancelContextOnClose(cancel context.CancelFunc) {
1190 // Ensure that the context gets cancelled if the flow is closed
1191 // due to a network error, or client cancellation.
1192 select {
1193 case <-fs.flow.Closed():
1194 // Here we remove the contexts channel as a deadline to the flow.
1195 // We do this to ensure clients get a consistent error when they read/write
1196 // after the flow is closed. Since the flow is already closed, it doesn't
1197 // matter that the context is also cancelled.
1198 fs.flow.SetDeadline(nil)
1199 cancel()
Todd Wang54feabe2015-04-15 23:38:26 -07001200 case <-fs.ctx.Done():
Robin Thellendc26c32e2014-10-06 17:44:04 -07001201 }
Todd Wang5739dda2014-11-16 22:44:02 -08001202}
1203
1204// lookup returns the invoker and authorizer responsible for serving the given
1205// name and method. The suffix is stripped of any leading slashes. If it begins
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001206// with rpc.DebugKeyword, we use the internal debug dispatcher to look up the
Todd Wang5739dda2014-11-16 22:44:02 -08001207// invoker. Otherwise, and we use the server's dispatcher. The suffix and method
1208// value may be modified to match the actual suffix and method to use.
Matt Rosencrantz311378b2015-03-25 15:26:12 -07001209func (fs *flowServer) lookup(suffix string, method string) (rpc.Invoker, security.Authorizer, error) {
1210 if naming.IsReserved(method) {
Asim Shankar149b4972015-04-23 13:29:58 -07001211 return reservedInvoker(fs.disp, fs.server.dispReserved), security.AllowEveryone(), nil
Todd Wang5739dda2014-11-16 22:44:02 -08001212 }
1213 disp := fs.disp
1214 if naming.IsReserved(suffix) {
1215 disp = fs.server.dispReserved
Ali Ghassemibac34032015-04-30 18:27:57 -07001216 } else if fs.server.isLeaf && suffix != "" {
1217 innerErr := verror.New(errUnexpectedSuffix, fs.ctx, suffix)
1218 return nil, nil, verror.New(verror.ErrUnknownSuffix, fs.ctx, suffix, innerErr)
Robin Thellendd24f0842014-09-23 10:27:29 -07001219 }
1220 if disp != nil {
Cosmos Nicolaou5a3125a2015-07-10 11:19:20 -07001221 obj, auth, err := disp.Lookup(fs.ctx, suffix)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001222 switch {
1223 case err != nil:
Todd Wang9548d852015-02-10 16:15:59 -08001224 return nil, nil, err
Todd Wang5739dda2014-11-16 22:44:02 -08001225 case obj != nil:
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08001226 invoker, err := objectToInvoker(obj)
1227 if err != nil {
Todd Wang54feabe2015-04-15 23:38:26 -07001228 return nil, nil, verror.New(verror.ErrInternal, fs.ctx, "invalid received object", err)
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08001229 }
1230 return invoker, auth, nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001231 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001232 }
Todd Wang54feabe2015-04-15 23:38:26 -07001233 return nil, nil, verror.New(verror.ErrUnknownSuffix, fs.ctx, suffix)
Todd Wang5739dda2014-11-16 22:44:02 -08001234}
1235
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001236func objectToInvoker(obj interface{}) (rpc.Invoker, error) {
Todd Wang5739dda2014-11-16 22:44:02 -08001237 if obj == nil {
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08001238 return nil, errors.New("nil object")
Todd Wang5739dda2014-11-16 22:44:02 -08001239 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001240 if invoker, ok := obj.(rpc.Invoker); ok {
Bogdan Caprita9592d9f2015-01-08 22:15:16 -08001241 return invoker, nil
Todd Wang5739dda2014-11-16 22:44:02 -08001242 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001243 return rpc.ReflectInvoker(obj)
Todd Wang5739dda2014-11-16 22:44:02 -08001244}
1245
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001246func (fs *flowServer) initSecurity(req *rpc.Request) error {
Ankurb905dae2015-03-04 12:38:20 -08001247 // LocalPrincipal is nil which means we are operating under
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -07001248 // SecurityNone.
Todd Wang54feabe2015-04-15 23:38:26 -07001249 if fs.LocalPrincipal() == nil {
Ankurb905dae2015-03-04 12:38:20 -08001250 return nil
1251 }
1252
Todd Wang5739dda2014-11-16 22:44:02 -08001253 // If additional credentials are provided, make them available in the context
Todd Wang5739dda2014-11-16 22:44:02 -08001254 // Detect unusable blessings now, rather then discovering they are unusable on
1255 // first use.
1256 //
1257 // TODO(ashankar,ataly): Potential confused deputy attack: The client provides
1258 // the server's identity as the blessing. Figure out what we want to do about
1259 // this - should servers be able to assume that a blessing is something that
1260 // does not have the authorizations that the server's own identity has?
Todd Wang54feabe2015-04-15 23:38:26 -07001261 if got, want := req.GrantedBlessings.PublicKey(), fs.LocalPrincipal().PublicKey(); got != nil && !reflect.DeepEqual(got, want) {
1262 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 -08001263 }
Asim Shankarb07ec692015-02-27 23:40:44 -08001264 fs.grantedBlessings = req.GrantedBlessings
Ankurb905dae2015-03-04 12:38:20 -08001265
Asim Shankarb07ec692015-02-27 23:40:44 -08001266 var err error
1267 if fs.clientBlessings, err = serverDecodeBlessings(fs.flow.VCDataCache(), req.Blessings, fs.server.stats); err != nil {
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001268 // When the server can't access the blessings cache, the client is not following
1269 // protocol, so the server closes the VCs corresponding to the client endpoint.
1270 // TODO(suharshs,toddw): Figure out a way to only shutdown the current VC, instead
1271 // of all VCs connected to the RemoteEndpoint.
1272 fs.server.streamMgr.ShutdownEndpoint(fs.RemoteEndpoint())
Todd Wang54feabe2015-04-15 23:38:26 -07001273 return verror.New(verror.ErrBadProtocol, fs.ctx, newErrBadBlessingsCache(fs.ctx, err))
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001274 }
Ankurb905dae2015-03-04 12:38:20 -08001275 // Verify that the blessings sent by the client in the request have the same public
1276 // key as those sent by the client during VC establishment.
1277 if got, want := fs.clientBlessings.PublicKey(), fs.flow.RemoteBlessings().PublicKey(); got != nil && !reflect.DeepEqual(got, want) {
Todd Wang54feabe2015-04-15 23:38:26 -07001278 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 -08001279 }
Asim Shankar2bf7b1e2015-02-27 00:45:12 -08001280 fs.ackBlessings = true
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001281
Asim Shankar3ad0b8a2015-02-25 00:37:21 -08001282 for _, d := range req.Discharges {
Asim Shankar08642822015-03-02 21:21:09 -08001283 fs.discharges[d.ID()] = d
Todd Wang5739dda2014-11-16 22:44:02 -08001284 }
1285 return nil
Robin Thellendc26c32e2014-10-06 17:44:04 -07001286}
1287
Todd Wang4264e4b2015-04-16 22:43:40 -07001288func authorize(ctx *context.T, call security.Call, auth security.Authorizer) error {
Matt Rosencrantz9dce9b22015-03-02 10:48:37 -08001289 if call.LocalPrincipal() == nil {
Todd Wang5739dda2014-11-16 22:44:02 -08001290 // LocalPrincipal is nil means that the server wanted to avoid
1291 // authentication, and thus wanted to skip authorization as well.
1292 return nil
1293 }
Asim Shankar8f05c222014-10-06 22:08:19 -07001294 if auth == nil {
Asim Shankare4a8c092015-04-01 18:43:39 -07001295 auth = security.DefaultAuthorizer()
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001296 }
Todd Wang4264e4b2015-04-16 22:43:40 -07001297 if err := auth.Authorize(ctx, call); err != nil {
Matt Rosencrantz250558f2015-03-17 11:37:31 -07001298 return verror.New(verror.ErrNoAccess, ctx, newErrBadAuth(ctx, call.Suffix(), call.Method(), err))
Asim Shankara5457f02014-10-24 23:23:07 -07001299 }
1300 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001301}
1302
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001303// Send implements the rpc.Stream method.
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001304func (fs *flowServer) Send(item interface{}) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -07001305 defer apilog.LogCallf(nil, "item=")(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001306 // The empty response header indicates what follows is a streaming result.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001307 if err := fs.enc.Encode(rpc.Response{}); err != nil {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001308 return err
1309 }
1310 return fs.enc.Encode(item)
1311}
1312
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001313// Recv implements the rpc.Stream method.
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001314func (fs *flowServer) Recv(itemptr interface{}) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -07001315 defer apilog.LogCallf(nil, "itemptr=")(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001316 var req rpc.Request
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001317 if err := fs.dec.Decode(&req); err != nil {
1318 return err
1319 }
1320 if req.EndStreamArgs {
1321 fs.endStreamArgs = true
1322 return io.EOF
1323 }
1324 return fs.dec.Decode(itemptr)
1325}
1326
Todd Wang54feabe2015-04-15 23:38:26 -07001327// Implementations of rpc.ServerCall and security.Call methods.
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001328
Todd Wang54feabe2015-04-15 23:38:26 -07001329func (fs *flowServer) Security() security.Call {
1330 //nologcall
1331 return fs
1332}
Ankuredd74ee2015-03-04 16:38:45 -08001333func (fs *flowServer) LocalDischarges() map[string]security.Discharge {
1334 //nologcall
1335 return fs.flow.LocalDischarges()
1336}
Asim Shankar2519cc12014-11-10 21:16:53 -08001337func (fs *flowServer) RemoteDischarges() map[string]security.Discharge {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001338 //nologcall
1339 return fs.discharges
1340}
Matt Rosencrantz98d6d7c2015-09-04 12:34:08 -07001341func (fs *flowServer) Server() rpc.Server {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001342 //nologcall
1343 return fs.server
1344}
Asim Shankar0cad0832014-11-04 01:27:38 -08001345func (fs *flowServer) Timestamp() time.Time {
1346 //nologcall
1347 return fs.starttime
1348}
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001349func (fs *flowServer) Method() string {
1350 //nologcall
1351 return fs.method
1352}
Todd Wangb31da592015-02-20 12:50:39 -08001353func (fs *flowServer) MethodTags() []*vdl.Value {
Asim Shankar0cad0832014-11-04 01:27:38 -08001354 //nologcall
1355 return fs.tags
1356}
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001357func (fs *flowServer) Suffix() string {
1358 //nologcall
1359 return fs.suffix
1360}
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001361func (fs *flowServer) LocalPrincipal() security.Principal {
1362 //nologcall
Asim Shankar8f05c222014-10-06 22:08:19 -07001363 return fs.flow.LocalPrincipal()
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001364}
1365func (fs *flowServer) LocalBlessings() security.Blessings {
1366 //nologcall
Asim Shankar8f05c222014-10-06 22:08:19 -07001367 return fs.flow.LocalBlessings()
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001368}
1369func (fs *flowServer) RemoteBlessings() security.Blessings {
1370 //nologcall
Asim Shankar2bf7b1e2015-02-27 00:45:12 -08001371 if !fs.clientBlessings.IsZero() {
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001372 return fs.clientBlessings
1373 }
Asim Shankar8f05c222014-10-06 22:08:19 -07001374 return fs.flow.RemoteBlessings()
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001375}
Suharsh Sivakumar380bf342015-02-27 15:38:27 -08001376func (fs *flowServer) GrantedBlessings() security.Blessings {
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001377 //nologcall
Suharsh Sivakumar380bf342015-02-27 15:38:27 -08001378 return fs.grantedBlessings
Mehrdad Afsharicd9852b2014-09-26 11:07:35 -07001379}
1380func (fs *flowServer) LocalEndpoint() naming.Endpoint {
1381 //nologcall
1382 return fs.flow.LocalEndpoint()
1383}
1384func (fs *flowServer) RemoteEndpoint() naming.Endpoint {
1385 //nologcall
1386 return fs.flow.RemoteEndpoint()
1387}
Asim Shankar99b18a72015-04-25 23:19:28 -07001388
1389type proxyAuth struct {
1390 s *server
1391}
1392
1393func (a proxyAuth) RPCStreamListenerOpt() {}
1394
1395func (a proxyAuth) Login(proxy stream.Flow) (security.Blessings, []security.Discharge, error) {
Asim Shankar6b1c8b02015-04-26 22:09:45 -07001396 var (
1397 principal = a.s.principal
1398 dc = a.s.dc
1399 ctx = a.s.ctx
1400 )
1401 if principal == nil {
1402 return security.Blessings{}, nil, nil
1403 }
1404 proxyNames, _ := security.RemoteBlessingNames(ctx, security.NewCall(&security.CallParams{
1405 LocalPrincipal: principal,
1406 RemoteBlessings: proxy.RemoteBlessings(),
1407 RemoteDischarges: proxy.RemoteDischarges(),
1408 RemoteEndpoint: proxy.RemoteEndpoint(),
1409 LocalEndpoint: proxy.LocalEndpoint(),
1410 }))
1411 blessings := principal.BlessingStore().ForPeer(proxyNames...)
1412 tpc := blessings.ThirdPartyCaveats()
1413 if len(tpc) == 0 {
1414 return blessings, nil, nil
1415 }
1416 // Set DischargeImpetus.Server = proxyNames.
1417 // See https://v.io/i/392
1418 discharges := dc.PrepareDischarges(ctx, tpc, security.DischargeImpetus{})
1419 return blessings, discharges, nil
Asim Shankar99b18a72015-04-25 23:19:28 -07001420}
1421
1422var _ manager.ProxyAuthenticator = proxyAuth{}