dsn.go 15 KB

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