raw.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. //go: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 fifo
  15. import (
  16. "syscall"
  17. )
  18. // SyscallConn provides raw access to the fifo's underlying filedescrptor.
  19. // See syscall.Conn for guarantees provided by this interface.
  20. func (f *fifo) SyscallConn() (syscall.RawConn, error) {
  21. // deterministic check for closed
  22. select {
  23. case <-f.closed:
  24. return nil, ErrClosed
  25. default:
  26. }
  27. select {
  28. case <-f.closed:
  29. return nil, ErrClosed
  30. case <-f.opened:
  31. return f.file.SyscallConn()
  32. default:
  33. }
  34. // Not opened and not closed, this means open is non-blocking AND it's not open yet
  35. // Use rawConn to deal with non-blocking open.
  36. rc := &rawConn{f: f, ready: make(chan struct{})}
  37. go func() {
  38. select {
  39. case <-f.closed:
  40. return
  41. case <-f.opened:
  42. rc.raw, rc.err = f.file.SyscallConn()
  43. close(rc.ready)
  44. }
  45. }()
  46. return rc, nil
  47. }
  48. type rawConn struct {
  49. f *fifo
  50. ready chan struct{}
  51. raw syscall.RawConn
  52. err error
  53. }
  54. func (r *rawConn) Control(f func(fd uintptr)) error {
  55. select {
  56. case <-r.f.closed:
  57. return ErrCtrlClosed
  58. case <-r.ready:
  59. }
  60. if r.err != nil {
  61. return r.err
  62. }
  63. return r.raw.Control(f)
  64. }
  65. func (r *rawConn) Read(f func(fd uintptr) (done bool)) error {
  66. if r.f.flag&syscall.O_WRONLY > 0 {
  67. return ErrRdFrmWRONLY
  68. }
  69. select {
  70. case <-r.f.closed:
  71. return ErrReadClosed
  72. case <-r.ready:
  73. }
  74. if r.err != nil {
  75. return r.err
  76. }
  77. return r.raw.Read(f)
  78. }
  79. func (r *rawConn) Write(f func(fd uintptr) (done bool)) error {
  80. if r.f.flag&(syscall.O_WRONLY|syscall.O_RDWR) == 0 {
  81. return ErrWrToRDONLY
  82. }
  83. select {
  84. case <-r.f.closed:
  85. return ErrWriteClosed
  86. case <-r.ready:
  87. }
  88. if r.err != nil {
  89. return r.err
  90. }
  91. return r.raw.Write(f)
  92. }