MCPcopy
hub / github.com/perkeep/perkeep / uidFromLsof

Function uidFromLsof

internal/netutil/ident.go:148–198  ·  view source on GitHub ↗
(lip net.IP, lport int, rip net.IP, rport int)

Source from the content-addressed store, hash-verified

146}
147
148func uidFromLsof(lip net.IP, lport int, rip net.IP, rport int) (uid int, err error) {
149 seek := fmt.Sprintf("%s:%d->%s:%d", maybeBrackets(lip), lport, maybeBrackets(rip), rport)
150 seekb := []byte(seek)
151 if _, err := exec.LookPath("lsof"); err != nil {
152 return 0, err
153 }
154
155 cmd := exec.Command("lsof",
156 "-b", // avoid system calls that could block
157 "-w", // and don't warn about cases where -b fails
158 "-n", // don't resolve network names
159 "-P", // don't resolve network ports,
160 // TODO(bradfitz): pass down the uid we care about, then do: ?
161 //"-a", // AND the following together:
162 // "-u", strconv.Itoa(uid) // just this uid
163 "-itcp") // we only care about TCP connections
164
165 stdout, err := cmd.StdoutPipe()
166 if err != nil {
167 return 0, err
168 }
169 if err := cmd.Start(); err != nil {
170 return 0, err
171 }
172
173 defer func() {
174 if werr := cmd.Wait(); werr != nil && err == nil {
175 err = werr
176 }
177 }()
178
179 br := bufio.NewReader(stdout)
180 for {
181 line, err := br.ReadSlice('\n')
182 if err == io.EOF {
183 return 0, ErrNotFound
184 }
185 if err != nil {
186 return 0, err
187 }
188 if !bytes.Contains(line, seekb) {
189 continue
190 }
191 // SystemUIS 276 bradfitz 15u IPv4 0xffffff801a7c74e0 0t0 TCP 127.0.0.1:56718->127.0.0.1:5204 (ESTABLISHED)
192 f := bytes.Fields(line)
193 if len(f) < 8 {
194 continue
195 }
196 return uidFromUsername(string(f[2]))
197 }
198}
199
200func uidFromSockstat(lip net.IP, lport int, rip net.IP, rport int) (uid int, err error) {
201 cmd := exec.Command("sockstat", "-Ptcp")

Callers 1

AddrPairUseridFunction · 0.85

Calls 6

maybeBracketsTypeAlias · 0.85
WaitMethod · 0.80
ContainsMethod · 0.80
LookPathMethod · 0.65
CommandMethod · 0.65
StartMethod · 0.65

Tested by

no test coverage detected