archive_unix.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // +build !windows
  2. package chrootarchive
  3. import (
  4. "bytes"
  5. "encoding/json"
  6. "flag"
  7. "fmt"
  8. "io"
  9. "os"
  10. "runtime"
  11. "syscall"
  12. "github.com/docker/docker/pkg/archive"
  13. "github.com/docker/docker/pkg/reexec"
  14. )
  15. func chroot(path string) error {
  16. if err := syscall.Chroot(path); err != nil {
  17. return err
  18. }
  19. return syscall.Chdir("/")
  20. }
  21. // untar is the entry-point for docker-untar on re-exec. This is not used on
  22. // Windows as it does not support chroot, hence no point sandboxing through
  23. // chroot and rexec.
  24. func untar() {
  25. runtime.LockOSThread()
  26. flag.Parse()
  27. var options *archive.TarOptions
  28. //read the options from the pipe "ExtraFiles"
  29. if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&options); err != nil {
  30. fatal(err)
  31. }
  32. if err := chroot(flag.Arg(0)); err != nil {
  33. fatal(err)
  34. }
  35. if err := archive.Unpack(os.Stdin, "/", options); err != nil {
  36. fatal(err)
  37. }
  38. // fully consume stdin in case it is zero padded
  39. flush(os.Stdin)
  40. os.Exit(0)
  41. }
  42. func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.TarOptions) error {
  43. // We can't pass a potentially large exclude list directly via cmd line
  44. // because we easily overrun the kernel's max argument/environment size
  45. // when the full image list is passed (e.g. when this is used by
  46. // `docker load`). We will marshall the options via a pipe to the
  47. // child
  48. r, w, err := os.Pipe()
  49. if err != nil {
  50. return fmt.Errorf("Untar pipe failure: %v", err)
  51. }
  52. cmd := reexec.Command("docker-untar", dest)
  53. cmd.Stdin = decompressedArchive
  54. cmd.ExtraFiles = append(cmd.ExtraFiles, r)
  55. output := bytes.NewBuffer(nil)
  56. cmd.Stdout = output
  57. cmd.Stderr = output
  58. if err := cmd.Start(); err != nil {
  59. return fmt.Errorf("Untar error on re-exec cmd: %v", err)
  60. }
  61. //write the options to the pipe for the untar exec to read
  62. if err := json.NewEncoder(w).Encode(options); err != nil {
  63. return fmt.Errorf("Untar json encode to pipe failed: %v", err)
  64. }
  65. w.Close()
  66. if err := cmd.Wait(); err != nil {
  67. return fmt.Errorf("Untar re-exec error: %v: output: %s", err, output)
  68. }
  69. return nil
  70. }