forked from snapcore/snapd
/
session_agent.go
311 lines (274 loc) · 7.11 KB
/
session_agent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2019 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package agent
import (
"context"
"fmt"
"net"
"net/http"
"os"
"sync"
"syscall"
"time"
"github.com/godbus/dbus"
"github.com/gorilla/mux"
"gopkg.in/tomb.v2"
"github.com/snapcore/snapd/dbusutil"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/netutil"
"github.com/snapcore/snapd/osutil/sys"
"github.com/snapcore/snapd/systemd"
)
type SessionAgent struct {
Version string
bus *dbus.Conn
listener net.Listener
serve *http.Server
tomb tomb.Tomb
router *mux.Router
idle *idleTracker
IdleTimeout time.Duration
}
const sessionAgentBusName = "io.snapcraft.SessionAgent"
// A ResponseFunc handles one of the individual verbs for a method
type ResponseFunc func(*Command, *http.Request) Response
// A Command routes a request to an individual per-verb ResponseFunc
type Command struct {
Path string
GET ResponseFunc
PUT ResponseFunc
POST ResponseFunc
DELETE ResponseFunc
s *SessionAgent
}
func (c *Command) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var rspf ResponseFunc
var rsp = MethodNotAllowed("method %q not allowed", r.Method)
switch r.Method {
case "GET":
rspf = c.GET
case "PUT":
rspf = c.PUT
case "POST":
rspf = c.POST
case "DELETE":
rspf = c.DELETE
}
if rspf != nil {
rsp = rspf(c, r)
}
rsp.ServeHTTP(w, r)
}
type idleTracker struct {
mu sync.Mutex
active map[net.Conn]struct{}
lastActive time.Time
}
var sysGetsockoptUcred = syscall.GetsockoptUcred
func getUcred(conn net.Conn) (*syscall.Ucred, error) {
if uconn, ok := conn.(*net.UnixConn); ok {
f, err := uconn.File()
if err != nil {
return nil, err
}
defer f.Close()
return sysGetsockoptUcred(int(f.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
}
return nil, fmt.Errorf("expected a net.UnixConn, but got a %T", conn)
}
func (it *idleTracker) trackConn(conn net.Conn, state http.ConnState) {
// Perform peer credentials check
if state == http.StateNew {
ucred, err := getUcred(conn)
if err != nil {
logger.Noticef("Failed to retrieve peer credentials: %v", err)
conn.Close()
return
}
if ucred.Uid != 0 && ucred.Uid != uint32(sys.Geteuid()) {
logger.Noticef("Blocking request from user ID %v", ucred.Uid)
conn.Close()
return
}
}
it.mu.Lock()
defer it.mu.Unlock()
oldActive := len(it.active)
if state == http.StateNew || state == http.StateActive {
it.active[conn] = struct{}{}
} else {
delete(it.active, conn)
}
if len(it.active) == 0 && oldActive != 0 {
it.lastActive = time.Now()
}
}
// idleDuration returns the duration of time the server has been idle
func (it *idleTracker) idleDuration() time.Duration {
it.mu.Lock()
defer it.mu.Unlock()
if len(it.active) != 0 {
return 0
}
return time.Since(it.lastActive)
}
const (
defaultIdleTimeout = 30 * time.Second
shutdownTimeout = 5 * time.Second
)
type closeOnceListener struct {
net.Listener
idempotClose sync.Once
closeErr error
}
func (l *closeOnceListener) Close() error {
l.idempotClose.Do(func() {
l.closeErr = l.Listener.Close()
})
return l.closeErr
}
func (s *SessionAgent) Init() error {
// Set up D-Bus connection
if err := s.tryConnectSessionBus(); err != nil {
return err
}
// Set up REST API server
listenerMap, err := netutil.ActivationListeners()
if err != nil {
return err
}
agentSocket := fmt.Sprintf("%s/%d/snapd-session-agent.socket", dirs.XdgRuntimeDirBase, os.Getuid())
if l, err := netutil.GetListener(agentSocket, listenerMap); err != nil {
return fmt.Errorf("cannot listen on socket %s: %v", agentSocket, err)
} else {
s.listener = &closeOnceListener{Listener: l}
}
s.idle = &idleTracker{
active: make(map[net.Conn]struct{}),
lastActive: time.Now(),
}
s.IdleTimeout = defaultIdleTimeout
s.addRoutes()
s.serve = &http.Server{
Handler: s.router,
ConnState: s.idle.trackConn,
}
return nil
}
func (s *SessionAgent) tryConnectSessionBus() (err error) {
s.bus, err = dbusutil.SessionBusPrivate()
if err != nil {
// ssh sessions on Ubuntu 16.04 may have a user
// instance of systemd but no D-Bus session bus. So
// don't treat this as an error.
logger.Noticef("Could not connect to session bus: %v", err)
return nil
}
defer func() {
if err != nil {
s.bus.Close()
s.bus = nil
}
}()
reply, err := s.bus.RequestName(sessionAgentBusName, dbus.NameFlagDoNotQueue)
if err != nil {
return err
}
if reply != dbus.RequestNameReplyPrimaryOwner {
return fmt.Errorf("cannot obtain bus name %q: %v", sessionAgentBusName, reply)
}
return nil
}
func (s *SessionAgent) addRoutes() {
s.router = mux.NewRouter()
for _, c := range restApi {
c.s = s
s.router.Handle(c.Path, c).Name(c.Path)
}
s.router.NotFoundHandler = NotFound("not found")
}
func (s *SessionAgent) Start() {
s.tomb.Go(s.runServer)
s.tomb.Go(s.shutdownServerOnKill)
s.tomb.Go(s.exitOnIdle)
systemd.SdNotify("READY=1")
}
func (s *SessionAgent) runServer() error {
err := s.serve.Serve(s.listener)
if err == http.ErrServerClosed {
err = nil
}
if s.tomb.Err() == tomb.ErrStillAlive {
return err
}
return nil
}
func (s *SessionAgent) shutdownServerOnKill() error {
<-s.tomb.Dying()
systemd.SdNotify("STOPPING=1")
// closing the listener (but then it needs wrapping in
// closeOnceListener) before actually calling Shutdown, to
// workaround https://github.com/golang/go/issues/20239, we
// can in some cases (e.g. tests) end up calling Shutdown
// before runServer calls Serve and in go <1.11 this can be
// racy and the shutdown blocks.
// Historically We do something similar in the main daemon
// logic as well.
s.listener.Close()
s.bus.Close()
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
return s.serve.Shutdown(ctx)
}
func (s *SessionAgent) exitOnIdle() error {
timer := time.NewTimer(s.IdleTimeout)
Loop:
for {
select {
case <-s.tomb.Dying():
break Loop
case <-timer.C:
// Have we been idle
idleDuration := s.idle.idleDuration()
if idleDuration >= s.IdleTimeout {
s.tomb.Kill(nil)
break Loop
} else {
timer.Reset(s.IdleTimeout - idleDuration)
}
}
}
return nil
}
// Stop performs a graceful shutdown of the session agent and waits up to 5
// seconds for it to complete.
func (s *SessionAgent) Stop() error {
s.tomb.Kill(nil)
return s.tomb.Wait()
}
func (s *SessionAgent) Dying() <-chan struct{} {
return s.tomb.Dying()
}
func New() (*SessionAgent, error) {
agent := &SessionAgent{}
if err := agent.Init(); err != nil {
return nil, err
}
return agent, nil
}