Skip to content

Commit

Permalink
Add static_build tag which avoids user.Current()
Browse files Browse the repository at this point in the history
Its not safe to use os/user.Current() in a statically linked program.
You will be getting warnings like:

 warning: Using 'getpwnam_r' in statically linked applications requires
  at runtime the shared libraries from the glibc version used for linking
 warning: Using 'getpwuid_r' in statically linked applications requires
  at runtime the shared libraries from the glibc version used for linking

We avoid this when building with -tag static_build by parsing
/etc/passwd directly for the homedir.
  • Loading branch information
alexlarsson committed Mar 27, 2014
1 parent 164977e commit da6051a
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 6 deletions.
7 changes: 1 addition & 6 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"errors"
"io"
"os"
"os/user"
"strconv"
)

Expand Down Expand Up @@ -55,11 +54,7 @@ type Auth interface {
func (conn *Conn) Auth(methods []Auth) error {
if methods == nil {
uid := strconv.Itoa(os.Getuid())
u, err := user.Current()
if err != nil {
return err
}
methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, u.HomeDir)}
methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
}
in := bufio.NewReader(conn.transport)
err := conn.transport.SendNullByte()
Expand Down
28 changes: 28 additions & 0 deletions homedir.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package dbus

import (
"os"
"sync"
)

var (
homeDir string
homeDirLock sync.Mutex
)

func getHomeDir() string {
homeDirLock.Lock()
defer homeDirLock.Unlock()

if homeDir != "" {
return homeDir
}

homeDir = os.Getenv("HOME")
if homeDir != "" {
return homeDir
}

homeDir = lookupHomeDir()
return homeDir
}
15 changes: 15 additions & 0 deletions homedir_dynamic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// +build !static_build

package dbus

import (
"os/user"
)

func lookupHomeDir() string {
u, err := user.Current()
if err != nil {
return "/"
}
return u.HomeDir
}
45 changes: 45 additions & 0 deletions homedir_static.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// +build static_build

package dbus

import (
"bufio"
"os"
"strconv"
"strings"
)

func lookupHomeDir() string {
myUid := os.Getuid()

f, err := os.Open("/etc/passwd")
if err != nil {
return "/"
}
defer f.Close()

s := bufio.NewScanner(f)

for s.Scan() {
if err := s.Err(); err != nil {
break
}

line := strings.TrimSpace(s.Text())
if line == "" {
continue
}

parts := strings.Split(line, ":")

if len(parts) >= 6 {
uid, err := strconv.Atoi(parts[2])
if err == nil && uid == myUid {
return parts[5]
}
}
}

// Default to / if we can't get a better value
return "/"
}

0 comments on commit da6051a

Please sign in to comment.