| 1 | package godaemon |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "os" |
| 6 | "syscall" |
| 7 | ) |
| 8 | |
| 9 | // Readlink returns the file pointed to by the given soft link, or an error of |
| 10 | // type PathError otherwise. This mimics the os.Readlink() function, but works |
| 11 | // around a bug we've seen in CentOS 5.10 (kernel 2.6.27.10 on x86_64) where the |
| 12 | // underlying OS function readlink() returns a wrong number of bytes for the |
| 13 | // result (see man readlink). Here we don't rely blindly on that value; if |
| 14 | // there's a zero byte among that number of bytes, then we keep only up to that |
| 15 | // point. |
| 16 | // |
| 17 | // NOTE: We chose not to use os.Readlink() and then search on its result to |
| 18 | // avoid an extra overhead of converting back to []byte. The function to search |
| 19 | // for a byte over the string itself (strings.IndexByte()) is only available |
| 20 | // starting with Go 1.2. Also, we're not searching at every iteration to save |
| 21 | // some CPU time, even though that could mean extra iterations for systems |
| 22 | // affected with this bug. But it's wiser to optimize for the general case |
| 23 | // (i.e., those not affected). |
| 24 | func Readlink(name string) (string, error) { |
| 25 | for len := 128; ; len *= 2 { |
| 26 | b := make([]byte, len) |
| 27 | n, e := syscall.Readlink(name, b) |
| 28 | if e != nil { |
| 29 | return "", &os.PathError{Op: "readlink", Path: name, Err: e} |
| 30 | } |
| 31 | if n < len { |
| 32 | if z := bytes.IndexByte(b[:n], 0); z >= 0 { |
| 33 | n = z |
| 34 | } |
| 35 | return string(b[:n]), nil |
| 36 | } |
| 37 | } |
| 38 | } |