You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dsn.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. "bytes"
  11. "crypto/rsa"
  12. "crypto/tls"
  13. "errors"
  14. "fmt"
  15. "math/big"
  16. "net"
  17. "net/url"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "time"
  22. )
  23. var (
  24. errInvalidDSNUnescaped = errors.New("invalid DSN: did you forget to escape a param value?")
  25. errInvalidDSNAddr = errors.New("invalid DSN: network address not terminated (missing closing brace)")
  26. errInvalidDSNNoSlash = errors.New("invalid DSN: missing the slash separating the database name")
  27. errInvalidDSNUnsafeCollation = errors.New("invalid DSN: interpolateParams can not be used with unsafe collations")
  28. )
  29. // Config is a configuration parsed from a DSN string.
  30. // If a new Config is created instead of being parsed from a DSN string,
  31. // the NewConfig function should be used, which sets default values.
  32. type Config struct {
  33. User string // Username
  34. Passwd string // Password (requires User)
  35. Net string // Network type
  36. Addr string // Network address (requires Net)
  37. DBName string // Database name
  38. Params map[string]string // Connection parameters
  39. Collation string // Connection collation
  40. Loc *time.Location // Location for time.Time values
  41. MaxAllowedPacket int // Max packet size allowed
  42. ServerPubKey string // Server public key name
  43. pubKey *rsa.PublicKey // Server public key
  44. TLSConfig string // TLS configuration name
  45. TLS *tls.Config // TLS configuration, its priority is higher than TLSConfig
  46. Timeout time.Duration // Dial timeout
  47. ReadTimeout time.Duration // I/O read timeout
  48. WriteTimeout time.Duration // I/O write timeout
  49. AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE
  50. AllowCleartextPasswords bool // Allows the cleartext client side plugin
  51. AllowFallbackToPlaintext bool // Allows fallback to unencrypted connection if server does not support TLS
  52. AllowNativePasswords bool // Allows the native password authentication method
  53. AllowOldPasswords bool // Allows the old insecure password method
  54. CheckConnLiveness bool // Check connections for liveness before using them
  55. ClientFoundRows bool // Return number of matching rows instead of rows changed
  56. ColumnsWithAlias bool // Prepend table alias to column names
  57. InterpolateParams bool // Interpolate placeholders into query string
  58. MultiStatements bool // Allow multiple statements in one query
  59. ParseTime bool // Parse time values to time.Time
  60. RejectReadOnly bool // Reject read-only connections
  61. }
  62. // NewConfig creates a new Config and sets default values.
  63. func NewConfig() *Config {
  64. return &Config{
  65. Collation: defaultCollation,
  66. Loc: time.UTC,
  67. MaxAllowedPacket: defaultMaxAllowedPacket,
  68. AllowNativePasswords: true,
  69. CheckConnLiveness: true,
  70. }
  71. }
  72. func (cfg *Config) Clone() *Config {
  73. cp := *cfg
  74. if cp.TLS != nil {
  75. cp.TLS = cfg.TLS.Clone()
  76. }
  77. if len(cp.Params) > 0 {
  78. cp.Params = make(map[string]string, len(cfg.Params))
  79. for k, v := range cfg.Params {
  80. cp.Params[k] = v
  81. }
  82. }
  83. if cfg.pubKey != nil {
  84. cp.pubKey = &rsa.PublicKey{
  85. N: new(big.Int).Set(cfg.pubKey.N),
  86. E: cfg.pubKey.E,
  87. }
  88. }
  89. return &cp
  90. }
  91. func (cfg *Config) normalize() error {
  92. if cfg.InterpolateParams && unsafeCollations[cfg.Collation] {
  93. return errInvalidDSNUnsafeCollation
  94. }
  95. // Set default network if empty
  96. if cfg.Net == "" {
  97. cfg.Net = "tcp"
  98. }
  99. // Set default address if empty
  100. if cfg.Addr == "" {
  101. switch cfg.Net {
  102. case "tcp":
  103. cfg.Addr = "127.0.0.1:3306"
  104. case "unix":
  105. cfg.Addr = "/tmp/mysql.sock"
  106. default:
  107. return errors.New("default addr for network '" + cfg.Net + "' unknown")
  108. }
  109. } else if cfg.Net == "tcp" {
  110. cfg.Addr = ensureHavePort(cfg.Addr)
  111. }
  112. if cfg.TLS == nil {
  113. switch cfg.TLSConfig {
  114. case "false", "":
  115. // don't set anything
  116. case "true":
  117. cfg.TLS = &tls.Config{}
  118. case "skip-verify":
  119. cfg.TLS = &tls.Config{InsecureSkipVerify: true}
  120. case "preferred":
  121. cfg.TLS = &tls.Config{InsecureSkipVerify: true}
  122. cfg.AllowFallbackToPlaintext = true
  123. default:
  124. cfg.TLS = getTLSConfigClone(cfg.TLSConfig)
  125. if cfg.TLS == nil {
  126. return errors.New("invalid value / unknown config name: " + cfg.TLSConfig)
  127. }
  128. }
  129. }
  130. if cfg.TLS != nil && cfg.TLS.ServerName == "" && !cfg.TLS.InsecureSkipVerify {
  131. host, _, err := net.SplitHostPort(cfg.Addr)
  132. if err == nil {
  133. cfg.TLS.ServerName = host
  134. }
  135. }
  136. if cfg.ServerPubKey != "" {
  137. cfg.pubKey = getServerPubKey(cfg.ServerPubKey)
  138. if cfg.pubKey == nil {
  139. return errors.New("invalid value / unknown server pub key name: " + cfg.ServerPubKey)
  140. }
  141. }
  142. return nil
  143. }
  144. func writeDSNParam(buf *bytes.Buffer, hasParam *bool, name, value string) {
  145. buf.Grow(1 + len(name) + 1 + len(value))
  146. if !*hasParam {
  147. *hasParam = true
  148. buf.WriteByte('?')
  149. } else {
  150. buf.WriteByte('&')
  151. }
  152. buf.WriteString(name)
  153. buf.WriteByte('=')
  154. buf.WriteString(value)
  155. }
  156. // FormatDSN formats the given Config into a DSN string which can be passed to
  157. // the driver.
  158. func (cfg *Config) FormatDSN() string {
  159. var buf bytes.Buffer
  160. // [username[:password]@]
  161. if len(cfg.User) > 0 {
  162. buf.WriteString(cfg.User)
  163. if len(cfg.Passwd) > 0 {
  164. buf.WriteByte(':')
  165. buf.WriteString(cfg.Passwd)
  166. }
  167. buf.WriteByte('@')
  168. }
  169. // [protocol[(address)]]
  170. if len(cfg.Net) > 0 {
  171. buf.WriteString(cfg.Net)
  172. if len(cfg.Addr) > 0 {
  173. buf.WriteByte('(')
  174. buf.WriteString(cfg.Addr)
  175. buf.WriteByte(')')
  176. }
  177. }
  178. // /dbname
  179. buf.WriteByte('/')
  180. buf.WriteString(cfg.DBName)
  181. // [?param1=value1&...&paramN=valueN]
  182. hasParam := false
  183. if cfg.AllowAllFiles {
  184. hasParam = true
  185. buf.WriteString("?allowAllFiles=true")
  186. }
  187. if cfg.AllowCleartextPasswords {
  188. writeDSNParam(&buf, &hasParam, "allowCleartextPasswords", "true")
  189. }
  190. if cfg.AllowFallbackToPlaintext {
  191. writeDSNParam(&buf, &hasParam, "allowFallbackToPlaintext", "true")
  192. }
  193. if !cfg.AllowNativePasswords {
  194. writeDSNParam(&buf, &hasParam, "allowNativePasswords", "false")
  195. }
  196. if cfg.AllowOldPasswords {
  197. writeDSNParam(&buf, &hasParam, "allowOldPasswords", "true")
  198. }
  199. if !cfg.CheckConnLiveness {
  200. writeDSNParam(&buf, &hasParam, "checkConnLiveness", "false")
  201. }
  202. if cfg.ClientFoundRows {
  203. writeDSNParam(&buf, &hasParam, "clientFoundRows", "true")
  204. }
  205. if col := cfg.Collation; col != defaultCollation && len(col) > 0 {
  206. writeDSNParam(&buf, &hasParam, "collation", col)
  207. }
  208. if cfg.ColumnsWithAlias {
  209. writeDSNParam(&buf, &hasParam, "columnsWithAlias", "true")
  210. }
  211. if cfg.InterpolateParams {
  212. writeDSNParam(&buf, &hasParam, "interpolateParams", "true")
  213. }
  214. if cfg.Loc != time.UTC && cfg.Loc != nil {
  215. writeDSNParam(&buf, &hasParam, "loc", url.QueryEscape(cfg.Loc.String()))
  216. }
  217. if cfg.MultiStatements {
  218. writeDSNParam(&buf, &hasParam, "multiStatements", "true")
  219. }
  220. if cfg.ParseTime {
  221. writeDSNParam(&buf, &hasParam, "parseTime", "true")
  222. }
  223. if cfg.ReadTimeout > 0 {
  224. writeDSNParam(&buf, &hasParam, "readTimeout", cfg.ReadTimeout.String())
  225. }
  226. if cfg.RejectReadOnly {
  227. writeDSNParam(&buf, &hasParam, "rejectReadOnly", "true")
  228. }
  229. if len(cfg.ServerPubKey) > 0 {
  230. writeDSNParam(&buf, &hasParam, "serverPubKey", url.QueryEscape(cfg.ServerPubKey))
  231. }
  232. if cfg.Timeout > 0 {
  233. writeDSNParam(&buf, &hasParam, "timeout", cfg.Timeout.String())
  234. }
  235. if len(cfg.TLSConfig) > 0 {
  236. writeDSNParam(&buf, &hasParam, "tls", url.QueryEscape(cfg.TLSConfig))
  237. }
  238. if cfg.WriteTimeout > 0 {
  239. writeDSNParam(&buf, &hasParam, "writeTimeout", cfg.WriteTimeout.String())
  240. }
  241. if cfg.MaxAllowedPacket != defaultMaxAllowedPacket {
  242. writeDSNParam(&buf, &hasParam, "maxAllowedPacket", strconv.Itoa(cfg.MaxAllowedPacket))
  243. }
  244. // other params
  245. if cfg.Params != nil {
  246. var params []string
  247. for param := range cfg.Params {
  248. params = append(params, param)
  249. }
  250. sort.Strings(params)
  251. for _, param := range params {
  252. writeDSNParam(&buf, &hasParam, param, url.QueryEscape(cfg.Params[param]))
  253. }
  254. }
  255. return buf.String()
  256. }
  257. // ParseDSN parses the DSN string to a Config
  258. func ParseDSN(dsn string) (cfg *Config, err error) {
  259. // New config with some default values
  260. cfg = NewConfig()
  261. // [user[:password]@][net[(addr)]]/dbname[?param1=value1&paramN=valueN]
  262. // Find the last '/' (since the password or the net addr might contain a '/')
  263. foundSlash := false
  264. for i := len(dsn) - 1; i >= 0; i-- {
  265. if dsn[i] == '/' {
  266. foundSlash = true
  267. var j, k int
  268. // left part is empty if i <= 0
  269. if i > 0 {
  270. // [username[:password]@][protocol[(address)]]
  271. // Find the last '@' in dsn[:i]
  272. for j = i; j >= 0; j-- {
  273. if dsn[j] == '@' {
  274. // username[:password]
  275. // Find the first ':' in dsn[:j]
  276. for k = 0; k < j; k++ {
  277. if dsn[k] == ':' {
  278. cfg.Passwd = dsn[k+1 : j]
  279. break
  280. }
  281. }
  282. cfg.User = dsn[:k]
  283. break
  284. }
  285. }
  286. // [protocol[(address)]]
  287. // Find the first '(' in dsn[j+1:i]
  288. for k = j + 1; k < i; k++ {
  289. if dsn[k] == '(' {
  290. // dsn[i-1] must be == ')' if an address is specified
  291. if dsn[i-1] != ')' {
  292. if strings.ContainsRune(dsn[k+1:i], ')') {
  293. return nil, errInvalidDSNUnescaped
  294. }
  295. return nil, errInvalidDSNAddr
  296. }
  297. cfg.Addr = dsn[k+1 : i-1]
  298. break
  299. }
  300. }
  301. cfg.Net = dsn[j+1 : k]
  302. }
  303. // dbname[?param1=value1&...&paramN=valueN]
  304. // Find the first '?' in dsn[i+1:]
  305. for j = i + 1; j < len(dsn); j++ {
  306. if dsn[j] == '?' {
  307. if err = parseDSNParams(cfg, dsn[j+1:]); err != nil {
  308. return
  309. }
  310. break
  311. }
  312. }
  313. cfg.DBName = dsn[i+1 : j]
  314. break
  315. }
  316. }
  317. if !foundSlash && len(dsn) > 0 {
  318. return nil, errInvalidDSNNoSlash
  319. }
  320. if err = cfg.normalize(); err != nil {
  321. return nil, err
  322. }
  323. return
  324. }
  325. // parseDSNParams parses the DSN "query string"
  326. // Values must be url.QueryEscape'ed
  327. func parseDSNParams(cfg *Config, params string) (err error) {
  328. for _, v := range strings.Split(params, "&") {
  329. param := strings.SplitN(v, "=", 2)
  330. if len(param) != 2 {
  331. continue
  332. }
  333. // cfg params
  334. switch value := param[1]; param[0] {
  335. // Disable INFILE allowlist / enable all files
  336. case "allowAllFiles":
  337. var isBool bool
  338. cfg.AllowAllFiles, isBool = readBool(value)
  339. if !isBool {
  340. return errors.New("invalid bool value: " + value)
  341. }
  342. // Use cleartext authentication mode (MySQL 5.5.10+)
  343. case "allowCleartextPasswords":
  344. var isBool bool
  345. cfg.AllowCleartextPasswords, isBool = readBool(value)
  346. if !isBool {
  347. return errors.New("invalid bool value: " + value)
  348. }
  349. // Allow fallback to unencrypted connection if server does not support TLS
  350. case "allowFallbackToPlaintext":
  351. var isBool bool
  352. cfg.AllowFallbackToPlaintext, isBool = readBool(value)
  353. if !isBool {
  354. return errors.New("invalid bool value: " + value)
  355. }
  356. // Use native password authentication
  357. case "allowNativePasswords":
  358. var isBool bool
  359. cfg.AllowNativePasswords, isBool = readBool(value)
  360. if !isBool {
  361. return errors.New("invalid bool value: " + value)
  362. }
  363. // Use old authentication mode (pre MySQL 4.1)
  364. case "allowOldPasswords":
  365. var isBool bool
  366. cfg.AllowOldPasswords, isBool = readBool(value)
  367. if !isBool {
  368. return errors.New("invalid bool value: " + value)
  369. }
  370. // Check connections for Liveness before using them
  371. case "checkConnLiveness":
  372. var isBool bool
  373. cfg.CheckConnLiveness, isBool = readBool(value)
  374. if !isBool {
  375. return errors.New("invalid bool value: " + value)
  376. }
  377. // Switch "rowsAffected" mode
  378. case "clientFoundRows":
  379. var isBool bool
  380. cfg.ClientFoundRows, isBool = readBool(value)
  381. if !isBool {
  382. return errors.New("invalid bool value: " + value)
  383. }
  384. // Collation
  385. case "collation":
  386. cfg.Collation = value
  387. case "columnsWithAlias":
  388. var isBool bool
  389. cfg.ColumnsWithAlias, isBool = readBool(value)
  390. if !isBool {
  391. return errors.New("invalid bool value: " + value)
  392. }
  393. // Compression
  394. case "compress":
  395. return errors.New("compression not implemented yet")
  396. // Enable client side placeholder substitution
  397. case "interpolateParams":
  398. var isBool bool
  399. cfg.InterpolateParams, isBool = readBool(value)
  400. if !isBool {
  401. return errors.New("invalid bool value: " + value)
  402. }
  403. // Time Location
  404. case "loc":
  405. if value, err = url.QueryUnescape(value); err != nil {
  406. return
  407. }
  408. cfg.Loc, err = time.LoadLocation(value)
  409. if err != nil {
  410. return
  411. }
  412. // multiple statements in one query
  413. case "multiStatements":
  414. var isBool bool
  415. cfg.MultiStatements, isBool = readBool(value)
  416. if !isBool {
  417. return errors.New("invalid bool value: " + value)
  418. }
  419. // time.Time parsing
  420. case "parseTime":
  421. var isBool bool
  422. cfg.ParseTime, isBool = readBool(value)
  423. if !isBool {
  424. return errors.New("invalid bool value: " + value)
  425. }
  426. // I/O read Timeout
  427. case "readTimeout":
  428. cfg.ReadTimeout, err = time.ParseDuration(value)
  429. if err != nil {
  430. return
  431. }
  432. // Reject read-only connections
  433. case "rejectReadOnly":
  434. var isBool bool
  435. cfg.RejectReadOnly, isBool = readBool(value)
  436. if !isBool {
  437. return errors.New("invalid bool value: " + value)
  438. }
  439. // Server public key
  440. case "serverPubKey":
  441. name, err := url.QueryUnescape(value)
  442. if err != nil {
  443. return fmt.Errorf("invalid value for server pub key name: %v", err)
  444. }
  445. cfg.ServerPubKey = name
  446. // Strict mode
  447. case "strict":
  448. panic("strict mode has been removed. See https://github.com/go-sql-driver/mysql/wiki/strict-mode")
  449. // Dial Timeout
  450. case "timeout":
  451. cfg.Timeout, err = time.ParseDuration(value)
  452. if err != nil {
  453. return
  454. }
  455. // TLS-Encryption
  456. case "tls":
  457. boolValue, isBool := readBool(value)
  458. if isBool {
  459. if boolValue {
  460. cfg.TLSConfig = "true"
  461. } else {
  462. cfg.TLSConfig = "false"
  463. }
  464. } else if vl := strings.ToLower(value); vl == "skip-verify" || vl == "preferred" {
  465. cfg.TLSConfig = vl
  466. } else {
  467. name, err := url.QueryUnescape(value)
  468. if err != nil {
  469. return fmt.Errorf("invalid value for TLS config name: %v", err)
  470. }
  471. cfg.TLSConfig = name
  472. }
  473. // I/O write Timeout
  474. case "writeTimeout":
  475. cfg.WriteTimeout, err = time.ParseDuration(value)
  476. if err != nil {
  477. return
  478. }
  479. case "maxAllowedPacket":
  480. cfg.MaxAllowedPacket, err = strconv.Atoi(value)
  481. if err != nil {
  482. return
  483. }
  484. default:
  485. // lazy init
  486. if cfg.Params == nil {
  487. cfg.Params = make(map[string]string)
  488. }
  489. if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil {
  490. return
  491. }
  492. }
  493. }
  494. return
  495. }
  496. func ensureHavePort(addr string) string {
  497. if _, _, err := net.SplitHostPort(addr); err != nil {
  498. return net.JoinHostPort(addr, "3306")
  499. }
  500. return addr
  501. }