syscallconn.go 1.8 KB

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