conncheck.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. // +build !windows,!appengine
  9. package mysql
  10. import (
  11. "errors"
  12. "io"
  13. "net"
  14. "syscall"
  15. )
  16. var errUnexpectedRead = errors.New("unexpected read from socket")
  17. func connCheck(conn net.Conn) error {
  18. var sysErr error
  19. sysConn, ok := conn.(syscall.Conn)
  20. if !ok {
  21. return nil
  22. }
  23. rawConn, err := sysConn.SyscallConn()
  24. if err != nil {
  25. return err
  26. }
  27. err = rawConn.Read(func(fd uintptr) bool {
  28. var buf [1]byte
  29. n, err := syscall.Read(int(fd), buf[:])
  30. switch {
  31. case n == 0 && err == nil:
  32. sysErr = io.EOF
  33. case n > 0:
  34. sysErr = errUnexpectedRead
  35. case err == syscall.EAGAIN || err == syscall.EWOULDBLOCK:
  36. sysErr = nil
  37. default:
  38. sysErr = err
  39. }
  40. return true
  41. })
  42. if err != nil {
  43. return err
  44. }
  45. return sysErr
  46. }