driver.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Package mysql provides a MySQL driver for Go's database/sql package.
  7. //
  8. // The driver should be used via the database/sql package:
  9. //
  10. // import "database/sql"
  11. // import _ "github.com/go-sql-driver/mysql"
  12. //
  13. // db, err := sql.Open("mysql", "user:password@/dbname")
  14. //
  15. // See https://github.com/go-sql-driver/mysql#usage for details
  16. package mysql
  17. import (
  18. "database/sql"
  19. "database/sql/driver"
  20. "net"
  21. "sync"
  22. )
  23. // watcher interface is used for context support (From Go 1.8)
  24. type watcher interface {
  25. startWatcher()
  26. }
  27. // MySQLDriver is exported to make the driver directly accessible.
  28. // In general the driver is used via the database/sql package.
  29. type MySQLDriver struct{}
  30. // DialFunc is a function which can be used to establish the network connection.
  31. // Custom dial functions must be registered with RegisterDial
  32. type DialFunc func(addr string) (net.Conn, error)
  33. var (
  34. dialsLock sync.RWMutex
  35. dials map[string]DialFunc
  36. )
  37. // RegisterDial registers a custom dial function. It can then be used by the
  38. // network address mynet(addr), where mynet is the registered new network.
  39. // addr is passed as a parameter to the dial function.
  40. func RegisterDial(net string, dial DialFunc) {
  41. dialsLock.Lock()
  42. defer dialsLock.Unlock()
  43. if dials == nil {
  44. dials = make(map[string]DialFunc)
  45. }
  46. dials[net] = dial
  47. }
  48. // Open new Connection.
  49. // See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how
  50. // the DSN string is formated
  51. func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {
  52. var err error
  53. // New mysqlConn
  54. mc := &mysqlConn{
  55. maxAllowedPacket: maxPacketSize,
  56. maxWriteSize: maxPacketSize - 1,
  57. closech: make(chan struct{}),
  58. }
  59. mc.cfg, err = ParseDSN(dsn)
  60. if err != nil {
  61. return nil, err
  62. }
  63. mc.parseTime = mc.cfg.ParseTime
  64. // Connect to Server
  65. dialsLock.RLock()
  66. dial, ok := dials[mc.cfg.Net]
  67. dialsLock.RUnlock()
  68. if ok {
  69. mc.netConn, err = dial(mc.cfg.Addr)
  70. } else {
  71. nd := net.Dialer{Timeout: mc.cfg.Timeout}
  72. mc.netConn, err = nd.Dial(mc.cfg.Net, mc.cfg.Addr)
  73. }
  74. if err != nil {
  75. return nil, err
  76. }
  77. // Enable TCP Keepalives on TCP connections
  78. if tc, ok := mc.netConn.(*net.TCPConn); ok {
  79. if err := tc.SetKeepAlive(true); err != nil {
  80. // Don't send COM_QUIT before handshake.
  81. mc.netConn.Close()
  82. mc.netConn = nil
  83. return nil, err
  84. }
  85. }
  86. // Call startWatcher for context support (From Go 1.8)
  87. if s, ok := interface{}(mc).(watcher); ok {
  88. s.startWatcher()
  89. }
  90. mc.buf = newBuffer(mc.netConn)
  91. // Set I/O timeouts
  92. mc.buf.timeout = mc.cfg.ReadTimeout
  93. mc.writeTimeout = mc.cfg.WriteTimeout
  94. // Reading Handshake Initialization Packet
  95. cipher, err := mc.readInitPacket()
  96. if err != nil {
  97. mc.cleanup()
  98. return nil, err
  99. }
  100. // Send Client Authentication Packet
  101. if err = mc.writeAuthPacket(cipher); err != nil {
  102. mc.cleanup()
  103. return nil, err
  104. }
  105. // Handle response to auth packet, switch methods if possible
  106. if err = handleAuthResult(mc, cipher); err != nil {
  107. // Authentication failed and MySQL has already closed the connection
  108. // (https://dev.mysql.com/doc/internals/en/authentication-fails.html).
  109. // Do not send COM_QUIT, just cleanup and return the error.
  110. mc.cleanup()
  111. return nil, err
  112. }
  113. if mc.cfg.MaxAllowedPacket > 0 {
  114. mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket
  115. } else {
  116. // Get max allowed packet size
  117. maxap, err := mc.getSystemVar("max_allowed_packet")
  118. if err != nil {
  119. mc.Close()
  120. return nil, err
  121. }
  122. mc.maxAllowedPacket = stringToInt(maxap) - 1
  123. }
  124. if mc.maxAllowedPacket < maxPacketSize {
  125. mc.maxWriteSize = mc.maxAllowedPacket
  126. }
  127. // Handle DSN Params
  128. err = mc.handleParams()
  129. if err != nil {
  130. mc.Close()
  131. return nil, err
  132. }
  133. return mc, nil
  134. }
  135. func handleAuthResult(mc *mysqlConn, oldCipher []byte) error {
  136. // Read Result Packet
  137. cipher, err := mc.readResultOK()
  138. if err == nil {
  139. return nil // auth successful
  140. }
  141. if mc.cfg == nil {
  142. return err // auth failed and retry not possible
  143. }
  144. // Retry auth if configured to do so.
  145. if mc.cfg.AllowOldPasswords && err == ErrOldPassword {
  146. // Retry with old authentication method. Note: there are edge cases
  147. // where this should work but doesn't; this is currently "wontfix":
  148. // https://github.com/go-sql-driver/mysql/issues/184
  149. // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is
  150. // sent and we have to keep using the cipher sent in the init packet.
  151. if cipher == nil {
  152. cipher = oldCipher
  153. }
  154. if err = mc.writeOldAuthPacket(cipher); err != nil {
  155. return err
  156. }
  157. _, err = mc.readResultOK()
  158. } else if mc.cfg.AllowCleartextPasswords && err == ErrCleartextPassword {
  159. // Retry with clear text password for
  160. // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html
  161. // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html
  162. if err = mc.writeClearAuthPacket(); err != nil {
  163. return err
  164. }
  165. _, err = mc.readResultOK()
  166. } else if mc.cfg.AllowNativePasswords && err == ErrNativePassword {
  167. if err = mc.writeNativeAuthPacket(cipher); err != nil {
  168. return err
  169. }
  170. _, err = mc.readResultOK()
  171. }
  172. return err
  173. }
  174. func init() {
  175. sql.Register("mysql", &MySQLDriver{})
  176. }