11package  userns
22
33import  (
4+ 	"bufio" 
5+ 	"fmt" 
6+ 	"os" 
47	"sync" 
5- 
6- 	"github.com/opencontainers/runc/libcontainer/user" 
78)
89
910var  (
@@ -12,26 +13,43 @@ var (
1213)
1314
1415// runningInUserNS detects whether we are currently running in a user namespace. 
15- // Originally copied from github.com/lxc/lxd/shared/util.go 
16+ // 
17+ // Originally copied from https://github.com/lxc/incus/blob/e45085dd42f826b3c8c3228e9733c0b6f998eafe/shared/util.go#L678-L700. 
1618func  runningInUserNS () bool  {
1719	nsOnce .Do (func () {
18- 		uidmap , err  :=  user .CurrentProcessUIDMap ()
20+ 		file , err  :=  os .Open ("/proc/self/uid_map" )
21+ 		if  err  !=  nil  {
22+ 			// This kernel-provided file only exists if user namespaces are supported. 
23+ 			return 
24+ 		}
25+ 		defer  file .Close ()
26+ 
27+ 		buf  :=  bufio .NewReader (file )
28+ 		l , _ , err  :=  buf .ReadLine ()
1929		if  err  !=  nil  {
20- 			// This kernel-provided file only exists if user namespaces are supported 
2130			return 
2231		}
23- 		inUserNS  =  uidMapInUserNS (uidmap )
32+ 
33+ 		inUserNS  =  uidMapInUserNS (string (l ))
2434	})
2535	return  inUserNS 
2636}
2737
28- func  uidMapInUserNS (uidmap  []user.IDMap ) bool  {
29- 	/* 
30- 	 * We assume we are in the initial user namespace if we have a full 
31- 	 * range - 4294967295 uids starting at uid 0. 
32- 	 */ 
33- 	if  len (uidmap ) ==  1  &&  uidmap [0 ].ID  ==  0  &&  uidmap [0 ].ParentID  ==  0  &&  uidmap [0 ].Count  ==  4294967295  {
38+ func  uidMapInUserNS (uidMap  string ) bool  {
39+ 	if  uidMap  ==  ""  {
40+ 		// File exist but empty (the initial state when userns is created, 
41+ 		// see user_namespaces(7)). 
42+ 		return  true 
43+ 	}
44+ 
45+ 	var  a , b , c  int64 
46+ 	if  _ , err  :=  fmt .Sscanf (uidMap , "%d %d %d" , & a , & b , & c ); err  !=  nil  {
47+ 		// Assume we are in a regular, non user namespace. 
3448		return  false 
3549	}
36- 	return  true 
50+ 
51+ 	// As per user_namespaces(7), /proc/self/uid_map of 
52+ 	// the initial user namespace shows 0 0 4294967295. 
53+ 	initNS  :=  a  ==  0  &&  b  ==  0  &&  c  ==  4294967295 
54+ 	return  ! initNS 
3755}
0 commit comments