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.
16package activation
17
18import (
19	"os"
20	"strconv"
21	"syscall"
22)
23
24// based on: https://gist.github.com/alberts/4640792
25const (
26	listenFdsStart = 3
27)
28
29func Files(unsetEnv bool) []*os.File {
30	if unsetEnv {
31		defer os.Unsetenv("LISTEN_PID")
32		defer os.Unsetenv("LISTEN_FDS")
33	}
34
35	pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
36	if err != nil || pid != os.Getpid() {
37		return nil
38	}
39
40	nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
41	if err != nil || nfds == 0 {
42		return nil
43	}
44
45	files := make([]*os.File, 0, nfds)
46	for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
47		syscall.CloseOnExec(fd)
48		files = append(files, os.NewFile(uintptr(fd), "LISTEN_FD_"+strconv.Itoa(fd)))
49	}
50
51	return files
52}
53