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