winproc

package module
v0.0.0-...-99bc6c1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 29, 2023 License: MIT Imports: 18 Imported by: 0

README

winproc GoDoc

The winproc package provides access to windows process management APIs.

Documentation

Rendered for windows/amd64

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrClosed is returned when a process handle needed for an action has
	// already been closed.
	ErrClosed = errors.New("the process handle has been closed")

	// ErrProcessStillActive is returned when a process is still active and
	// has not exited yet.
	ErrProcessStillActive = errors.New("the process is still active")
)

Functions

func Watch

func Watch(ctx context.Context, interval time.Duration, chanSize int, options ...CollectionOption) <-chan ChangeSet

Watch polls the process tree on an interval until an error is encountered or the context is cancelled. It sends differences in the process list on the returned channel.

This function is experimental and may be changed in future revisions.

Types

type Change

type Change struct {
	Process Process
	Removed bool
}

Change describes a process that is being added or removed from a process list.

type ChangeSet

type ChangeSet struct {
	Changes []Change
	Time    time.Time
	Err     error
}

ChangeSet holds a set of changes to a process list.

type Collection

type Collection struct {
	Procs    []Process
	Excluded []bool // Excluded[i] corresponds to Procs[i]
}

Collection holds interim processing information while collecting processes.

type CollectionOption

type CollectionOption interface {
	Apply(*Collection)
}

A CollectionOption is capable of applying its settings to a collection.

type Collector

type Collector int

A Collector is a collection option that collects additional information about a process.

Information will only be collected for processes that have not been excluded by previous filtering options.

const (
	// CollectCommands is an option that enables collection of process
	// command line, path and argument information.
	CollectCommands Collector = 1 << iota

	// CollectSessions is an option that enables collection of process
	// session information.
	CollectSessions

	// CollectUsers is an option that enables collection of process
	// user information.
	CollectUsers

	// CollectTimes is an option that enables collection of process
	// time information.
	CollectTimes

	// CollectCriticality is an option that enables collection of process
	// criticality information.
	CollectCriticality
)

func (Collector) Apply

func (c Collector) Apply(col *Collection)

Apply applies the collector to the collection.

func (Collector) Contains

func (c Collector) Contains(b Collector) bool

Contains returns true if c contains b.

func (Collector) Merge

func (c Collector) Merge(next CollectionOption) (merged CollectionOption, ok bool)

Merge attempts to merge the collector with the next option. It returns true if successful.

type Exclude

type Exclude Filter

Exclude is an exclusion filter.

func (Exclude) Apply

func (exclude Exclude) Apply(col *Collection)

Apply applies the exclusion filter to the collection.

type Filter

type Filter func(Process) bool

A Filter returns true if it matches a process.

func ContainsName

func ContainsName(name string) Filter

ContainsName returns a filter that matches part of a process name.

func EqualsName

func EqualsName(name string) Filter

EqualsName returns a filter that matches a process name case-insensitively.

func MatchAll

func MatchAll(filters ...Filter) Filter

MatchAll returns true if all of the filters match the process.

MatchAll returns true if no filters are provided.

func MatchAny

func MatchAny(filters ...Filter) Filter

MatchAny returns true if any of the filters match the process.

MatchAny returns true if no filters are provided.

func MatchID

func MatchID(pid ID) Filter

MatchID returns a filter that matches a process ID.

func MatchName

func MatchName(matcher StringMatcher) Filter

MatchName returns a filter that matches a process name.

type ID

type ID uint32

ID is a 32-bit windows process identifier.

func (ID) String

func (id ID) String() string

String returns a string representation of the id.

type Include

type Include Filter

Include is an inclusion filter.

func (Include) Apply

func (include Include) Apply(col *Collection)

Apply applies the inclusion filter to the collection.

type MergableCollectionOption

type MergableCollectionOption interface {
	Merge(next CollectionOption) (merged CollectionOption, ok bool)
}

A MergableCollectionOption is capable of merging with the next option in the list. Some options implement this interface when bulk operations can be performed more efficiently.

type Node

type Node struct {
	Process
	Children []Node
}

Node is a node in a process tree.

func Tree

func Tree(procs []Process) []Node

Tree creates a hierarchy out of a list of processes.

Example
//go:build windows
// +build windows

package main

import (
	"fmt"
	"strings"

	"github.com/gentlemanautomaton/winproc"
)

func main() {
	procs, err := winproc.List(
		winproc.Include(winproc.ContainsName("svchost")),
		winproc.IncludeAncestors,
		winproc.IncludeDescendants,
		winproc.CollectCommands)
	if err != nil {
		fmt.Printf("Failed to retrieve process list: %v\n", err)
		return
	}

	printChildren(0, winproc.Tree(procs))
}

func printChildren(depth int, nodes []winproc.Node) {
	for _, node := range nodes {
		fmt.Printf("%s%s\n", strings.Repeat("  ", depth), node.Process)
		printChildren(depth+1, node.Children)
	}
}
Output:

type Process

type Process struct {
	ID          ID
	ParentID    ID
	Name        string
	Path        string
	Args        []string
	CommandLine string
	SessionID   uint32
	User        User
	Threads     int
	Times       Times
	Critical    bool
}

Process holds information about a windows process.

func List

func List(options ...CollectionOption) ([]Process, error)

List returns a list of running processes. Collection options can be provided to filter the list and collect additional process information. Options will be evaluated in order.

If a filter relies on process information gathered by one or more collector options, those options must be included before the filter.

Example
package main

import (
	"fmt"

	"github.com/gentlemanautomaton/winproc"
)

func main() {
	procs, err := winproc.List(
		winproc.Include(winproc.ContainsName("winlogon")),
		winproc.IncludeAncestors)
	if err != nil {
		fmt.Printf("Failed to retrieve process list: %v\n", err)
		return
	}

	for _, proc := range procs {
		fmt.Printf("%s\n", proc)
	}
}
Output:

func (Process) Protected

func (p Process) Protected() bool

Protected returns true if p represents a protected process of some kind:

All processes in session 0
All processes running as Local System, NT Authority or Network Service
All processes for which the SID has not been collected
The process with ID 0
The process with ID 4

TODO: Skip anything with the CREATE_PROTECTED_PROCESS flag?

func (Process) Ref

func (p Process) Ref(rights ...processaccess.Rights) (*Ref, error)

Ref returns a reference to the running process that matches the process ID of p.

It is the caller's responsibility to close the reference when finished with it.

func (Process) String

func (p Process) String() string

String returns a string representation of the process.

func (Process) UniqueID

func (p Process) UniqueID() UniqueID

UniqueID returns a unique identifier for the process by combining its creation time and process ID.

The process must contain a creation time for this function to return a unique value. This can be accomplished by supplying the CollectTimes option when collecting processes.

type Ref

type Ref struct {
	// contains filtered or unexported fields
}

A Ref is a reference to a running or exited process. It manages an open system handle internally. As long as a reference is open it prevents the associated process ID from being recycled.

Each reference must be closed when it is no longer needed.

func Open

func Open(pid ID, rights ...processaccess.Rights) (*Ref, error)

Open returns a reference to the process with the given process ID and access rights.

If one or more access rights are provided, they will be combined. If no access rights are provided, the QueryLimitedInformation right will be used.

It is the caller's responsibility to close the handle when finished with it.

func (*Ref) Close

func (ref *Ref) Close() error

Close releases the process handle maintained by ref.

If ref has already been closed it will return ErrClosed.

func (*Ref) CommandLine

func (ref *Ref) CommandLine() (command string, err error)

CommandLine returns the command line used to invoke the process.

This call is only supported on Windows 10 1511 or newer.

TODO: Consider adding support for older operating systems by using older, more arcane implementations when necessary.

https://wj32.org/wp/2009/01/24/howto-get-the-command-line-of-processes/ https://stackoverflow.com/questions/45891035/get-processid-from-binary-path-command-line-statement-in-c

func (*Ref) Critical

func (ref *Ref) Critical() (bool, error)

Critical returns true if the process is considered critical to the system's operation.

This call is only supported on Windows 8.1 or newer.

func (*Ref) ExitCode

func (ref *Ref) ExitCode() (exitCode uint32, err error)

ExitCode returns the exit code for the process if it has exited.

If the process is still running it returns ErrProcessStillActive.

Due to the design of the underlying windows API call, this will incorrectly return ErrProcessStillActive if the process exited with status code 259. See the documentation for GetExitCodeProcess for more details.

func (*Ref) ID

func (ref *Ref) ID() (ID, error)

ID returns the ID of the process.

func (*Ref) SessionID

func (ref *Ref) SessionID() (sessionID uint32, err error)

SessionID returns the ID of the windows session associated with the process.

func (*Ref) Terminate

func (ref *Ref) Terminate(exitCode uint32) error

Terminate instructs the operating system to terminate the process with the given exit code.

func (*Ref) Times

func (ref *Ref) Times() (times Times, err error)

Times returns time information about the process.

func (*Ref) UniqueID

func (ref *Ref) UniqueID() (UniqueID, error)

UniqueID returns a unique identifier for the process by combining its creation time and process ID.

func (*Ref) User

func (ref *Ref) User() (user User, err error)

User returns information about the windows user associated with the process.

func (*Ref) Wait

func (ref *Ref) Wait(ctx context.Context) error

Wait waits until the process terminates or ctx is cancelled. It returns nil if the process has terminated.

If ctx is cancelled the value of ctx.Err() will be returned.

type Relation

type Relation int

Relation is a collection option that includes processes related to those already matched.

const (
	// IncludeAncestors is a collection option that includes all ancestors
	// of matched processes.
	IncludeAncestors Relation = 1 << iota

	// IncludeDescendants is a collection option that includes all descendants
	// of matched processes.
	IncludeDescendants
)

func (Relation) Apply

func (r Relation) Apply(col *Collection)

Apply applies the relation to the collection.

func (Relation) Contains

func (r Relation) Contains(b Relation) bool

Contains returns true if r contains b.

func (Relation) Merge

func (r Relation) Merge(next CollectionOption) (merged CollectionOption, ok bool)

Merge attempts to merge the relation with the next option. It returns true if successful.

type StringMatcher

type StringMatcher func(string) bool

A StringMatcher is a function that matches strings

type Times

type Times struct {
	Creation time.Time     // Process creation time
	Exit     time.Time     // Process exit time
	Kernel   time.Duration // Time spent in kernel mode
	User     time.Duration // Time spent in user mode
}

Times holds time information about a windows process.

type TreeAction

type TreeAction func(tree []Node) error

TreeAction is a function that takes action on a tree.

type UniqueID

type UniqueID struct {
	Creation int64 // Nanoseconds since (00:00:00 UTC, January 1, 1970)
	ID       ID
}

UniqueID is a 12-byte identifier that uniquely identifies a process on a host machine by combining its creation time and process ID.

func (UniqueID) Bytes

func (uid UniqueID) Bytes() (b [12]byte)

Bytes returns uid as a sequence of bytes.

func (UniqueID) String

func (uid UniqueID) String() string

String returns a string representation of the identifier.

type User

type User struct {
	SID     string
	Account string
	Domain  string
	Type    uint32
}

User holds account information for the security context of a process.

func (User) String

func (u User) String() string

String returns a string representation of the user.

func (User) System

func (u User) System() bool

System returns true if u describes a system user with one of the following security identifiers:

Local System
NT Authority
Network Service

Directories

Path Synopsis
cmd
Package ntstatus defines NTSTATUS codes used by the windows kernel and many protocols and programs.
Package ntstatus defines NTSTATUS codes used by the windows kernel and many protocols and programs.
Package winsecid contains a list of well-known Windows security IDs.
Package winsecid contains a list of well-known Windows security IDs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL