archive_unix.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. flush(os.Stdin)
  41. os.Exit(0)
  42. }
  43. func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.TarOptions) error {
  44. // We can't pass a potentially large exclude list directly via cmd line
  45. // because we easily overrun the kernel's max argument/environment size
  46. // when the full image list is passed (e.g. when this is used by
  47. // `docker load`). We will marshall the options via a pipe to the
  48. // child
  49. r, w, err := os.Pipe()
  50. if err != nil {
  51. return fmt.Errorf("Untar pipe failure: %v", err)
  52. }
  53. cmd := reexec.Command("docker-untar", dest)
  54. cmd.Stdin = decompressedArchive
  55. cmd.ExtraFiles = append(cmd.ExtraFiles, r)
  56. output := bytes.NewBuffer(nil)
  57. cmd.Stdout = output
  58. cmd.Stderr = output
  59. if err := cmd.Start(); err != nil {
  60. return fmt.Errorf("Untar error on re-exec cmd: %v", err)
  61. }
  62. //write the options to the pipe for the untar exec to read
  63. if err := json.NewEncoder(w).Encode(options); err != nil {
  64. return fmt.Errorf("Untar json encode to pipe failed: %v", err)
  65. }
  66. w.Close()
  67. if err := cmd.Wait(); err != nil {
  68. // when `xz -d -c -q | docker-untar ...` failed on docker-untar side,
  69. // we need to exhaust `xz`'s output, otherwise the `xz` side will be
  70. // pending on write pipe forever
  71. io.Copy(ioutil.Discard, decompressedArchive)
  72. return fmt.Errorf("Untar re-exec error: %v: output: %s", err, output)
  73. }
  74. return nil
  75. }