github.com/mem/u-root@v2.0.1-0.20181004165302-9b18b4636a33+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  	"log"
    11  	"os"
    12  	"path"
    13  	"path/filepath"
    14  	"strings"
    15  
    16  	"github.com/u-root/u-root/pkg/cpio"
    17  	"github.com/u-root/u-root/pkg/golang"
    18  	"github.com/u-root/u-root/pkg/ldd"
    19  	"github.com/u-root/u-root/pkg/uroot/builder"
    20  	"github.com/u-root/u-root/pkg/uroot/initramfs"
    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.
   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  	// OutputFile is the archive output file.
   144  	OutputFile initramfs.Writer
   145  
   146  	// BaseArchive is an existing initramfs to include in the resulting
   147  	// initramfs.
   148  	BaseArchive initramfs.Reader
   149  
   150  	// UseExistingInit determines whether the existing init from
   151  	// BaseArchive should be used.
   152  	//
   153  	// If this is false, the "init" from BaseArchive will be renamed to
   154  	// "inito" (init-original).
   155  	UseExistingInit bool
   156  
   157  	// InitCmd is the name of a command to link /init to.
   158  	//
   159  	// This can be an absolute path or the name of a command included in
   160  	// Commands.
   161  	//
   162  	// If this is empty, no init symlink will be created.
   163  	InitCmd string
   164  
   165  	// DefaultShell is the default shell to start after init.
   166  	//
   167  	// This can be an absolute path or the name of a command included in
   168  	// Commands.
   169  	//
   170  	// This must be specified to have a default shell.
   171  	DefaultShell string
   172  }
   173  
   174  // CreateInitramfs creates an initramfs built to opts' specifications.
   175  func CreateInitramfs(logger *log.Logger, opts Opts) error {
   176  	if _, err := os.Stat(opts.TempDir); os.IsNotExist(err) {
   177  		return fmt.Errorf("temp dir %q must exist: %v", opts.TempDir, err)
   178  	}
   179  	if opts.OutputFile == nil {
   180  		return fmt.Errorf("must give output file")
   181  	}
   182  
   183  	files := initramfs.NewFiles()
   184  
   185  	// Expand commands.
   186  	for index, cmds := range opts.Commands {
   187  		importPaths, err := ResolvePackagePaths(logger, opts.Env, cmds.Packages)
   188  		if err != nil {
   189  			return err
   190  		}
   191  		opts.Commands[index].Packages = importPaths
   192  	}
   193  
   194  	// Add each build mode's commands to the archive.
   195  	for _, cmds := range opts.Commands {
   196  		builderTmpDir, err := ioutil.TempDir(opts.TempDir, "builder")
   197  		if err != nil {
   198  			return err
   199  		}
   200  
   201  		// Build packages.
   202  		bOpts := builder.Opts{
   203  			Env:       opts.Env,
   204  			Packages:  cmds.Packages,
   205  			TempDir:   builderTmpDir,
   206  			BinaryDir: cmds.TargetDir(),
   207  		}
   208  		if err := cmds.Builder.Build(files, bOpts); err != nil {
   209  			return fmt.Errorf("error building %#v: %v", bOpts, err)
   210  		}
   211  	}
   212  
   213  	// Open the target initramfs file.
   214  	archive := initramfs.Opts{
   215  		Files:           files,
   216  		OutputFile:      opts.OutputFile,
   217  		BaseArchive:     opts.BaseArchive,
   218  		UseExistingInit: opts.UseExistingInit,
   219  	}
   220  
   221  	if len(opts.DefaultShell) > 0 {
   222  		if target, err := resolveCommandOrPath(opts.DefaultShell, opts.Commands); err != nil {
   223  			logger.Printf("No default shell: %v", err)
   224  		} else if err := archive.AddRecord(cpio.Symlink("bin/defaultsh", target)); err != nil {
   225  			return err
   226  		}
   227  	}
   228  
   229  	if len(opts.InitCmd) > 0 {
   230  		if target, err := resolveCommandOrPath(opts.InitCmd, opts.Commands); err != nil {
   231  			return fmt.Errorf("could not find init: %v", err)
   232  		} else if err := archive.AddRecord(cpio.Symlink("init", target)); err != nil {
   233  			return err
   234  		}
   235  	}
   236  
   237  	if err := ParseExtraFiles(logger, archive.Files, opts.ExtraFiles, true); err != nil {
   238  		return err
   239  	}
   240  
   241  	// Finally, write the archive.
   242  	if err := initramfs.Write(&archive); err != nil {
   243  		return fmt.Errorf("error archiving: %v", err)
   244  	}
   245  	return nil
   246  }
   247  
   248  // resolvePackagePath finds import paths for a single import path or directory string
   249  func resolvePackagePath(logger *log.Logger, env golang.Environ, pkg string) ([]string, error) {
   250  	// Search the current working directory, as well GOROOT and GOPATHs
   251  	prefixes := append([]string{""}, env.SrcDirs()...)
   252  	// Resolve file system paths to package import paths.
   253  	for _, prefix := range prefixes {
   254  		path := filepath.Join(prefix, pkg)
   255  		matches, err := filepath.Glob(path)
   256  		if len(matches) == 0 || err != nil {
   257  			continue
   258  		}
   259  
   260  		var importPaths []string
   261  		for _, match := range matches {
   262  			p, err := env.PackageByPath(match)
   263  			if err != nil {
   264  				logger.Printf("Skipping package %q: %v", match, err)
   265  			} else if p.ImportPath == "." {
   266  				// TODO: I do not completely understand why
   267  				// this is triggered. This is only an issue
   268  				// while this function is run inside the
   269  				// process of a "go test".
   270  				importPaths = append(importPaths, pkg)
   271  			} else {
   272  				importPaths = append(importPaths, p.ImportPath)
   273  			}
   274  		}
   275  		return importPaths, nil
   276  	}
   277  
   278  	// No file import paths found. Check if pkg still resolves as a package name.
   279  	if _, err := env.Package(pkg); err != nil {
   280  		return nil, fmt.Errorf("%q is neither package or path/glob: %v", pkg, err)
   281  	}
   282  	return []string{pkg}, nil
   283  }
   284  
   285  func resolveCommandOrPath(cmd string, cmds []Commands) (string, error) {
   286  	if filepath.IsAbs(cmd) {
   287  		return cmd, nil
   288  	}
   289  
   290  	for _, c := range cmds {
   291  		for _, p := range c.Packages {
   292  			// Figure out which build mode the shell is in, and symlink to
   293  			// that build modee
   294  			if name := path.Base(p); name == cmd {
   295  				return path.Join("/", c.TargetDir(), cmd), nil
   296  			}
   297  		}
   298  	}
   299  
   300  	return "", fmt.Errorf("command or path %q not included in u-root build", cmd)
   301  }
   302  
   303  // ResolvePackagePaths takes a list of Go package import paths and directories
   304  // and turns them into exclusively import paths.
   305  //
   306  // Currently allowed formats:
   307  //
   308  //   - package imports; e.g. github.com/u-root/u-root/cmds/ls
   309  //   - globs of package imports, e.g. github.com/u-root/u-root/cmds/*
   310  //   - paths to package directories; e.g. $GOPATH/src/github.com/u-root/u-root/cmds/ls
   311  //   - globs of paths to package directories; e.g. ./cmds/*
   312  //
   313  // Directories may be relative or absolute, with or without globs.
   314  // Globs are resolved using filepath.Glob.
   315  func ResolvePackagePaths(logger *log.Logger, env golang.Environ, pkgs []string) ([]string, error) {
   316  	var importPaths []string
   317  	for _, pkg := range pkgs {
   318  		paths, err := resolvePackagePath(logger, env, pkg)
   319  		if err != nil {
   320  			return nil, err
   321  		}
   322  		importPaths = append(importPaths, paths...)
   323  	}
   324  	return importPaths, nil
   325  }
   326  
   327  // ParseExtraFiles adds files from the extraFiles list to the archive.
   328  //
   329  // The following formats are allowed in the extraFiles list:
   330  //
   331  //   - "/home/chrisko/foo:root/bar" adds the file from absolute path
   332  //     /home/chrisko/foo on the host at the relative root/bar in the
   333  //     archive.
   334  //   - "/home/foo" is equivalent to "/home/foo:home/foo".
   335  //
   336  // ParseExtraFiles will also add ldd-listed dependencies if lddDeps is true.
   337  func ParseExtraFiles(logger *log.Logger, archive *initramfs.Files, extraFiles []string, lddDeps bool) error {
   338  	var err error
   339  	// Add files from command line.
   340  	for _, file := range extraFiles {
   341  		var src, dst string
   342  		parts := strings.SplitN(file, ":", 2)
   343  		if len(parts) == 2 {
   344  			// treat the entry with the new src:dst syntax
   345  			src = filepath.Clean(parts[0])
   346  			dst = filepath.Clean(parts[1])
   347  		} else {
   348  			// plain old syntax
   349  			// filepath.Clean interprets an empty string as CWD for no good reason.
   350  			if len(file) == 0 {
   351  				continue
   352  			}
   353  			src = filepath.Clean(file)
   354  			dst = src
   355  			if filepath.IsAbs(dst) {
   356  				dst, err = filepath.Rel("/", dst)
   357  				if err != nil {
   358  					return fmt.Errorf("cannot make path relative to /: %v: %v", dst, err)
   359  				}
   360  			}
   361  		}
   362  		src, err := filepath.Abs(src)
   363  		if err != nil {
   364  			return fmt.Errorf("couldn't find absolute path for %q: %v", src, err)
   365  		}
   366  		if err := archive.AddFile(src, dst); err != nil {
   367  			return fmt.Errorf("couldn't add %q to archive: %v", file, err)
   368  		}
   369  
   370  		if lddDeps {
   371  			// Pull dependencies in the case of binaries. If `path` is not
   372  			// a binary, `libs` will just be empty.
   373  			libs, err := ldd.List([]string{src})
   374  			if err != nil {
   375  				logger.Printf("WARNING: couldn't add ldd dependencies for %q: %v", file, err)
   376  				continue
   377  			}
   378  			for _, lib := range libs {
   379  				if err := archive.AddFile(lib, lib[1:]); err != nil {
   380  					logger.Printf("WARNING: couldn't add ldd dependencies for %q: %v", lib, err)
   381  				}
   382  			}
   383  		}
   384  	}
   385  	return nil
   386  }