dsn.go 13 KB

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