io_unix.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // +build !windows
  2. /*
  3. Copyright The containerd Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package runc
  15. import (
  16. "github.com/pkg/errors"
  17. "golang.org/x/sys/unix"
  18. )
  19. // NewPipeIO creates pipe pairs to be used with runc
  20. func NewPipeIO(uid, gid int, opts ...IOOpt) (i IO, err error) {
  21. option := defaultIOOption()
  22. for _, o := range opts {
  23. o(option)
  24. }
  25. var (
  26. pipes []*pipe
  27. stdin, stdout, stderr *pipe
  28. )
  29. // cleanup in case of an error
  30. defer func() {
  31. if err != nil {
  32. for _, p := range pipes {
  33. p.Close()
  34. }
  35. }
  36. }()
  37. if option.OpenStdin {
  38. if stdin, err = newPipe(); err != nil {
  39. return nil, err
  40. }
  41. pipes = append(pipes, stdin)
  42. if err = unix.Fchown(int(stdin.r.Fd()), uid, gid); err != nil {
  43. return nil, errors.Wrap(err, "failed to chown stdin")
  44. }
  45. }
  46. if option.OpenStdout {
  47. if stdout, err = newPipe(); err != nil {
  48. return nil, err
  49. }
  50. pipes = append(pipes, stdout)
  51. if err = unix.Fchown(int(stdout.w.Fd()), uid, gid); err != nil {
  52. return nil, errors.Wrap(err, "failed to chown stdout")
  53. }
  54. }
  55. if option.OpenStderr {
  56. if stderr, err = newPipe(); err != nil {
  57. return nil, err
  58. }
  59. pipes = append(pipes, stderr)
  60. if err = unix.Fchown(int(stderr.w.Fd()), uid, gid); err != nil {
  61. return nil, errors.Wrap(err, "failed to chown stderr")
  62. }
  63. }
  64. return &pipeIO{
  65. in: stdin,
  66. out: stdout,
  67. err: stderr,
  68. }, nil
  69. }