github.com/system-transparency/u-root@v6.0.1-0.20190919065413-ed07a650de4c+incompatible/pkg/uroot/uroot.go (about)

     1  // Copyright 2015-2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package uroot
     6  
     7  import (
     8  	"fmt"
     9  	"io/ioutil"
    10  	"os"
    11  	"path"
    12  	"path/filepath"
    13  	"strings"
    14  
    15  	"github.com/u-root/u-root/pkg/cpio"
    16  	"github.com/u-root/u-root/pkg/golang"
    17  	"github.com/u-root/u-root/pkg/ldd"
    18  	"github.com/u-root/u-root/pkg/uroot/builder"
    19  	"github.com/u-root/u-root/pkg/uroot/initramfs"
    20  	"github.com/u-root/u-root/pkg/uroot/logger"
    21  )
    22  
    23  // These constants are used in DefaultRamfs.
    24  const (
    25  	// This is the literal timezone file for GMT-0. Given that we have no
    26  	// idea where we will be running, GMT seems a reasonable guess. If it
    27  	// matters, setup code should download and change this to something
    28  	// else.
    29  	gmt0 = "TZif2\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00GMT\x00\x00\x00TZif2\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x04\xf8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00GMT\x00\x00\x00\nGMT0\n"
    30  
    31  	nameserver = "nameserver 8.8.8.8\n"
    32  )
    33  
    34  // DefaultRamfs are files that are contained in all u-root initramfs archives
    35  // by default.
    36  var DefaultRamfs = cpio.ArchiveFromRecords([]cpio.Record{
    37  	cpio.Directory("tcz", 0755),
    38  	cpio.Directory("etc", 0755),
    39  	cpio.Directory("dev", 0755),
    40  	cpio.Directory("tmp", 0777),
    41  	cpio.Directory("ubin", 0755),
    42  	cpio.Directory("usr", 0755),
    43  	cpio.Directory("usr/lib", 0755),
    44  	cpio.Directory("var/log", 0777),
    45  	cpio.Directory("lib64", 0755),
    46  	cpio.Directory("bin", 0755),
    47  	cpio.CharDev("dev/console", 0600, 5, 1),
    48  	cpio.CharDev("dev/tty", 0666, 5, 0),
    49  	cpio.CharDev("dev/null", 0666, 1, 3),
    50  	cpio.CharDev("dev/port", 0640, 1, 4),
    51  	cpio.CharDev("dev/urandom", 0666, 1, 9),
    52  	cpio.StaticFile("etc/resolv.conf", nameserver, 0644),
    53  	cpio.StaticFile("etc/localtime", gmt0, 0644),
    54  })
    55  
    56  // Commands specifies a list of Golang packages to build with a builder, e.g.
    57  // in busybox mode, source mode, or binary mode.
    58  //
    59  // See Builder for an explanation of build modes.
    60  type Commands struct {
    61  	// Builder is the Go compiler mode.
    62  	Builder builder.Builder
    63  
    64  	// Packages are the Go commands to include (compiled or otherwise) and
    65  	// add to the archive.
    66  	//
    67  	// Currently allowed formats:
    68  	//
    69  	//   - package imports; e.g. github.com/u-root/u-root/cmds/ls
    70  	//   - globs of package imports; e.g. github.com/u-root/u-root/cmds/*
    71  	//   - paths to package directories; e.g. $GOPATH/src/github.com/u-root/u-root/cmds/ls
    72  	//   - globs of paths to package directories; e.g. ./cmds/*
    73  	//
    74  	// Directories may be relative or absolute, with or without globs.
    75  	// Globs are resolved using filepath.Glob.
    76  	Packages []string
    77  
    78  	// BinaryDir is the directory in which the resulting binaries are
    79  	// placed inside the initramfs.
    80  	//
    81  	// BinaryDir may be empty, in which case Builder.DefaultBinaryDir()
    82  	// will be used.
    83  	BinaryDir string
    84  }
    85  
    86  // TargetDir returns the initramfs binary directory for these Commands.
    87  func (c Commands) TargetDir() string {
    88  	if len(c.BinaryDir) != 0 {
    89  		return c.BinaryDir
    90  	}
    91  	return c.Builder.DefaultBinaryDir()
    92  }
    93  
    94  // Opts are the arguments to CreateInitramfs.
    95  //
    96  // Opts contains everything that influences initramfs creation such as the Go
    97  // build environment.
    98  type Opts struct {
    99  	// Env is the Golang build environment (GOOS, GOARCH, etc).
   100  	Env golang.Environ
   101  
   102  	// Commands specify packages to build using a specific builder.
   103  	//
   104  	// E.g. the following will build 'ls' and 'ip' in busybox mode, but
   105  	// 'cd' and 'cat' as separate binaries. 'cd', 'cat', 'bb', and symlinks
   106  	// from 'ls' and 'ip' will be added to the final initramfs.
   107  	//
   108  	//   []Commands{
   109  	//     Commands{
   110  	//       Builder: builder.BusyBox,
   111  	//       Packages: []string{
   112  	//         "github.com/u-root/u-root/cmds/ls",
   113  	//         "github.com/u-root/u-root/cmds/ip",
   114  	//       },
   115  	//     },
   116  	//     Commands{
   117  	//       Builder: builder.Binary,
   118  	//       Packages: []string{
   119  	//         "github.com/u-root/u-root/cmds/cd",
   120  	//         "github.com/u-root/u-root/cmds/cat",
   121  	//       },
   122  	//     },
   123  	//   }
   124  	Commands []Commands
   125  
   126  	// TempDir is a temporary directory for builders to store files in.
   127  	TempDir string
   128  
   129  	// ExtraFiles are files to add to the archive in addition to the Go
   130  	// packages.
   131  	//
   132  	// Shared library dependencies will automatically also be added to the
   133  	// archive using ldd, unless SkipLDD (below) is true.
   134  	//
   135  	// The following formats are allowed in the list:
   136  	//
   137  	//   - "/home/chrisko/foo:root/bar" adds the file from absolute path
   138  	//     /home/chrisko/foo on the host at the relative root/bar in the
   139  	//     archive.
   140  	//   - "/home/foo" is equivalent to "/home/foo:home/foo".
   141  	ExtraFiles []string
   142  
   143  	// If true, do not use ldd to pick up dependencies from local machine for
   144  	// ExtraFiles. Useful if you have all deps revision controlled and wish to
   145  	// ensure builds are repeatable, and/or if the local machine's binaries use
   146  	// instructions unavailable on the emulated cpu.
   147  	//
   148  	// If you turn this on but do not manually list all deps, affected binaries
   149  	// will misbehave.
   150  	SkipLDD bool
   151  
   152  	// OutputFile is the archive output file.
   153  	OutputFile initramfs.Writer
   154  
   155  	// BaseArchive is an existing initramfs to include in the resulting
   156  	// initramfs.
   157  	BaseArchive initramfs.Reader
   158  
   159  	// UseExistingInit determines whether the existing init from
   160  	// BaseArchive should be used.
   161  	//
   162  	// If this is false, the "init" from BaseArchive will be renamed to
   163  	// "inito" (init-original).
   164  	UseExistingInit bool
   165  
   166  	// InitCmd is the name of a command to link /init to.
   167  	//
   168  	// This can be an absolute path or the name of a command included in
   169  	// Commands.
   170  	//
   171  	// If this is empty, no init symlink will be created.
   172  	InitCmd string
   173  
   174  	// DefaultShell is the default shell to start after init.
   175  	//
   176  	// This can be an absolute path or the name of a command included in
   177  	// Commands.
   178  	//
   179  	// This must be specified to have a default shell.
   180  	DefaultShell string
   181  }
   182  
   183  // CreateInitramfs creates an initramfs built to opts' specifications.
   184  func CreateInitramfs(logger logger.Logger, opts Opts) error {
   185  	if _, err := os.Stat(opts.TempDir); os.IsNotExist(err) {
   186  		return fmt.Errorf("temp dir %q must exist: %v", opts.TempDir, err)
   187  	}
   188  	if opts.OutputFile == nil {
   189  		return fmt.Errorf("must give output file")
   190  	}
   191  
   192  	files := initramfs.NewFiles()
   193  
   194  	// Expand commands.
   195  	for index, cmds := range opts.Commands {
   196  		importPaths, err := ResolvePackagePaths(logger, opts.Env, cmds.Packages)
   197  		if err != nil {
   198  			return err
   199  		}
   200  		opts.Commands[index].Packages = importPaths
   201  	}
   202  
   203  	// Add each build mode's commands to the archive.
   204  	for _, cmds := range opts.Commands {
   205  		builderTmpDir, err := ioutil.TempDir(opts.TempDir, "builder")
   206  		if err != nil {
   207  			return err
   208  		}
   209  
   210  		// Build packages.
   211  		bOpts := builder.Opts{
   212  			Env:       opts.Env,
   213  			Packages:  cmds.Packages,
   214  			TempDir:   builderTmpDir,
   215  			BinaryDir: cmds.TargetDir(),
   216  		}
   217  		if err := cmds.Builder.Build(files, bOpts); err != nil {
   218  			return fmt.Errorf("error building: %v", err)
   219  		}
   220  	}
   221  
   222  	// Open the target initramfs file.
   223  	archive := initramfs.Opts{
   224  		Files:           files,
   225  		OutputFile:      opts.OutputFile,
   226  		BaseArchive:     opts.BaseArchive,
   227  		UseExistingInit: opts.UseExistingInit,
   228  	}
   229  
   230  	if len(opts.DefaultShell) > 0 {
   231  		if target, err := resolveCommandOrPath(opts.DefaultShell, opts.Commands); err != nil {
   232  			logger.Printf("No default shell: %v", err)
   233  		} else {
   234  			rtarget, err := filepath.Rel("/", target)
   235  			if err != nil {
   236  				return err
   237  			}
   238  
   239  			if err := archive.AddRecord(cpio.Symlink("bin/defaultsh", filepath.Join("..", rtarget))); err != nil {
   240  				return err
   241  			}
   242  			if err := archive.AddRecord(cpio.Symlink("bin/sh", filepath.Join("..", rtarget))); err != nil {
   243  				return err
   244  			}
   245  		}
   246  	}
   247  
   248  	if len(opts.InitCmd) > 0 {
   249  		if target, err := resolveCommandOrPath(opts.InitCmd, opts.Commands); err != nil {
   250  			if opts.Commands != nil {
   251  				return fmt.Errorf("could not find init: %v", err)
   252  			}
   253  		} else {
   254  			rtarget, err := filepath.Rel("/", target)
   255  			if err != nil {
   256  				return err
   257  			}
   258  			if err := archive.AddRecord(cpio.Symlink("init", rtarget)); err != nil {
   259  				return err
   260  			}
   261  		}
   262  	}
   263  
   264  	if err := ParseExtraFiles(logger, archive.Files, opts.ExtraFiles, !opts.SkipLDD); err != nil {
   265  		return err
   266  	}
   267  
   268  	// Finally, write the archive.
   269  	if err := initramfs.Write(&archive); err != nil {
   270  		return fmt.Errorf("error archiving: %v", err)
   271  	}
   272  	return nil
   273  }
   274  
   275  // resolvePackagePath finds import paths for a single import path or directory string
   276  func resolvePackagePath(logger logger.Logger, env golang.Environ, pkg string) ([]string, error) {
   277  	// Search the current working directory, as well GOROOT and GOPATHs
   278  	prefixes := append([]string{""}, env.SrcDirs()...)
   279  	// Resolve file system paths to package import paths.
   280  	for _, prefix := range prefixes {
   281  		path := filepath.Join(prefix, pkg)
   282  		matches, err := filepath.Glob(path)
   283  		if len(matches) == 0 || err != nil {
   284  			continue
   285  		}
   286  
   287  		var importPaths []string
   288  		for _, match := range matches {
   289  
   290  			// Only match directories for building.
   291  			// Skip anything that is not a directory
   292  			fileInfo, _ := os.Stat(match)
   293  			if !fileInfo.IsDir() {
   294  				continue
   295  			}
   296  
   297  			p, err := env.PackageByPath(match)
   298  			if err != nil {
   299  				logger.Printf("Skipping package %q: %v", match, err)
   300  			} else if p.ImportPath == "." {
   301  				// TODO: I do not completely understand why
   302  				// this is triggered. This is only an issue
   303  				// while this function is run inside the
   304  				// process of a "go test".
   305  				importPaths = append(importPaths, pkg)
   306  			} else {
   307  				importPaths = append(importPaths, p.ImportPath)
   308  			}
   309  		}
   310  		return importPaths, nil
   311  	}
   312  
   313  	// No file import paths found. Check if pkg still resolves as a package name.
   314  	if _, err := env.Package(pkg); err != nil {
   315  		return nil, fmt.Errorf("%q is neither package or path/glob: %v", pkg, err)
   316  	}
   317  	return []string{pkg}, nil
   318  }
   319  
   320  func resolveCommandOrPath(cmd string, cmds []Commands) (string, error) {
   321  	if filepath.IsAbs(cmd) {
   322  		return cmd, nil
   323  	}
   324  
   325  	for _, c := range cmds {
   326  		for _, p := range c.Packages {
   327  			// Figure out which build mode the shell is in, and symlink to
   328  			// that build modee
   329  			if name := path.Base(p); name == cmd {
   330  				return path.Join("/", c.TargetDir(), cmd), nil
   331  			}
   332  		}
   333  	}
   334  
   335  	return "", fmt.Errorf("command or path %q not included in u-root build", cmd)
   336  }
   337  
   338  // ResolvePackagePaths takes a list of Go package import paths and directories
   339  // and turns them into exclusively import paths.
   340  //
   341  // Currently allowed formats:
   342  //
   343  //   - package imports; e.g. github.com/u-root/u-root/cmds/ls
   344  //   - globs of package imports, e.g. github.com/u-root/u-root/cmds/*
   345  //   - paths to package directories; e.g. $GOPATH/src/github.com/u-root/u-root/cmds/ls
   346  //   - globs of paths to package directories; e.g. ./cmds/*
   347  //
   348  // Directories may be relative or absolute, with or without globs.
   349  // Globs are resolved using filepath.Glob.
   350  func ResolvePackagePaths(logger logger.Logger, env golang.Environ, pkgs []string) ([]string, error) {
   351  	var importPaths []string
   352  	for _, pkg := range pkgs {
   353  		paths, err := resolvePackagePath(logger, env, pkg)
   354  		if err != nil {
   355  			return nil, err
   356  		}
   357  		importPaths = append(importPaths, paths...)
   358  	}
   359  	return importPaths, nil
   360  }
   361  
   362  // ParseExtraFiles adds files from the extraFiles list to the archive.
   363  //
   364  // The following formats are allowed in the extraFiles list:
   365  //
   366  //   - "/home/chrisko/foo:root/bar" adds the file from absolute path
   367  //     /home/chrisko/foo on the host at the relative root/bar in the
   368  //     archive.
   369  //   - "/home/foo" is equivalent to "/home/foo:home/foo".
   370  //
   371  // ParseExtraFiles will also add ldd-listed dependencies if lddDeps is true.
   372  func ParseExtraFiles(logger logger.Logger, archive *initramfs.Files, extraFiles []string, lddDeps bool) error {
   373  	var err error
   374  	// Add files from command line.
   375  	for _, file := range extraFiles {
   376  		var src, dst string
   377  		parts := strings.SplitN(file, ":", 2)
   378  		if len(parts) == 2 {
   379  			// treat the entry with the new src:dst syntax
   380  			src = filepath.Clean(parts[0])
   381  			dst = filepath.Clean(parts[1])
   382  		} else {
   383  			// plain old syntax
   384  			// filepath.Clean interprets an empty string as CWD for no good reason.
   385  			if len(file) == 0 {
   386  				continue
   387  			}
   388  			src = filepath.Clean(file)
   389  			dst = src
   390  			if filepath.IsAbs(dst) {
   391  				dst, err = filepath.Rel("/", dst)
   392  				if err != nil {
   393  					return fmt.Errorf("cannot make path relative to /: %v: %v", dst, err)
   394  				}
   395  			}
   396  		}
   397  		src, err := filepath.Abs(src)
   398  		if err != nil {
   399  			return fmt.Errorf("couldn't find absolute path for %q: %v", src, err)
   400  		}
   401  		if err := archive.AddFileNoFollow(src, dst); err != nil {
   402  			return fmt.Errorf("couldn't add %q to archive: %v", file, err)
   403  		}
   404  
   405  		if lddDeps {
   406  			// Pull dependencies in the case of binaries. If `path` is not
   407  			// a binary, `libs` will just be empty.
   408  			libs, err := ldd.List([]string{src})
   409  			if err != nil {
   410  				logger.Printf("WARNING: couldn't add ldd dependencies for %q: %v", file, err)
   411  				continue
   412  			}
   413  			for _, lib := range libs {
   414  				// N.B.: we already added information about the src.
   415  				// Don't add it twice. We have to do this check here in
   416  				// case we're renaming the src to a different dest.
   417  				if lib == src {
   418  					continue
   419  				}
   420  				if err := archive.AddFileNoFollow(lib, lib[1:]); err != nil {
   421  					logger.Printf("WARNING: couldn't add ldd dependencies for %q: %v", lib, err)
   422  				}
   423  			}
   424  		}
   425  	}
   426  	return nil
   427  }
   428  
   429  // AddCommands adds commands to the build.
   430  func (o *Opts) AddCommands(c ...Commands) {
   431  	o.Commands = append(o.Commands, c...)
   432  }
   433  
   434  func (o *Opts) AddBusyBoxCommands(pkgs ...string) {
   435  	for i, cmds := range o.Commands {
   436  		if cmds.Builder == builder.BusyBox {
   437  			o.Commands[i].Packages = append(cmds.Packages, pkgs...)
   438  			return
   439  		}
   440  	}
   441  
   442  	// Not found? Add first busybox.
   443  	o.AddCommands(BusyBoxCmds(pkgs...)...)
   444  }
   445  
   446  // BinaryCmds returns a list of Commands with cmds built as a busybox.
   447  func BinaryCmds(cmds ...string) []Commands {
   448  	if len(cmds) == 0 {
   449  		return nil
   450  	}
   451  	return []Commands{
   452  		{
   453  			Builder:  builder.Binary,
   454  			Packages: cmds,
   455  		},
   456  	}
   457  }
   458  
   459  // BusyBoxCmds returns a list of Commands with cmds built as a busybox.
   460  func BusyBoxCmds(cmds ...string) []Commands {
   461  	if len(cmds) == 0 {
   462  		return nil
   463  	}
   464  	return []Commands{
   465  		{
   466  			Builder:  builder.BusyBox,
   467  			Packages: cmds,
   468  		},
   469  	}
   470  }