Skip to content
quarry Artifact [c5b2ecf9c8]
Login

Artifact [c5b2ecf9c8]

Artifact c5b2ecf9c8fdd85353fb7d69b41c974a505477c034cf4f567e0b033dd822c42a:


package pickupclient

import (
	"errors"
	"fmt"
	"net"
	"os"
	"strconv"
)

// 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")
}