dsn.go 14 KB

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