driver.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. // Read Result Packet
  137. cipher, err := mc.readResultOK()
  138. if err == nil {
  139. // handle caching_sha2_password
  140. // https://insidemysql.com/preparing-your-community-connector-for-mysql-8-part-2-sha256/
  141. if pluginName == "caching_sha2_password" {
  142. if len(cipher) == 1 {
  143. switch cipher[0] {
  144. case cachingSha2PasswordFastAuthSuccess:
  145. cipher, err = mc.readResultOK()
  146. if err == nil {
  147. return nil // auth successful
  148. }
  149. case cachingSha2PasswordPerformFullAuthentication:
  150. if mc.cfg.tls != nil || mc.cfg.Net == "unix" {
  151. if err = mc.writeClearAuthPacket(); err != nil {
  152. return err
  153. }
  154. } else {
  155. if err = mc.writePublicKeyAuthPacket(oldCipher); err != nil {
  156. return err
  157. }
  158. }
  159. cipher, err = mc.readResultOK()
  160. if err == nil {
  161. return nil // auth successful
  162. }
  163. default:
  164. return ErrMalformPkt
  165. }
  166. } else {
  167. return ErrMalformPkt
  168. }
  169. } else {
  170. return nil // auth successful
  171. }
  172. }
  173. if mc.cfg == nil {
  174. return err // auth failed and retry not possible
  175. }
  176. // Retry auth if configured to do so
  177. switch err {
  178. case ErrCleartextPassword:
  179. if mc.cfg.AllowCleartextPasswords {
  180. // Retry with clear text password for
  181. // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html
  182. // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html
  183. if err = mc.writeClearAuthPacket(); err != nil {
  184. return err
  185. }
  186. _, err = mc.readResultOK()
  187. }
  188. case ErrNativePassword:
  189. if mc.cfg.AllowNativePasswords {
  190. if err = mc.writeNativeAuthPacket(cipher); err != nil {
  191. return err
  192. }
  193. _, err = mc.readResultOK()
  194. }
  195. case ErrOldPassword:
  196. if mc.cfg.AllowOldPasswords {
  197. // Retry with old authentication method. Note: there are edge cases
  198. // where this should work but doesn't; this is currently "wontfix":
  199. // https://github.com/go-sql-driver/mysql/issues/184
  200. // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is
  201. // sent and we have to keep using the cipher sent in the init packet.
  202. if cipher == nil {
  203. cipher = oldCipher
  204. }
  205. if err = mc.writeOldAuthPacket(cipher); err != nil {
  206. return err
  207. }
  208. _, err = mc.readResultOK()
  209. }
  210. }
  211. return err
  212. }
  213. func init() {
  214. sql.Register("mysql", &MySQLDriver{})
  215. }