Skip to content

Commit

Permalink
Merge pull request #13 from eonarheim/master
Browse files Browse the repository at this point in the history
Add GetProcCredName implementation to windows gosigar
  • Loading branch information
andrewkroh committed Jan 21, 2016
2 parents 2742b88 + a473715 commit 99d5aaa
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions sigar_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ const (

type ProcState struct {
Name string
Username string
State RunState
Ppid int
Tty int
Expand Down
47 changes: 47 additions & 0 deletions sigar_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,12 @@ func (self *ProcState) Get(pid int) error {
if err != nil {
return err
}

self.Username, err = GetProcCredName(pid)
if err != nil {
return err
}

return nil
}

Expand Down Expand Up @@ -306,6 +312,47 @@ func GetProcName(pid int) (string, error) {

}

func GetProcCredName(pid int) (string, error) {
var err error

handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))

if err != nil {
return "", fmt.Errorf("OpenProcess fails with %v", err)
}

defer syscall.CloseHandle(handle)

var token syscall.Token

// Find process token via win32
err = syscall.OpenProcessToken(handle, syscall.TOKEN_QUERY, &token)

if err != nil {
return "", fmt.Errorf("Error opening process token %v", err)
}

// Find the token user
tokenUser, err := token.GetTokenUser()
if err != nil {
return "", fmt.Errorf("Error getting token user %v", err)
}

// Close token to prevent handle leaks
err = token.Close()
if err != nil {
return "", fmt.Errorf("Error failed to closed process token")
}

// look up domain account by sid
account, domain, _, err := tokenUser.User.Sid.LookupAccount("localhost")
if err != nil {
return "", fmt.Errorf("Error looking up sid %v", err)
}

return fmt.Sprintf("%s\\%s", domain, account), nil
}

func GetProcStatus(pid int) (RunState, error) {

handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
Expand Down
13 changes: 13 additions & 0 deletions sigar_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package sigar_test
import (
"math"
"os"
"os/user"
"strings"
"testing"

Expand Down Expand Up @@ -32,6 +33,18 @@ var _ = Describe("SigarWindows", func() {
Ω(usage.Total).Should(BeNumerically(">", 0))
})
})

Describe("Process", func() {
It("gets the current process user name", func() {
proc := sigar.ProcState{}
err := proc.Get(os.Getpid())
user, usererr := user.Current()

Ω(err).ShouldNot(HaveOccurred())
Ω(usererr).ShouldNot(HaveOccurred())
Ω(proc.Username).Should(Equal(user.Username))
})
})
})

func TestProcArgs(t *testing.T) {
Expand Down

0 comments on commit 99d5aaa

Please sign in to comment.