dsn.go 13 KB

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