syscallconn.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package credentials
  19. import (
  20. "net"
  21. "syscall"
  22. )
  23. type sysConn = syscall.Conn
  24. // syscallConn keeps reference of rawConn to support syscall.Conn for channelz.
  25. // SyscallConn() (the method in interface syscall.Conn) is explicitly
  26. // implemented on this type,
  27. //
  28. // Interface syscall.Conn is implemented by most net.Conn implementations (e.g.
  29. // TCPConn, UnixConn), but is not part of net.Conn interface. So wrapper conns
  30. // that embed net.Conn don't implement syscall.Conn. (Side note: tls.Conn
  31. // doesn't embed net.Conn, so even if syscall.Conn is part of net.Conn, it won't
  32. // help here).
  33. type syscallConn struct {
  34. net.Conn
  35. // sysConn is a type alias of syscall.Conn. It's necessary because the name
  36. // `Conn` collides with `net.Conn`.
  37. sysConn
  38. }
  39. // WrapSyscallConn tries to wrap rawConn and newConn into a net.Conn that
  40. // implements syscall.Conn. rawConn will be used to support syscall, and newConn
  41. // will be used for read/write.
  42. //
  43. // This function returns newConn if rawConn doesn't implement syscall.Conn.
  44. func WrapSyscallConn(rawConn, newConn net.Conn) net.Conn {
  45. sysConn, ok := rawConn.(syscall.Conn)
  46. if !ok {
  47. return newConn
  48. }
  49. return &syscallConn{
  50. Conn: newConn,
  51. sysConn: sysConn,
  52. }
  53. }