github.com/oweisse/u-root@v0.0.0-20181109060735-d005ad25fef1/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.
   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 logger.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 logger.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  
   263  			// Only match directories for building.
   264  			// Skip anything that is not a directory
   265  			fileInfo, _ := os.Stat(match)
   266  			if !fileInfo.IsDir() {
   267  				continue
   268  			}
   269  
   270  			p, err := env.PackageByPath(match)
   271  			if err != nil {
   272  				logger.Printf("Skipping package %q: %v", match, err)
   273  			} else if p.ImportPath == "." {
   274  				// TODO: I do not completely understand why
   275  				// this is triggered. This is only an issue
   276  				// while this function is run inside the
   277  				// process of a "go test".
   278  				importPaths = append(importPaths, pkg)
   279  			} else {
   280  				importPaths = append(importPaths, p.ImportPath)
   281  			}
   282  		}
   283  		return importPaths, nil
   284  	}
   285  
   286  	// No file import paths found. Check if pkg still resolves as a package name.
   287  	if _, err := env.Package(pkg); err != nil {
   288  		return nil, fmt.Errorf("%q is neither package or path/glob: %v", pkg, err)
   289  	}
   290  	return []string{pkg}, nil
   291  }
   292  
   293  func resolveCommandOrPath(cmd string, cmds []Commands) (string, error) {
   294  	if filepath.IsAbs(cmd) {
   295  		return cmd, nil
   296  	}
   297  
   298  	for _, c := range cmds {
   299  		for _, p := range c.Packages {
   300  			// Figure out which build mode the shell is in, and symlink to
   301  			// that build modee
   302  			if name := path.Base(p); name == cmd {
   303  				return path.Join("/", c.TargetDir(), cmd), nil
   304  			}
   305  		}
   306  	}
   307  
   308  	return "", fmt.Errorf("command or path %q not included in u-root build", cmd)
   309  }
   310  
   311  // ResolvePackagePaths takes a list of Go package import paths and directories
   312  // and turns them into exclusively import paths.
   313  //
   314  // Currently allowed formats:
   315  //
   316  //   - package imports; e.g. github.com/u-root/u-root/cmds/ls
   317  //   - globs of package imports, e.g. github.com/u-root/u-root/cmds/*
   318  //   - paths to package directories; e.g. $GOPATH/src/github.com/u-root/u-root/cmds/ls
   319  //   - globs of paths to package directories; e.g. ./cmds/*
   320  //
   321  // Directories may be relative or absolute, with or without globs.
   322  // Globs are resolved using filepath.Glob.
   323  func ResolvePackagePaths(logger logger.Logger, env golang.Environ, pkgs []string) ([]string, error) {
   324  	var importPaths []string
   325  	for _, pkg := range pkgs {
   326  		paths, err := resolvePackagePath(logger, env, pkg)
   327  		if err != nil {
   328  			return nil, err
   329  		}
   330  		importPaths = append(importPaths, paths...)
   331  	}
   332  	return importPaths, nil
   333  }
   334  
   335  // ParseExtraFiles adds files from the extraFiles list to the archive.
   336  //
   337  // The following formats are allowed in the extraFiles list:
   338  //
   339  //   - "/home/chrisko/foo:root/bar" adds the file from absolute path
   340  //     /home/chrisko/foo on the host at the relative root/bar in the
   341  //     archive.
   342  //   - "/home/foo" is equivalent to "/home/foo:home/foo".
   343  //
   344  // ParseExtraFiles will also add ldd-listed dependencies if lddDeps is true.
   345  func ParseExtraFiles(logger logger.Logger, archive *initramfs.Files, extraFiles []string, lddDeps bool) error {
   346  	var err error
   347  	// Add files from command line.
   348  	for _, file := range extraFiles {
   349  		var src, dst string
   350  		parts := strings.SplitN(file, ":", 2)
   351  		if len(parts) == 2 {
   352  			// treat the entry with the new src:dst syntax
   353  			src = filepath.Clean(parts[0])
   354  			dst = filepath.Clean(parts[1])
   355  		} else {
   356  			// plain old syntax
   357  			// filepath.Clean interprets an empty string as CWD for no good reason.
   358  			if len(file) == 0 {
   359  				continue
   360  			}
   361  			src = filepath.Clean(file)
   362  			dst = src
   363  			if filepath.IsAbs(dst) {
   364  				dst, err = filepath.Rel("/", dst)
   365  				if err != nil {
   366  					return fmt.Errorf("cannot make path relative to /: %v: %v", dst, err)
   367  				}
   368  			}
   369  		}
   370  		src, err := filepath.Abs(src)
   371  		if err != nil {
   372  			return fmt.Errorf("couldn't find absolute path for %q: %v", src, err)
   373  		}
   374  		if err := archive.AddFileNoFollow(src, dst); err != nil {
   375  			return fmt.Errorf("couldn't add %q to archive: %v", file, err)
   376  		}
   377  
   378  		if lddDeps {
   379  			// Pull dependencies in the case of binaries. If `path` is not
   380  			// a binary, `libs` will just be empty.
   381  			libs, err := ldd.List([]string{src})
   382  			if err != nil {
   383  				logger.Printf("WARNING: couldn't add ldd dependencies for %q: %v", file, err)
   384  				continue
   385  			}
   386  			for _, lib := range libs {
   387  				if err := archive.AddFileNoFollow(lib, lib[1:]); err != nil {
   388  					logger.Printf("WARNING: couldn't add ldd dependencies for %q: %v", lib, err)
   389  				}
   390  			}
   391  		}
   392  	}
   393  	return nil
   394  }