dsn.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. return
  336. }
  337. // parseDSNParams parses the DSN "query string"
  338. // Values must be url.QueryEscape'ed
  339. func parseDSNParams(cfg *Config, params string) (err error) {
  340. for _, v := range strings.Split(params, "&") {
  341. param := strings.SplitN(v, "=", 2)
  342. if len(param) != 2 {
  343. continue
  344. }
  345. // cfg params
  346. switch value := param[1]; param[0] {
  347. // Disable INFILE whitelist / enable all files
  348. case "allowAllFiles":
  349. var isBool bool
  350. cfg.AllowAllFiles, isBool = readBool(value)
  351. if !isBool {
  352. return errors.New("invalid bool value: " + value)
  353. }
  354. // Use cleartext authentication mode (MySQL 5.5.10+)
  355. case "allowCleartextPasswords":
  356. var isBool bool
  357. cfg.AllowCleartextPasswords, isBool = readBool(value)
  358. if !isBool {
  359. return errors.New("invalid bool value: " + value)
  360. }
  361. // Use native password authentication
  362. case "allowNativePasswords":
  363. var isBool bool
  364. cfg.AllowNativePasswords, isBool = readBool(value)
  365. if !isBool {
  366. return errors.New("invalid bool value: " + value)
  367. }
  368. // Use old authentication mode (pre MySQL 4.1)
  369. case "allowOldPasswords":
  370. var isBool bool
  371. cfg.AllowOldPasswords, isBool = readBool(value)
  372. if !isBool {
  373. return errors.New("invalid bool value: " + value)
  374. }
  375. // Switch "rowsAffected" mode
  376. case "clientFoundRows":
  377. var isBool bool
  378. cfg.ClientFoundRows, isBool = readBool(value)
  379. if !isBool {
  380. return errors.New("invalid bool value: " + value)
  381. }
  382. // Collation
  383. case "collation":
  384. cfg.Collation = value
  385. break
  386. case "columnsWithAlias":
  387. var isBool bool
  388. cfg.ColumnsWithAlias, isBool = readBool(value)
  389. if !isBool {
  390. return errors.New("invalid bool value: " + value)
  391. }
  392. // Compression
  393. case "compress":
  394. return errors.New("compression not implemented yet")
  395. // Enable client side placeholder substitution
  396. case "interpolateParams":
  397. var isBool bool
  398. cfg.InterpolateParams, isBool = readBool(value)
  399. if !isBool {
  400. return errors.New("invalid bool value: " + value)
  401. }
  402. // Time Location
  403. case "loc":
  404. if value, err = url.QueryUnescape(value); err != nil {
  405. return
  406. }
  407. cfg.Loc, err = time.LoadLocation(value)
  408. if err != nil {
  409. return
  410. }
  411. // multiple statements in one query
  412. case "multiStatements":
  413. var isBool bool
  414. cfg.MultiStatements, isBool = readBool(value)
  415. if !isBool {
  416. return errors.New("invalid bool value: " + value)
  417. }
  418. // time.Time parsing
  419. case "parseTime":
  420. var isBool bool
  421. cfg.ParseTime, isBool = readBool(value)
  422. if !isBool {
  423. return errors.New("invalid bool value: " + value)
  424. }
  425. // I/O read Timeout
  426. case "readTimeout":
  427. cfg.ReadTimeout, err = time.ParseDuration(value)
  428. if err != nil {
  429. return
  430. }
  431. // Reject read-only connections
  432. case "rejectReadOnly":
  433. var isBool bool
  434. cfg.RejectReadOnly, isBool = readBool(value)
  435. if !isBool {
  436. return errors.New("invalid bool value: " + value)
  437. }
  438. // Strict mode
  439. case "strict":
  440. var isBool bool
  441. cfg.Strict, isBool = readBool(value)
  442. if !isBool {
  443. return errors.New("invalid bool value: " + value)
  444. }
  445. // Dial Timeout
  446. case "timeout":
  447. cfg.Timeout, err = time.ParseDuration(value)
  448. if err != nil {
  449. return
  450. }
  451. // TLS-Encryption
  452. case "tls":
  453. boolValue, isBool := readBool(value)
  454. if isBool {
  455. if boolValue {
  456. cfg.TLSConfig = "true"
  457. cfg.tls = &tls.Config{}
  458. host, _, err := net.SplitHostPort(cfg.Addr)
  459. if err == nil {
  460. cfg.tls.ServerName = host
  461. }
  462. } else {
  463. cfg.TLSConfig = "false"
  464. }
  465. } else if vl := strings.ToLower(value); vl == "skip-verify" {
  466. cfg.TLSConfig = vl
  467. cfg.tls = &tls.Config{InsecureSkipVerify: true}
  468. } else {
  469. name, err := url.QueryUnescape(value)
  470. if err != nil {
  471. return fmt.Errorf("invalid value for TLS config name: %v", err)
  472. }
  473. if tlsConfig := getTLSConfigClone(name); tlsConfig != nil {
  474. if len(tlsConfig.ServerName) == 0 && !tlsConfig.InsecureSkipVerify {
  475. host, _, err := net.SplitHostPort(cfg.Addr)
  476. if err == nil {
  477. tlsConfig.ServerName = host
  478. }
  479. }
  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. }