driver.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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, pluginName, 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, pluginName); 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, pluginName); 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, pluginName string) error {
  136. // handle caching_sha2_password
  137. if pluginName == "caching_sha2_password" {
  138. auth, err := mc.readCachingSha2PasswordAuthResult()
  139. if err != nil {
  140. return err
  141. }
  142. if auth == cachingSha2PasswordPerformFullAuthentication {
  143. if mc.cfg.tls != nil || mc.cfg.Net == "unix" {
  144. if err = mc.writeClearAuthPacket(); err != nil {
  145. return err
  146. }
  147. } else {
  148. if err = mc.writePublicKeyAuthPacket(oldCipher); err != nil {
  149. return err
  150. }
  151. }
  152. }
  153. }
  154. // Read Result Packet
  155. cipher, err := mc.readResultOK()
  156. if err == nil {
  157. return nil // auth successful
  158. }
  159. if mc.cfg == nil {
  160. return err // auth failed and retry not possible
  161. }
  162. // Retry auth if configured to do so.
  163. if mc.cfg.AllowOldPasswords && err == ErrOldPassword {
  164. // Retry with old authentication method. Note: there are edge cases
  165. // where this should work but doesn't; this is currently "wontfix":
  166. // https://github.com/go-sql-driver/mysql/issues/184
  167. // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is
  168. // sent and we have to keep using the cipher sent in the init packet.
  169. if cipher == nil {
  170. cipher = oldCipher
  171. }
  172. if err = mc.writeOldAuthPacket(cipher); err != nil {
  173. return err
  174. }
  175. _, err = mc.readResultOK()
  176. } else if mc.cfg.AllowCleartextPasswords && err == ErrCleartextPassword {
  177. // Retry with clear text password for
  178. // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html
  179. // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html
  180. if err = mc.writeClearAuthPacket(); err != nil {
  181. return err
  182. }
  183. _, err = mc.readResultOK()
  184. } else if mc.cfg.AllowNativePasswords && err == ErrNativePassword {
  185. if err = mc.writeNativeAuthPacket(cipher); err != nil {
  186. return err
  187. }
  188. _, err = mc.readResultOK()
  189. }
  190. return err
  191. }
  192. func init() {
  193. sql.Register("mysql", &MySQLDriver{})
  194. }