github.com/squaremo/docker@v1.3.2-0.20150516120342-42cfc9554972/api/server/unix_socket.go (about)

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