github.com/datadog/cilium@v1.6.12/pkg/api/socket.go (about) 1 // Copyright 2017-2018 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package api 16 17 import ( 18 "bufio" 19 "fmt" 20 "io" 21 "os" 22 "strconv" 23 "strings" 24 25 "github.com/cilium/cilium/pkg/logging" 26 "github.com/cilium/cilium/pkg/logging/logfields" 27 28 "github.com/sirupsen/logrus" 29 ) 30 31 var log = logging.DefaultLogger.WithField(logfields.LogSubsys, "api") 32 33 // GetGroupIDByName returns the group ID for the given grpName. 34 func GetGroupIDByName(grpName string) (int, error) { 35 f, err := os.Open(GroupFilePath) 36 if err != nil { 37 return -1, err 38 } 39 defer f.Close() 40 br := bufio.NewReader(f) 41 for { 42 s, err := br.ReadString('\n') 43 if err == io.EOF { 44 break 45 } 46 if err != nil { 47 return -1, err 48 } 49 p := strings.Split(s, ":") 50 if len(p) >= 3 && p[0] == grpName { 51 return strconv.Atoi(p[2]) 52 } 53 } 54 return -1, fmt.Errorf("group %q not found", grpName) 55 } 56 57 // SetDefaultPermissions sets the given socket to with cilium's default 58 // group and mode permissions. Group `CiliumGroupName` and mode `0660` 59 func SetDefaultPermissions(socketPath string) error { 60 gid, err := GetGroupIDByName(CiliumGroupName) 61 if err != nil { 62 log.WithError(err).WithFields(logrus.Fields{ 63 logfields.Path: socketPath, 64 "group": CiliumGroupName, 65 }).Info("Group not found") 66 } else { 67 if err := os.Chown(socketPath, 0, gid); err != nil { 68 return fmt.Errorf("failed while setting up %s's group ID"+ 69 " in %q: %s", CiliumGroupName, socketPath, err) 70 } 71 } 72 if err := os.Chmod(socketPath, SocketFileMode); err != nil { 73 return fmt.Errorf("failed while setting up %s's file"+ 74 " permissions in %q: %s", CiliumGroupName, socketPath, err) 75 } 76 return nil 77 }