Skip to content
quarry Artifact [666986503f]
Login

Artifact [666986503f]

Artifact 666986503fb5c58d970dbc192ba9858151663f80e5d6db53ad6505009683a584:


package pickupclient

import (
	"context"
	"errors"
	"fmt"
	"net"
	"os/exec"
	"strconv"
	"strings"
	"time"
)

// 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, by asking lsof for the process's TCP sockets. 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 {
	// By absolute path: a PATH can name another program.
	const lsof = "/usr/sbin/lsof"
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	out, err := exec.CommandContext(ctx, lsof, "-a", "-p", strconv.Itoa(pid), "-iTCP", "-n", "-P", "-F", "n").Output()
	var ee *exec.ExitError
	if err != nil && !errors.As(err, &ee) {
		return fmt.Errorf("could not tell which process connected (lsof: %v)", err)
	}
	// lsof exits 1 when the process has no such sockets: an answer.
	want := fmt.Sprintf("n%s:%d->%s:%d", src.IP, src.Port, dst.IP, dst.Port)
	for _, line := range strings.Split(string(out), "\n") {
		if line == want {
			return nil
		}
	}
	return errors.New("the connection is not from the fossil this client started")
}