gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/fsutil/fsutil.go (about)

     1  // Copyright 2022 The gVisor Authors.
     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 fsutil contains filesystem utilities that can be shared between the
    16  // sentry and other sandbox components.
    17  package fsutil
    18  
    19  import "golang.org/x/sys/unix"
    20  
    21  // DirentHandler is a function that handles a dirent.
    22  type DirentHandler func(ino uint64, off int64, ftype uint8, name string, reclen uint16)
    23  
    24  // ForEachDirent retrieves all dirents from dirfd using getdents64(2) and
    25  // invokes handleDirent on them.
    26  func ForEachDirent(dirfd int, handleDirent DirentHandler) error {
    27  	var direntsBuf [8192]byte
    28  	for {
    29  		n, err := unix.Getdents(dirfd, direntsBuf[:])
    30  		if err != nil {
    31  			return err
    32  		}
    33  		if n <= 0 {
    34  			return nil
    35  		}
    36  		ParseDirents(direntsBuf[:n], handleDirent)
    37  	}
    38  }
    39  
    40  // DirentNames retrieves all dirents from dirfd using getdents64(2) and returns
    41  // all the recorded dirent names.
    42  func DirentNames(dirfd int) ([]string, error) {
    43  	var names []string
    44  	err := ForEachDirent(dirfd, func(_ uint64, _ int64, _ uint8, name string, _ uint16) {
    45  		names = append(names, name)
    46  	})
    47  	return names, err
    48  }