github.com/gunjan5/docker@v1.8.2/pkg/sockets/unix_socket.go (about)

     1  // +build linux
     2  
     3  package sockets
     4  
     5  import (
     6  	"fmt"
     7  	"net"
     8  	"os"
     9  	"strconv"
    10  	"syscall"
    11  
    12  	"github.com/Sirupsen/logrus"
    13  	"github.com/docker/docker/pkg/listenbuffer"
    14  	"github.com/opencontainers/runc/libcontainer/user"
    15  )
    16  
    17  func NewUnixSocket(path, group string, activate <-chan struct{}) (net.Listener, error) {
    18  	if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) {
    19  		return nil, err
    20  	}
    21  	mask := syscall.Umask(0777)
    22  	defer syscall.Umask(mask)
    23  	l, err := listenbuffer.NewListenBuffer("unix", path, activate)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	if err := setSocketGroup(path, group); err != nil {
    28  		l.Close()
    29  		return nil, err
    30  	}
    31  	if err := os.Chmod(path, 0660); err != nil {
    32  		l.Close()
    33  		return nil, err
    34  	}
    35  	return l, nil
    36  }
    37  
    38  func setSocketGroup(path, group string) error {
    39  	if group == "" {
    40  		return nil
    41  	}
    42  	if err := changeGroup(path, group); err != nil {
    43  		if group != "docker" {
    44  			return err
    45  		}
    46  		logrus.Debugf("Warning: could not change group %s to docker: %v", path, err)
    47  	}
    48  	return nil
    49  }
    50  
    51  func changeGroup(path string, nameOrGid string) error {
    52  	gid, err := lookupGidByName(nameOrGid)
    53  	if err != nil {
    54  		return err
    55  	}
    56  	logrus.Debugf("%s group found. gid: %d", nameOrGid, gid)
    57  	return os.Chown(path, 0, gid)
    58  }
    59  
    60  func lookupGidByName(nameOrGid string) (int, error) {
    61  	groupFile, err := user.GetGroupPath()
    62  	if err != nil {
    63  		return -1, err
    64  	}
    65  	groups, err := user.ParseGroupFileFilter(groupFile, func(g user.Group) bool {
    66  		return g.Name == nameOrGid || strconv.Itoa(g.Gid) == nameOrGid
    67  	})
    68  	if err != nil {
    69  		return -1, err
    70  	}
    71  	if groups != nil && len(groups) > 0 {
    72  		return groups[0].Gid, nil
    73  	}
    74  	gid, err := strconv.Atoi(nameOrGid)
    75  	if err == nil {
    76  		logrus.Warnf("Could not find GID %d", gid)
    77  		return gid, nil
    78  	}
    79  	return -1, fmt.Errorf("Group %s not found", nameOrGid)
    80  }