driver.go 5.2 KB

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