dsn.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. package mysql
  9. import (
  10. "crypto/tls"
  11. "errors"
  12. "fmt"
  13. "net"
  14. "net/url"
  15. "strings"
  16. "time"
  17. )
  18. var (
  19. errInvalidDSNUnescaped = errors.New("Invalid DSN: Did you forget to escape a param value?")
  20. errInvalidDSNAddr = errors.New("Invalid DSN: Network Address not terminated (missing closing brace)")
  21. errInvalidDSNNoSlash = errors.New("Invalid DSN: Missing the slash separating the database name")
  22. errInvalidDSNUnsafeCollation = errors.New("Invalid DSN: interpolateParams can be used with ascii, latin1, utf8 and utf8mb4 charset")
  23. )
  24. // Config is a configuration parsed from a DSN string
  25. type Config struct {
  26. User string // Username
  27. Passwd string // Password
  28. Net string // Network type
  29. Addr string // Network address
  30. DBName string // Database name
  31. Params map[string]string // Connection parameters
  32. Loc *time.Location // Location for time.Time values
  33. TLS *tls.Config // TLS configuration
  34. Timeout time.Duration // Dial timeout
  35. Collation uint8 // Connection collation
  36. AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE
  37. AllowCleartextPasswords bool // Allows the cleartext client side plugin
  38. AllowOldPasswords bool // Allows the old insecure password method
  39. ClientFoundRows bool // Return number of matching rows instead of rows changed
  40. ColumnsWithAlias bool // Prepend table alias to column names
  41. InterpolateParams bool // Interpolate placeholders into query string
  42. ParseTime bool // Parse time values to time.Time
  43. Strict bool // Return warnings as errors
  44. }
  45. // ParseDSN parses the DSN string to a Config
  46. func ParseDSN(dsn string) (cfg *Config, err error) {
  47. // New config with some default values
  48. cfg = &Config{
  49. Loc: time.UTC,
  50. Collation: defaultCollation,
  51. }
  52. // [user[:password]@][net[(addr)]]/dbname[?param1=value1&paramN=valueN]
  53. // Find the last '/' (since the password or the net addr might contain a '/')
  54. foundSlash := false
  55. for i := len(dsn) - 1; i >= 0; i-- {
  56. if dsn[i] == '/' {
  57. foundSlash = true
  58. var j, k int
  59. // left part is empty if i <= 0
  60. if i > 0 {
  61. // [username[:password]@][protocol[(address)]]
  62. // Find the last '@' in dsn[:i]
  63. for j = i; j >= 0; j-- {
  64. if dsn[j] == '@' {
  65. // username[:password]
  66. // Find the first ':' in dsn[:j]
  67. for k = 0; k < j; k++ {
  68. if dsn[k] == ':' {
  69. cfg.Passwd = dsn[k+1 : j]
  70. break
  71. }
  72. }
  73. cfg.User = dsn[:k]
  74. break
  75. }
  76. }
  77. // [protocol[(address)]]
  78. // Find the first '(' in dsn[j+1:i]
  79. for k = j + 1; k < i; k++ {
  80. if dsn[k] == '(' {
  81. // dsn[i-1] must be == ')' if an address is specified
  82. if dsn[i-1] != ')' {
  83. if strings.ContainsRune(dsn[k+1:i], ')') {
  84. return nil, errInvalidDSNUnescaped
  85. }
  86. return nil, errInvalidDSNAddr
  87. }
  88. cfg.Addr = dsn[k+1 : i-1]
  89. break
  90. }
  91. }
  92. cfg.Net = dsn[j+1 : k]
  93. }
  94. // dbname[?param1=value1&...&paramN=valueN]
  95. // Find the first '?' in dsn[i+1:]
  96. for j = i + 1; j < len(dsn); j++ {
  97. if dsn[j] == '?' {
  98. if err = parseDSNParams(cfg, dsn[j+1:]); err != nil {
  99. return
  100. }
  101. break
  102. }
  103. }
  104. cfg.DBName = dsn[i+1 : j]
  105. break
  106. }
  107. }
  108. if !foundSlash && len(dsn) > 0 {
  109. return nil, errInvalidDSNNoSlash
  110. }
  111. if cfg.InterpolateParams && unsafeCollations[cfg.Collation] {
  112. return nil, errInvalidDSNUnsafeCollation
  113. }
  114. // Set default network if empty
  115. if cfg.Net == "" {
  116. cfg.Net = "tcp"
  117. }
  118. // Set default address if empty
  119. if cfg.Addr == "" {
  120. switch cfg.Net {
  121. case "tcp":
  122. cfg.Addr = "127.0.0.1:3306"
  123. case "unix":
  124. cfg.Addr = "/tmp/mysql.sock"
  125. default:
  126. return nil, errors.New("Default addr for network '" + cfg.Net + "' unknown")
  127. }
  128. }
  129. return
  130. }
  131. // parseDSNParams parses the DSN "query string"
  132. // Values must be url.QueryEscape'ed
  133. func parseDSNParams(cfg *Config, params string) (err error) {
  134. for _, v := range strings.Split(params, "&") {
  135. param := strings.SplitN(v, "=", 2)
  136. if len(param) != 2 {
  137. continue
  138. }
  139. // cfg params
  140. switch value := param[1]; param[0] {
  141. // Disable INFILE whitelist / enable all files
  142. case "allowAllFiles":
  143. var isBool bool
  144. cfg.AllowAllFiles, isBool = readBool(value)
  145. if !isBool {
  146. return fmt.Errorf("Invalid Bool value: %s", value)
  147. }
  148. // Use cleartext authentication mode (MySQL 5.5.10+)
  149. case "allowCleartextPasswords":
  150. var isBool bool
  151. cfg.AllowCleartextPasswords, isBool = readBool(value)
  152. if !isBool {
  153. return fmt.Errorf("Invalid Bool value: %s", value)
  154. }
  155. // Use old authentication mode (pre MySQL 4.1)
  156. case "allowOldPasswords":
  157. var isBool bool
  158. cfg.AllowOldPasswords, isBool = readBool(value)
  159. if !isBool {
  160. return fmt.Errorf("Invalid Bool value: %s", value)
  161. }
  162. // Switch "rowsAffected" mode
  163. case "clientFoundRows":
  164. var isBool bool
  165. cfg.ClientFoundRows, isBool = readBool(value)
  166. if !isBool {
  167. return fmt.Errorf("Invalid Bool value: %s", value)
  168. }
  169. // Collation
  170. case "collation":
  171. collation, ok := collations[value]
  172. if !ok {
  173. // Note possibility for false negatives:
  174. // could be triggered although the collation is valid if the
  175. // collations map does not contain entries the server supports.
  176. err = errors.New("unknown collation")
  177. return
  178. }
  179. cfg.Collation = collation
  180. break
  181. case "columnsWithAlias":
  182. var isBool bool
  183. cfg.ColumnsWithAlias, isBool = readBool(value)
  184. if !isBool {
  185. return fmt.Errorf("Invalid Bool value: %s", value)
  186. }
  187. // Compression
  188. case "compress":
  189. return errors.New("Compression not implemented yet")
  190. // Enable client side placeholder substitution
  191. case "interpolateParams":
  192. var isBool bool
  193. cfg.InterpolateParams, isBool = readBool(value)
  194. if !isBool {
  195. return fmt.Errorf("Invalid Bool value: %s", value)
  196. }
  197. // Time Location
  198. case "loc":
  199. if value, err = url.QueryUnescape(value); err != nil {
  200. return
  201. }
  202. cfg.Loc, err = time.LoadLocation(value)
  203. if err != nil {
  204. return
  205. }
  206. // time.Time parsing
  207. case "parseTime":
  208. var isBool bool
  209. cfg.ParseTime, isBool = readBool(value)
  210. if !isBool {
  211. return errors.New("Invalid Bool value: " + value)
  212. }
  213. // Strict mode
  214. case "strict":
  215. var isBool bool
  216. cfg.Strict, isBool = readBool(value)
  217. if !isBool {
  218. return errors.New("Invalid Bool value: " + value)
  219. }
  220. // Dial Timeout
  221. case "timeout":
  222. cfg.Timeout, err = time.ParseDuration(value)
  223. if err != nil {
  224. return
  225. }
  226. // TLS-Encryption
  227. case "tls":
  228. boolValue, isBool := readBool(value)
  229. if isBool {
  230. if boolValue {
  231. cfg.TLS = &tls.Config{}
  232. }
  233. } else if value, err := url.QueryUnescape(value); err != nil {
  234. return fmt.Errorf("Invalid value for tls config name: %v", err)
  235. } else {
  236. if strings.ToLower(value) == "skip-verify" {
  237. cfg.TLS = &tls.Config{InsecureSkipVerify: true}
  238. } else if tlsConfig, ok := tlsConfigRegister[value]; ok {
  239. if len(tlsConfig.ServerName) == 0 && !tlsConfig.InsecureSkipVerify {
  240. host, _, err := net.SplitHostPort(cfg.Addr)
  241. if err == nil {
  242. tlsConfig.ServerName = host
  243. }
  244. }
  245. cfg.TLS = tlsConfig
  246. } else {
  247. return fmt.Errorf("Invalid value / unknown config name: %s", value)
  248. }
  249. }
  250. default:
  251. // lazy init
  252. if cfg.Params == nil {
  253. cfg.Params = make(map[string]string)
  254. }
  255. if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil {
  256. return
  257. }
  258. }
  259. }
  260. return
  261. }