-
Notifications
You must be signed in to change notification settings - Fork 0
/
restartable.go
341 lines (293 loc) · 7.65 KB
/
restartable.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//go:build linux
package main
import (
"bytes"
"fmt"
"golang.org/x/sys/unix"
"log"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
)
import flag "github.com/spf13/pflag"
type proc struct {
command string
deleted []string
ppid string
uid int
service string
}
const version string = "2.2.2"
var usernames map[int]string
var opts struct {
proc string
short int
user bool
verbose bool
version bool
}
var (
regexDeleted = regexp.MustCompile(`/.* \(deleted\)$`)
regexIgnored = regexp.MustCompile(`[^/]*/(dev|memfd:|run| )`)
regexExecMap = regexp.MustCompile(`^[0-9a-f]+-[0-9a-f]+ r(w|-)x`)
regexName = regexp.MustCompile(`(?m)^Name:\t(.*)$`)
regexPpid = regexp.MustCompile(`(?m)^PPid:\t(.*)$`)
regexRuid = regexp.MustCompile(`(?m)^Uid:\t([0-9]+)\t`)
regexSystemService = regexp.MustCompile(`\d+:[^:]*:/system\.slice/(?:.*/)?(.*)\.service$`)
regexUserService = regexp.MustCompile(`\d+:[^:]*:/user\.slice/(?:.*/)?(.*)\.service$`)
)
// Quote special characters
func quoteString(str string) string {
if len(str) > 0 {
str = strconv.Quote(str)
return str[1 : len(str)-1]
}
return ""
}
func readFile(dirFd int, path string) ([]byte, error) {
fd, err := unix.Openat(dirFd, path, unix.O_NOFOLLOW, unix.O_RDONLY)
if err != nil {
return []byte{}, err
}
defer unix.Close(fd)
data := make([]byte, 0, 1024)
for {
if len(data) >= cap(data) {
d := append(data[:cap(data)], 0)
data = d[:len(data)]
}
if n, err := unix.Read(fd, data[len(data):cap(data)]); n > 0 {
data = data[:len(data)+n]
} else {
return data, err
}
}
}
func readLink(dirFd int, path string) (string, error) {
for size := unix.PathMax; ; size *= 2 {
data := make([]byte, unix.PathMax)
if n, err := unix.Readlinkat(dirFd, path, data); err != nil {
return "", err
} else if n != size {
return string(data[:n]), err
}
}
}
func getUser(uid int) (username string) {
if _, ok := usernames[uid]; ok {
username = usernames[uid]
} else {
if info, err := user.LookupId(strconv.Itoa(uid)); err != nil {
username = "-"
} else {
username = info.Username
}
usernames[uid] = username
}
return username
}
func getDeleted(dirFd int, pid string) (files []string) {
maps, err := readFile(dirFd, "maps")
if err != nil {
return
}
for _, str := range strings.Split(string(maps), "\n") {
file := regexDeleted.FindString(str)
if file != "" && regexExecMap.MatchString(str) && !regexIgnored.MatchString(str) {
files = append(files, quoteString(strings.TrimSuffix(file, " (deleted)")))
}
}
sort.Strings(files)
return
}
func getService(dirFd int, pid string) (service string) {
cgroup, err := readFile(dirFd, "cgroup")
if err != nil {
return "-"
}
var match []string
if opts.user {
match = regexUserService.FindStringSubmatch(strings.TrimSpace(string(cgroup)))
} else {
match = regexSystemService.FindStringSubmatch(strings.TrimSpace(string(cgroup)))
}
if len(match) > 1 {
return match[1]
}
return "-"
}
func getInfo(pidInt int) (info *proc, err error) {
pid := strconv.Itoa(pidInt)
dirFd, err := unix.Open(filepath.Join(opts.proc, pid), unix.O_DIRECTORY|unix.O_PATH|unix.O_NOATIME, unix.O_RDONLY)
if err != nil {
return nil, err
}
defer unix.Close(dirFd)
files := getDeleted(dirFd, pid)
if len(files) == 0 {
return
}
data, err := readFile(dirFd, "status")
if err != nil {
return nil, err
}
status := string(data)
uid, _ := strconv.Atoi(regexRuid.FindStringSubmatch(status)[1])
data, err = readFile(dirFd, "cmdline")
if err != nil {
return nil, err
}
cmdline := []string{}
if bytes.HasSuffix(data, []byte("\x00")) {
cmdline = strings.Split(string(data), "\x00")
cmdline = cmdline[:len(cmdline)-1]
} else {
cmdline = append(cmdline, string(data))
}
command := ""
if opts.verbose {
// Use full path
// cmdline is empty if zombie, but zombies have void proc.maps
exe, err := readLink(dirFd, "exe")
if err != nil {
exe = ""
}
exe = strings.TrimSuffix(exe, " (deleted)")
if len(cmdline) > 0 && !strings.HasPrefix(cmdline[0], "/") && exe != "" && filepath.Base(cmdline[0]) == filepath.Base(exe) {
command = exe + " " + strings.Join(cmdline[1:], " ")
} else {
command = strings.Join(cmdline, " ")
}
} else {
command = regexName.FindStringSubmatch(status)[1]
// The command may be truncated to 15 chars in /proc/<pid>/status
// Also, kernel usermode helpers use "none"
if len(cmdline) > 0 && cmdline[0] != "" && (len(command) == 15 || command == "none") {
command = cmdline[0]
}
if strings.HasPrefix(command, "/") {
command = filepath.Base(command)
} else {
command = strings.Split(command, " ")[0]
}
}
return &proc{
command: quoteString(command),
deleted: files,
ppid: regexPpid.FindStringSubmatch(status)[1],
uid: uid,
service: getService(dirFd, pid),
}, nil
}
func printInfoAll(dir string) error {
entries, err := os.ReadDir(dir)
if err != nil {
return err
}
var pids []int
for _, entry := range entries {
if pid, err := strconv.Atoi(entry.Name()); err == nil {
pids = append(pids, pid)
}
}
sort.Ints(pids)
services := make(map[string]bool)
if opts.short < 3 {
fmt.Printf("%s\t%s\t%s\t%-20s\t%20s\t%s\n", "PID", "PPID", "UID", "User", "Service", "Command")
}
channel := make(map[int]chan *proc, len(pids))
for _, pid := range pids {
channel[pid] = make(chan *proc)
}
go func() {
for _, pid := range pids {
go func(pid int) {
if info, err := getInfo(pid); info != nil && err == nil {
channel[pid] <- info
} else {
if err != nil {
log.Print(err)
}
close(channel[pid])
}
}(pid)
}
}()
for _, pid := range pids {
proc := <-channel[pid]
if proc == nil {
continue
}
//close(channel[pid])
if opts.short < 3 {
fmt.Printf("%d\t%s\t%d\t%-20s\t%20s\t%s\n", pid, proc.ppid, proc.uid, getUser(proc.uid), proc.service, proc.command)
} else if proc.service != "-" {
services[proc.service] = true
}
if opts.short == 0 {
for _, deleted := range proc.deleted {
fmt.Printf("\t%s\n", deleted)
}
}
}
if opts.short == 3 && len(services) > 0 {
// Print services in sorted mode
ss := make([]string, 0, len(services))
for s := range services {
ss = append(ss, s)
}
sort.Strings(ss)
for _, service := range ss {
fmt.Println(service)
}
}
return nil
}
func getCommit() string {
var commit, dirty string
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
switch {
case setting.Key == "vcs.revision":
commit = setting.Value
case setting.Key == "vcs.modified":
dirty = "-dirty"
}
}
}
return commit + dirty
}
func init() {
log.SetPrefix("ERROR: ")
log.SetFlags(0)
flag.StringVarP(&opts.proc, "proc", "P", "/proc", "proc directory")
flag.CountVarP(&opts.short, "short", "s", "Create a short table not showing the deleted files. Given twice, show only processes which are associated with a system service. Given three times, list the associated system service names only.")
flag.BoolVarP(&opts.user, "user", "u", false, "show user services instead of system services")
flag.BoolVarP(&opts.verbose, "verbose", "v", false, "verbose output")
flag.BoolVarP(&opts.version, "version", "V", false, "show version and exit")
flag.Parse()
if opts.version {
fmt.Printf("v%s %v %s/%s %s\n", version, runtime.Version(), runtime.GOOS, runtime.GOARCH, getCommit())
os.Exit(0)
}
if flag.NArg() > 0 {
flag.Usage()
os.Exit(1)
}
}
func main() {
usernames = make(map[int]string)
if os.Geteuid() != 0 {
fmt.Fprintln(os.Stderr, "WARN: Run this program as root")
}
if err := printInfoAll(opts.proc); err != nil {
log.Fatal(err)
}
os.Exit(0)
}