|
| 1 | +// Gets process environment by PID in Linux operating systems. |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "bufio" |
| 7 | + "bytes" |
| 8 | + "fmt" |
| 9 | + "os" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | +) |
| 13 | + |
| 14 | +func dropNullByte(data []byte) []byte { |
| 15 | + size := len(data) |
| 16 | + if size > 0 && data[size-1] == '\000' { |
| 17 | + return data[0 : size-1] |
| 18 | + } |
| 19 | + return data |
| 20 | +} |
| 21 | + |
| 22 | +func SplitProcEnviron(data []byte, atEOF bool) (advance int, token []byte, err error) { |
| 23 | + if atEOF { |
| 24 | + if len(data) == 0 { |
| 25 | + return 0, nil, nil |
| 26 | + } else { |
| 27 | + return len(data), dropNullByte(data), nil |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + if data[0] == '\000' { |
| 32 | + return 1, nil, nil |
| 33 | + } |
| 34 | + |
| 35 | + if i := bytes.IndexByte(data, '\000'); i > 0 { |
| 36 | + return i + 1, dropNullByte(data[0:i]), nil |
| 37 | + } |
| 38 | + |
| 39 | + return 0, nil, nil |
| 40 | +} |
| 41 | + |
| 42 | +func ProcessEnvProvider(filter string) (map[string]string, error) { |
| 43 | + vars := map[string]string{} |
| 44 | + |
| 45 | + // TODO(zomglings): For now, we expect the filter to contain the process PID but we will later |
| 46 | + // want to add other things, like whitelists or blacklists of environment variables to read. |
| 47 | + pid, pidErr := strconv.ParseUint(filter, 10, 64) |
| 48 | + if pidErr != nil { |
| 49 | + return vars, pidErr |
| 50 | + } |
| 51 | + filename := fmt.Sprintf("/proc/%d/environ", pid) |
| 52 | + |
| 53 | + ifp, fileErr := os.Open(filename) |
| 54 | + if fileErr != nil { |
| 55 | + return vars, fileErr |
| 56 | + } |
| 57 | + defer ifp.Close() |
| 58 | + |
| 59 | + scanner := bufio.NewScanner(ifp) |
| 60 | + scanner.Split(SplitProcEnviron) |
| 61 | + for scanner.Scan() { |
| 62 | + line := scanner.Text() |
| 63 | + components := strings.Split(line, "=") |
| 64 | + name := components[0] |
| 65 | + var value string |
| 66 | + if len(components) > 1 { |
| 67 | + value = strings.Join(components[1:], "=") |
| 68 | + } |
| 69 | + vars[name] = value |
| 70 | + } |
| 71 | + |
| 72 | + scanErr := scanner.Err() |
| 73 | + return vars, scanErr |
| 74 | +} |
| 75 | + |
| 76 | +func init() { |
| 77 | + helpString := "Provides the environment variables set for the process with the given pid." |
| 78 | + RegisterPlugin("proc", helpString, noop, ProcessEnvProvider) |
| 79 | +} |
0 commit comments