driver.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. mc.strict = mc.cfg.Strict
  59. // Connect to Server
  60. if dial, ok := dials[mc.cfg.Net]; ok {
  61. mc.netConn, err = dial(mc.cfg.Addr)
  62. } else {
  63. nd := net.Dialer{Timeout: mc.cfg.Timeout}
  64. mc.netConn, err = nd.Dial(mc.cfg.Net, mc.cfg.Addr)
  65. }
  66. if err != nil {
  67. return nil, err
  68. }
  69. // Enable TCP Keepalives on TCP connections
  70. if tc, ok := mc.netConn.(*net.TCPConn); ok {
  71. if err := tc.SetKeepAlive(true); err != nil {
  72. // Don't send COM_QUIT before handshake.
  73. mc.netConn.Close()
  74. mc.netConn = nil
  75. return nil, err
  76. }
  77. }
  78. // Call startWatcher for context support (From Go 1.8)
  79. if s, ok := interface{}(mc).(watcher); ok {
  80. s.startWatcher()
  81. }
  82. mc.buf = newBuffer(mc.netConn)
  83. // Set I/O timeouts
  84. mc.buf.timeout = mc.cfg.ReadTimeout
  85. mc.writeTimeout = mc.cfg.WriteTimeout
  86. // Reading Handshake Initialization Packet
  87. cipher, err := mc.readInitPacket()
  88. if err != nil {
  89. mc.cleanup()
  90. return nil, err
  91. }
  92. // Send Client Authentication Packet
  93. if err = mc.writeAuthPacket(cipher); err != nil {
  94. mc.cleanup()
  95. return nil, err
  96. }
  97. // Handle response to auth packet, switch methods if possible
  98. if err = handleAuthResult(mc, cipher); err != nil {
  99. // Authentication failed and MySQL has already closed the connection
  100. // (https://dev.mysql.com/doc/internals/en/authentication-fails.html).
  101. // Do not send COM_QUIT, just cleanup and return the error.
  102. mc.cleanup()
  103. return nil, err
  104. }
  105. if mc.cfg.MaxAllowedPacket > 0 {
  106. mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket
  107. } else {
  108. // Get max allowed packet size
  109. maxap, err := mc.getSystemVar("max_allowed_packet")
  110. if err != nil {
  111. mc.Close()
  112. return nil, err
  113. }
  114. mc.maxAllowedPacket = stringToInt(maxap) - 1
  115. }
  116. if mc.maxAllowedPacket < maxPacketSize {
  117. mc.maxWriteSize = mc.maxAllowedPacket
  118. }
  119. // Handle DSN Params
  120. err = mc.handleParams()
  121. if err != nil {
  122. mc.Close()
  123. return nil, err
  124. }
  125. return mc, nil
  126. }
  127. func handleAuthResult(mc *mysqlConn, oldCipher []byte) error {
  128. // Read Result Packet
  129. cipher, err := mc.readResultOK()
  130. if err == nil {
  131. return nil // auth successful
  132. }
  133. if mc.cfg == nil {
  134. return err // auth failed and retry not possible
  135. }
  136. // Retry auth if configured to do so.
  137. if mc.cfg.AllowOldPasswords && err == ErrOldPassword {
  138. // Retry with old authentication method. Note: there are edge cases
  139. // where this should work but doesn't; this is currently "wontfix":
  140. // https://github.com/go-sql-driver/mysql/issues/184
  141. // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is
  142. // sent and we have to keep using the cipher sent in the init packet.
  143. if cipher == nil {
  144. cipher = oldCipher
  145. }
  146. if err = mc.writeOldAuthPacket(cipher); err != nil {
  147. return err
  148. }
  149. _, err = mc.readResultOK()
  150. } else if mc.cfg.AllowCleartextPasswords && err == ErrCleartextPassword {
  151. // Retry with clear text password for
  152. // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html
  153. // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html
  154. if err = mc.writeClearAuthPacket(); err != nil {
  155. return err
  156. }
  157. _, err = mc.readResultOK()
  158. } else if mc.cfg.AllowNativePasswords && err == ErrNativePassword {
  159. if err = mc.writeNativeAuthPacket(cipher); err != nil {
  160. return err
  161. }
  162. _, err = mc.readResultOK()
  163. }
  164. return err
  165. }
  166. func init() {
  167. sql.Register("mysql", &MySQLDriver{})
  168. }