handle_linux.go 2.1 KB

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