dsn.go 14 KB

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