| 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 |
//go:build !windows |
| 16 |
|
| 17 |
// Package activation implements primitives for systemd socket activation. |
| 18 |
package activation |
| 19 |
|
| 20 |
import ( |
| 21 |
"os" |
| 22 |
"strconv" |
| 23 |
"strings" |
| 24 |
"syscall" |
| 25 |
) |
| 26 |
|
| 27 |
const ( |
| 28 |
// listenFdsStart corresponds to `SD_LISTEN_FDS_START`. |
| 29 |
listenFdsStart = 3 |
| 30 |
) |
| 31 |
|
| 32 |
// Files returns a slice containing a `os.File` object for each |
| 33 |
// file descriptor passed to this process via systemd fd-passing protocol. |
| 34 |
// |
| 35 |
// The order of the file descriptors is preserved in the returned slice. |
| 36 |
// `unsetEnv` is typically set to `true` in order to avoid clashes in |
| 37 |
// fd usage and to avoid leaking environment flags to child processes. |
| 38 |
func Files(unsetEnv bool) []*os.File { |
| 39 |
if unsetEnv { |
| 40 |
defer func() { |
| 41 |
// Unsetenv implementation for unix never returns an error. |
| 42 |
_ = os.Unsetenv("LISTEN_PID") |
| 43 |
_ = os.Unsetenv("LISTEN_FDS") |
| 44 |
_ = os.Unsetenv("LISTEN_FDNAMES") |
| 45 |
}() |
| 46 |
} |
| 47 |
|
| 48 |
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID")) |
| 49 |
if err != nil || pid != os.Getpid() { |
| 50 |
return nil |
| 51 |
} |
| 52 |
|
| 53 |
nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS")) |
| 54 |
if err != nil || nfds == 0 { |
| 55 |
return nil |
| 56 |
} |
| 57 |
|
| 58 |
names := strings.Split(os.Getenv("LISTEN_FDNAMES"), ":") |
| 59 |
|
| 60 |
files := make([]*os.File, 0, nfds) |
| 61 |
for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ { |
| 62 |
syscall.CloseOnExec(fd) |
| 63 |
name := "LISTEN_FD_" + strconv.Itoa(fd) |
| 64 |
offset := fd - listenFdsStart |
| 65 |
if offset < len(names) && len(names[offset]) > 0 { |
| 66 |
name = names[offset] |
| 67 |
} |
| 68 |
files = append(files, os.NewFile(uintptr(fd), name)) |
| 69 |
} |
| 70 |
|
| 71 |
return files |
| 72 |
} |