driver.go 4.7 KB

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