This repository has been archived by the owner on Feb 24, 2020. It is now read-only.
/
echo-socket-activated.go
123 lines (104 loc) · 2.29 KB
/
echo-socket-activated.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
// Copyright 2015 The rkt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"io"
"net"
"os"
"strconv"
"github.com/rkt/rkt/pkg/sys"
)
const (
SD_LISTEN_FDS_START = 3
)
func sdListenFDs(unsetEnvironment bool) (int, error) {
defer func() {
if unsetEnvironment {
os.Unsetenv("LISTEN_PID")
os.Unsetenv("LISTEN_FDS")
}
}()
e := os.Getenv("LISTEN_PID")
if e == "" {
return 0, nil
}
pid, err := strconv.Atoi(e)
if err != nil {
return -1, err
}
if os.Getpid() != pid {
return 0, nil
}
e = os.Getenv("LISTEN_FDS")
if e == "" {
return 0, nil
}
n, err := strconv.Atoi(e)
if err != nil {
return -1, err
}
for fd := SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; fd++ {
if err := sys.CloseOnExec(fd, true); err != nil {
return -1, err
}
}
return n, nil
}
func main() {
var fd uintptr
n, err := sdListenFDs(false)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting socket-activated FDs: %v\n", err)
os.Exit(254)
}
switch {
case n == 1:
fd = SD_LISTEN_FDS_START
case n > 1:
fmt.Fprintf(os.Stderr, "Too many file descriptors received.\n")
os.Exit(254)
default:
fmt.Fprintf(os.Stderr, "Not socket activated.\n")
os.Exit(254)
}
f := os.NewFile(fd, "")
defer f.Close()
l, err := net.FileListener(f)
if err != nil {
fmt.Fprintf(os.Stderr, "FileListener: %v.\n", err)
os.Exit(254)
}
conn, err := l.Accept()
if err != nil {
fmt.Fprintf(os.Stderr, "Accept: %v.\n", err)
os.Exit(254)
}
buf := make([]byte, 1024)
for {
nr, err := conn.Read(buf)
if err != nil {
if err != io.EOF {
fmt.Fprintf(os.Stderr, "Read: %v.\n", err)
os.Exit(254)
}
break
}
data := buf[0:nr]
if _, err := conn.Write(data); err != nil {
fmt.Fprintf(os.Stderr, "Write: %v.\n", err)
os.Exit(254)
}
}
}