github.com/sagernet/sing-box@v1.9.0-rc.20/common/process/searcher.go (about)

     1  package process
     2  
     3  import (
     4  	"context"
     5  	"net/netip"
     6  	"os/user"
     7  
     8  	"github.com/sagernet/sing-box/log"
     9  	"github.com/sagernet/sing-tun"
    10  	E "github.com/sagernet/sing/common/exceptions"
    11  	F "github.com/sagernet/sing/common/format"
    12  )
    13  
    14  type Searcher interface {
    15  	FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error)
    16  }
    17  
    18  var ErrNotFound = E.New("process not found")
    19  
    20  type Config struct {
    21  	Logger         log.ContextLogger
    22  	PackageManager tun.PackageManager
    23  }
    24  
    25  type Info struct {
    26  	ProcessPath string
    27  	PackageName string
    28  	User        string
    29  	UserId      int32
    30  }
    31  
    32  func FindProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
    33  	info, err := searcher.FindProcessInfo(ctx, network, source, destination)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	if info.UserId != -1 {
    38  		osUser, _ := user.LookupId(F.ToString(info.UserId))
    39  		if osUser != nil {
    40  			info.User = osUser.Username
    41  		}
    42  	}
    43  	return info, nil
    44  }