handle_linux.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // +build linux
  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 fifo
  15. import (
  16. "fmt"
  17. "os"
  18. "sync"
  19. "syscall"
  20. "github.com/pkg/errors"
  21. )
  22. //nolint:golint
  23. const O_PATH = 010000000
  24. type handle struct {
  25. f *os.File
  26. fd uintptr
  27. dev uint64
  28. ino uint64
  29. closeOnce sync.Once
  30. name string
  31. }
  32. func getHandle(fn string) (*handle, error) {
  33. f, err := os.OpenFile(fn, O_PATH, 0)
  34. if err != nil {
  35. return nil, errors.Wrapf(err, "failed to open %v with O_PATH", fn)
  36. }
  37. var (
  38. stat syscall.Stat_t
  39. fd = f.Fd()
  40. )
  41. if err := syscall.Fstat(int(fd), &stat); err != nil {
  42. f.Close()
  43. return nil, errors.Wrapf(err, "failed to stat handle %v", fd)
  44. }
  45. h := &handle{
  46. f: f,
  47. name: fn,
  48. //nolint:unconvert
  49. dev: uint64(stat.Dev),
  50. ino: stat.Ino,
  51. fd: fd,
  52. }
  53. // check /proc just in case
  54. if _, err := os.Stat(h.procPath()); err != nil {
  55. f.Close()
  56. return nil, errors.Wrapf(err, "couldn't stat %v", h.procPath())
  57. }
  58. return h, nil
  59. }
  60. func (h *handle) procPath() string {
  61. return fmt.Sprintf("/proc/self/fd/%d", h.fd)
  62. }
  63. func (h *handle) Name() string {
  64. return h.name
  65. }
  66. func (h *handle) Path() (string, error) {
  67. var stat syscall.Stat_t
  68. if err := syscall.Stat(h.procPath(), &stat); err != nil {
  69. return "", errors.Wrapf(err, "path %v could not be statted", h.procPath())
  70. }
  71. //nolint:unconvert
  72. if uint64(stat.Dev) != h.dev || stat.Ino != h.ino {
  73. return "", errors.Errorf("failed to verify handle %v/%v %v/%v", stat.Dev, h.dev, stat.Ino, h.ino)
  74. }
  75. return h.procPath(), nil
  76. }
  77. func (h *handle) Close() error {
  78. h.closeOnce.Do(func() {
  79. h.f.Close()
  80. })
  81. return nil
  82. }