Debian Codegraph @

vendor/github.com/coreos/go-systemd/activation/files.go

raw
1 // Copyright 2015 CoreOS, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package activation implements primitives for systemd socket activation.
16 package activation
17
18 import (
19 "os"
20 "strconv"
21 "strings"
22 "syscall"
23 )
24
25 const (
26 // listenFdsStart corresponds to `SD_LISTEN_FDS_START`.
27 listenFdsStart = 3
28 )
29
30 // Files returns a slice containing a `os.File` object for each
31 // file descriptor passed to this process via systemd fd-passing protocol.
32 //
33 // The order of the file descriptors is preserved in the returned slice.
34 // `unsetEnv` is typically set to `true` in order to avoid clashes in
35 // fd usage and to avoid leaking environment flags to child processes.
36 func Files(unsetEnv bool) []*os.File {
37 if unsetEnv {
38 defer os.Unsetenv("LISTEN_PID")
39 defer os.Unsetenv("LISTEN_FDS")
40 defer os.Unsetenv("LISTEN_FDNAMES")
41 }
42
43 pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
44 if err != nil || pid != os.Getpid() {
45 return nil
46 }
47
48 nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
49 if err != nil || nfds == 0 {
50 return nil
51 }
52
53 names := strings.Split(os.Getenv("LISTEN_FDNAMES"), ":")
54
55 files := make([]*os.File, 0, nfds)
56 for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
57 syscall.CloseOnExec(fd)
58 name := "LISTEN_FD_" + strconv.Itoa(fd)
59 offset := fd - listenFdsStart
60 if offset < len(names) && len(names[offset]) > 0 {
61 name = names[offset]
62 }
63 files = append(files, os.NewFile(uintptr(fd), name))
64 }
65
66 return files
67 }