Skip to content
quarry Artifact [26131d0f68]
Login

Artifact [26131d0f68]

Artifact 26131d0f680af837ca3ad75d908e28b20f48f77b0ac3187694744178cc2e2cc8:


package pickupclient

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

// 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 {
	lsof, err := exec.LookPath("lsof")
	if err != nil {
		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")
}