dsn.go 14 KB

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