gopkg.in/hugelgupf/u-root.v4@v4.0.0-20180831060141-1d761fb73d50/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.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 or 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 packages to compile and add to the archive.
    65  	//
    66  	// Currently allowed formats:
    67  	//
    68  	//   - package imports; e.g. github.com/u-root/u-root/cmds/ls
    69  	//   - globs of package imports; e.g. github.com/u-root/u-root/cmds/*
    70  	//   - paths to package directories; e.g. $GOPATH/src/github.com/u-root/u-root/cmds/ls
    71  	//   - globs of paths to package directories; e.g. ./cmds/*
    72  	//
    73  	// Directories may be relative or absolute, with or without globs.
    74  	// Globs are resolved using filepath.Glob.
    75  	Packages []string
    76  
    77  	// BinaryDir is the directory in which the resulting binaries are
    78  	// placed inside the initramfs.
    79  	BinaryDir string
    80  }
    81  
    82  // TargetDir returns the initramfs binary directory for these Commands.
    83  func (c Commands) TargetDir() string {
    84  	if len(c.BinaryDir) != 0 {
    85  		return c.BinaryDir
    86  	}
    87  	return c.Builder.DefaultBinaryDir()
    88  }
    89  
    90  // Opts are the arguments to CreateInitramfs.
    91  //
    92  // Opts contains everything that influences initramfs creation such as the Go
    93  // build environment.
    94  //
    95  //
    96  type Opts struct {
    97  	// Env is the Golang build environment (GOOS, GOARCH, etc).
    98  	Env golang.Environ
    99  
   100  	// Commands specify packages to build using a specific builder.
   101  	Commands []Commands
   102  
   103  	// TempDir is a temporary directory for builders to store files in.
   104  	TempDir string
   105  
   106  	// ExtraFiles are files to add to the archive in addition to the Go
   107  	// packages.
   108  	//
   109  	// Shared library dependencies will automatically also be added to the
   110  	// archive using ldd.
   111  	ExtraFiles []string
   112  
   113  	// OutputFile is the archive output file.
   114  	OutputFile initramfs.Writer
   115  
   116  	// BaseArchive is an existing initramfs to include in the resulting
   117  	// initramfs.
   118  	BaseArchive initramfs.Reader
   119  
   120  	// UseExistingInit determines whether the existing init from
   121  	// BaseArchive should be used.
   122  	//
   123  	// If this is false, the "init" from BaseArchive will be renamed to
   124  	// "inito".
   125  	UseExistingInit bool
   126  
   127  	// InitCmd is the name of a command to link /init to.
   128  	//
   129  	// This can be an absolute path or the name of a command included in
   130  	// Commands.
   131  	//
   132  	// If this is empty, no init symlink will be created.
   133  	InitCmd string
   134  
   135  	// DefaultShell is the default shell to start after init.
   136  	//
   137  	// This can be an absolute path or the name of a command included in
   138  	// Commands.
   139  	//
   140  	// This must be specified to have a default shell.
   141  	DefaultShell string
   142  }
   143  
   144  // CreateInitramfs creates an initramfs built to opts' specifications.
   145  func CreateInitramfs(opts Opts) error {
   146  	if _, err := os.Stat(opts.TempDir); os.IsNotExist(err) {
   147  		return fmt.Errorf("temp dir %q must exist: %v", opts.TempDir, err)
   148  	}
   149  	if opts.OutputFile == nil {
   150  		return fmt.Errorf("must give output file")
   151  	}
   152  
   153  	files := initramfs.NewFiles()
   154  
   155  	// Expand commands.
   156  	for index, cmds := range opts.Commands {
   157  		importPaths, err := ResolvePackagePaths(opts.Env, cmds.Packages)
   158  		if err != nil {
   159  			return err
   160  		}
   161  		opts.Commands[index].Packages = importPaths
   162  	}
   163  
   164  	// Add each build mode's commands to the archive.
   165  	for _, cmds := range opts.Commands {
   166  		builderTmpDir, err := ioutil.TempDir(opts.TempDir, "builder")
   167  		if err != nil {
   168  			return err
   169  		}
   170  
   171  		// Build packages.
   172  		bOpts := builder.Opts{
   173  			Env:       opts.Env,
   174  			Packages:  cmds.Packages,
   175  			TempDir:   builderTmpDir,
   176  			BinaryDir: cmds.TargetDir(),
   177  		}
   178  		if err := cmds.Builder.Build(files, bOpts); err != nil {
   179  			return fmt.Errorf("error building %#v: %v", bOpts, err)
   180  		}
   181  	}
   182  
   183  	// Open the target initramfs file.
   184  	archive := initramfs.Opts{
   185  		Files:           files,
   186  		OutputFile:      opts.OutputFile,
   187  		BaseArchive:     opts.BaseArchive,
   188  		UseExistingInit: opts.UseExistingInit,
   189  		DefaultRecords:  DefaultRamfs,
   190  	}
   191  
   192  	if len(opts.DefaultShell) > 0 {
   193  		if target, err := resolveCommandOrPath(opts.DefaultShell, opts.Commands); err != nil {
   194  			log.Printf("No default shell: %v", err)
   195  		} else if err := archive.AddRecord(cpio.Symlink("bin/defaultsh", target)); err != nil {
   196  			return err
   197  		}
   198  	}
   199  
   200  	if len(opts.InitCmd) > 0 {
   201  		if target, err := resolveCommandOrPath(opts.InitCmd, opts.Commands); err != nil {
   202  			return fmt.Errorf("could not find init: %v", err)
   203  		} else if err := archive.AddRecord(cpio.Symlink("init", target)); err != nil {
   204  			return err
   205  		}
   206  	}
   207  
   208  	if err := ParseExtraFiles(archive.Files, opts.ExtraFiles, true); err != nil {
   209  		return err
   210  	}
   211  
   212  	// Finally, write the archive.
   213  	if err := initramfs.Write(&archive); err != nil {
   214  		return fmt.Errorf("error archiving: %v", err)
   215  	}
   216  	return nil
   217  }
   218  
   219  // resolvePackagePath finds import paths for a single import path or directory string
   220  func resolvePackagePath(env golang.Environ, pkg string) ([]string, error) {
   221  	// Search the current working directory, as well GOROOT and GOPATHs
   222  	prefixes := append([]string{""}, env.SrcDirs()...)
   223  	// Resolve file system paths to package import paths.
   224  	for _, prefix := range prefixes {
   225  		path := filepath.Join(prefix, pkg)
   226  		matches, err := filepath.Glob(path)
   227  		if len(matches) == 0 || err != nil {
   228  			continue
   229  		}
   230  
   231  		var importPaths []string
   232  		for _, match := range matches {
   233  			p, err := env.PackageByPath(match)
   234  			if err != nil {
   235  				log.Printf("Skipping package %q: %v", match, err)
   236  			} else if p.ImportPath == "." {
   237  				// TODO: I do not completely understand why
   238  				// this is triggered. This is only an issue
   239  				// while this function is run inside the
   240  				// process of a "go test".
   241  				importPaths = append(importPaths, pkg)
   242  			} else {
   243  				importPaths = append(importPaths, p.ImportPath)
   244  			}
   245  		}
   246  		return importPaths, nil
   247  	}
   248  
   249  	// No file import paths found. Check if pkg still resolves as a package name.
   250  	if _, err := env.Package(pkg); err != nil {
   251  		return nil, fmt.Errorf("%q is neither package or path/glob: %v", pkg, err)
   252  	}
   253  	return []string{pkg}, nil
   254  }
   255  
   256  func resolveCommandOrPath(cmd string, cmds []Commands) (string, error) {
   257  	if filepath.IsAbs(cmd) {
   258  		return cmd, nil
   259  	}
   260  
   261  	for _, c := range cmds {
   262  		for _, p := range c.Packages {
   263  			// Figure out which build mode the shell is in, and symlink to
   264  			// that build modee
   265  			if name := path.Base(p); name == cmd {
   266  				return path.Join("/", c.TargetDir(), cmd), nil
   267  			}
   268  		}
   269  	}
   270  
   271  	return "", fmt.Errorf("command or path %q not included in u-root build", cmd)
   272  }
   273  
   274  // ResolvePackagePaths takes a list of Go package import paths and directories
   275  // and turns them into exclusively import paths.
   276  //
   277  // Currently allowed formats:
   278  //
   279  //   - package imports; e.g. github.com/u-root/u-root/cmds/ls
   280  //   - globs of package imports, e.g. github.com/u-root/u-root/cmds/*
   281  //   - paths to package directories; e.g. $GOPATH/src/github.com/u-root/u-root/cmds/ls
   282  //   - globs of paths to package directories; e.g. ./cmds/*
   283  //
   284  // Directories may be relative or absolute, with or without globs.
   285  // Globs are resolved using filepath.Glob.
   286  func ResolvePackagePaths(env golang.Environ, pkgs []string) ([]string, error) {
   287  	var importPaths []string
   288  	for _, pkg := range pkgs {
   289  		paths, err := resolvePackagePath(env, pkg)
   290  		if err != nil {
   291  			return nil, err
   292  		}
   293  		importPaths = append(importPaths, paths...)
   294  	}
   295  	return importPaths, nil
   296  }
   297  
   298  // ParseExtraFiles adds files from the extraFiles list to the archive.
   299  //
   300  // The following formats are allowed in the extraFiles list:
   301  //
   302  //   - hostPath:archivePath adds the file from hostPath at the relative
   303  //     archivePath in the archive.
   304  //   - justAPath is added to the archive under justAPath.
   305  //
   306  // ParseExtraFiles will also add ldd-listed dependencies if lddDeps is true.
   307  func ParseExtraFiles(archive initramfs.Files, extraFiles []string, lddDeps bool) error {
   308  	var err error
   309  	// Add files from command line.
   310  	for _, file := range extraFiles {
   311  		var src, dst string
   312  		parts := strings.SplitN(file, ":", 2)
   313  		if len(parts) == 2 {
   314  			// treat the entry with the new src:dst syntax
   315  			src = filepath.Clean(parts[0])
   316  			dst = filepath.Clean(parts[1])
   317  		} else {
   318  			// plain old syntax
   319  			// filepath.Clean interprets an empty string as CWD for no good reason.
   320  			if len(file) == 0 {
   321  				continue
   322  			}
   323  			src = filepath.Clean(file)
   324  			dst = src
   325  			if filepath.IsAbs(dst) {
   326  				dst, err = filepath.Rel("/", dst)
   327  				if err != nil {
   328  					return fmt.Errorf("cannot make path relative to /: %v: %v", dst, err)
   329  				}
   330  			}
   331  		}
   332  		src, err := filepath.Abs(src)
   333  		if err != nil {
   334  			return fmt.Errorf("couldn't find absolute path for %q: %v", src, err)
   335  		}
   336  		if err := archive.AddFile(src, dst); err != nil {
   337  			return fmt.Errorf("couldn't add %q to archive: %v", file, err)
   338  		}
   339  
   340  		if lddDeps {
   341  			// Pull dependencies in the case of binaries. If `path` is not
   342  			// a binary, `libs` will just be empty.
   343  			libs, err := ldd.List([]string{src})
   344  			if err != nil {
   345  				log.Printf("WARNING: couldn't add ldd dependencies for %q: %v", file, err)
   346  				return nil
   347  			}
   348  			for _, lib := range libs {
   349  				if err := archive.AddFile(lib, lib[1:]); err != nil {
   350  					log.Printf("WARNING: couldn't add ldd dependencies for %q: %v", lib, err)
   351  				}
   352  			}
   353  		}
   354  	}
   355  	return nil
   356  }