archive_unix.go 2.3 KB

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