package pickupclient
import (
"errors"
"fmt"
"net"
"os"
"strconv"
)
// hasPeerCheck says this platform can tell which process is at the other
// end of a loopback connection; --fossil with a login needs it.
const hasPeerCheck = true
// peerOwnedBy says whether the connection from src to dst is held open by
// process pid: the socket's inode from /proc/net/tcp is looked for among
// the descriptors of /proc/PID/fd. It fails closed: an error says why the
// check could not be made or why the connection is another process's.
func peerOwnedBy(pid int, src, dst *net.TCPAddr) error {
tcp, err := os.ReadFile("/proc/net/tcp")
if err != nil {
return fmt.Errorf("could not tell which process connected (/proc/net/tcp: %v)", err)
}
inode, ok := inodeOfConn(string(tcp), src, dst)
if !ok {
return errors.New("could not tell which process connected (the connection is not in /proc/net/tcp)")
}
dir := "/proc/" + strconv.Itoa(pid) + "/fd"
ents, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("could not tell which process connected (%v)", err)
}
want := "socket:[" + inode + "]"
for _, e := range ents {
if l, err := os.Readlink(dir + "/" + e.Name()); err == nil && l == want {
return nil
}
}
return errors.New("the connection is not from the fossil this client started")
}