dsn.go 15 KB

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