github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/daemon/initlayer/setup_unix.go (about)

     1  //go:build linux || freebsd
     2  
     3  package initlayer // import "github.com/Prakhar-Agarwal-byte/moby/daemon/initlayer"
     4  
     5  import (
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"github.com/Prakhar-Agarwal-byte/moby/pkg/idtools"
    11  	"golang.org/x/sys/unix"
    12  )
    13  
    14  // Setup populates a directory with mountpoints suitable
    15  // for bind-mounting things into the container.
    16  //
    17  // This extra layer is used by all containers as the top-most ro layer. It protects
    18  // the container from unwanted side-effects on the rw layer.
    19  func Setup(initLayerFs string, rootIdentity idtools.Identity) error {
    20  	// Since all paths are local to the container, we can just extract initLayerFs.Path()
    21  	initLayer := initLayerFs
    22  
    23  	for pth, typ := range map[string]string{
    24  		"/dev/pts":         "dir",
    25  		"/dev/shm":         "dir",
    26  		"/proc":            "dir",
    27  		"/sys":             "dir",
    28  		"/.dockerenv":      "file",
    29  		"/etc/resolv.conf": "file",
    30  		"/etc/hosts":       "file",
    31  		"/etc/hostname":    "file",
    32  		"/dev/console":     "file",
    33  		"/etc/mtab":        "/proc/mounts",
    34  	} {
    35  		parts := strings.Split(pth, "/")
    36  		prev := "/"
    37  		for _, p := range parts[1:] {
    38  			prev = filepath.Join(prev, p)
    39  			unix.Unlink(filepath.Join(initLayer, prev))
    40  		}
    41  
    42  		if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
    43  			if os.IsNotExist(err) {
    44  				if err := idtools.MkdirAllAndChownNew(filepath.Join(initLayer, filepath.Dir(pth)), 0o755, rootIdentity); err != nil {
    45  					return err
    46  				}
    47  				switch typ {
    48  				case "dir":
    49  					if err := idtools.MkdirAllAndChownNew(filepath.Join(initLayer, pth), 0o755, rootIdentity); err != nil {
    50  						return err
    51  					}
    52  				case "file":
    53  					f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0o755)
    54  					if err != nil {
    55  						return err
    56  					}
    57  					f.Chown(rootIdentity.UID, rootIdentity.GID)
    58  					f.Close()
    59  				default:
    60  					if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
    61  						return err
    62  					}
    63  				}
    64  			} else {
    65  				return err
    66  			}
    67  		}
    68  	}
    69  
    70  	// Layer is ready to use, if it wasn't before.
    71  	return nil
    72  }