[lxc-devel] [lxd/master] util linux: guess size when sysconf() returns -1

brauner on Github lxc-bot at linuxcontainers.org
Mon Jul 24 13:15:44 UTC 2017


A non-text attachment was scrubbed...
Name: not available
Type: text/x-mailbox
Size: 364 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-devel/attachments/20170724/2524a646/attachment.bin>
-------------- next part --------------
From 937fc090f35f562c5e162e4806dc93f902d621cc Mon Sep 17 00:00:00 2001
From: Christian Brauner <christian.brauner at ubuntu.com>
Date: Mon, 24 Jul 2017 15:13:51 +0200
Subject: [PATCH] util linux: guess size when sysconf() returns -1

Signed-off-by: Christian Brauner <christian.brauner at ubuntu.com>
---
 shared/util_linux.go | 42 ++++++++++++++++++++++++++++++++++++------
 1 file changed, 36 insertions(+), 6 deletions(-)

diff --git a/shared/util_linux.go b/shared/util_linux.go
index 5be541c6e..62225f8a1 100644
--- a/shared/util_linux.go
+++ b/shared/util_linux.go
@@ -292,6 +292,10 @@ func UserId(name string) (int, error) {
 	var result *C.struct_passwd
 
 	bufSize := C.size_t(C.sysconf(C._SC_GETPW_R_SIZE_MAX))
+	if bufSize < 0 {
+		bufSize = 4096
+	}
+
 	buf := C.malloc(bufSize)
 	if buf == nil {
 		return -1, fmt.Errorf("allocation failed")
@@ -301,13 +305,24 @@ func UserId(name string) (int, error) {
 	cname := C.CString(name)
 	defer C.free(unsafe.Pointer(cname))
 
-	rv := C.getpwnam_r(cname,
+again:
+	rv, errno := C.getpwnam_r(cname,
 		&pw,
 		(*C.char)(buf),
 		bufSize,
 		&result)
-
-	if rv != 0 {
+	if rv < 0 {
+		// OOM killer will take care of us if we end up doing this too
+		// often.
+		if errno == syscall.ERANGE {
+			bufSize *= 2
+			tmp := C.realloc(buf, bufSize)
+			if tmp == nil {
+				return -1, fmt.Errorf("allocation failed")
+			}
+			buf = tmp
+			goto again
+		}
 		return -1, fmt.Errorf("failed user lookup: %s", syscall.Errno(rv))
 	}
 
@@ -324,6 +339,10 @@ func GroupId(name string) (int, error) {
 	var result *C.struct_group
 
 	bufSize := C.size_t(C.sysconf(C._SC_GETGR_R_SIZE_MAX))
+	if bufSize < 0 {
+		bufSize = 4096
+	}
+
 	buf := C.malloc(bufSize)
 	if buf == nil {
 		return -1, fmt.Errorf("allocation failed")
@@ -333,13 +352,24 @@ func GroupId(name string) (int, error) {
 	cname := C.CString(name)
 	defer C.free(unsafe.Pointer(cname))
 
-	rv := C.getgrnam_r(cname,
+again:
+	rv, errno := C.getgrnam_r(cname,
 		&grp,
 		(*C.char)(buf),
 		bufSize,
 		&result)
-
-	if rv != 0 {
+	if rv < 0 {
+		// OOM killer will take care of us if we end up doing this too
+		// often.
+		if errno == syscall.ERANGE {
+			bufSize *= 2
+			tmp := C.realloc(buf, bufSize)
+			if tmp == nil {
+				return -1, fmt.Errorf("allocation failed")
+			}
+			buf = tmp
+			goto again
+		}
 		return -1, fmt.Errorf("failed group lookup: %s", syscall.Errno(rv))
 	}
 


More information about the lxc-devel mailing list