dsn.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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=true")
  97. } else {
  98. hasParam = true
  99. buf.WriteString("?allowNativePasswords=true")
  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. }
  257. // [user[:password]@][net[(addr)]]/dbname[?param1=value1&paramN=valueN]
  258. // Find the last '/' (since the password or the net addr might contain a '/')
  259. foundSlash := false
  260. for i := len(dsn) - 1; i >= 0; i-- {
  261. if dsn[i] == '/' {
  262. foundSlash = true
  263. var j, k int
  264. // left part is empty if i <= 0
  265. if i > 0 {
  266. // [username[:password]@][protocol[(address)]]
  267. // Find the last '@' in dsn[:i]
  268. for j = i; j >= 0; j-- {
  269. if dsn[j] == '@' {
  270. // username[:password]
  271. // Find the first ':' in dsn[:j]
  272. for k = 0; k < j; k++ {
  273. if dsn[k] == ':' {
  274. cfg.Passwd = dsn[k+1 : j]
  275. break
  276. }
  277. }
  278. cfg.User = dsn[:k]
  279. break
  280. }
  281. }
  282. // [protocol[(address)]]
  283. // Find the first '(' in dsn[j+1:i]
  284. for k = j + 1; k < i; k++ {
  285. if dsn[k] == '(' {
  286. // dsn[i-1] must be == ')' if an address is specified
  287. if dsn[i-1] != ')' {
  288. if strings.ContainsRune(dsn[k+1:i], ')') {
  289. return nil, errInvalidDSNUnescaped
  290. }
  291. return nil, errInvalidDSNAddr
  292. }
  293. cfg.Addr = dsn[k+1 : i-1]
  294. break
  295. }
  296. }
  297. cfg.Net = dsn[j+1 : k]
  298. }
  299. // dbname[?param1=value1&...&paramN=valueN]
  300. // Find the first '?' in dsn[i+1:]
  301. for j = i + 1; j < len(dsn); j++ {
  302. if dsn[j] == '?' {
  303. if err = parseDSNParams(cfg, dsn[j+1:]); err != nil {
  304. return
  305. }
  306. break
  307. }
  308. }
  309. cfg.DBName = dsn[i+1 : j]
  310. break
  311. }
  312. }
  313. if !foundSlash && len(dsn) > 0 {
  314. return nil, errInvalidDSNNoSlash
  315. }
  316. if cfg.InterpolateParams && unsafeCollations[cfg.Collation] {
  317. return nil, errInvalidDSNUnsafeCollation
  318. }
  319. // Set default network if empty
  320. if cfg.Net == "" {
  321. cfg.Net = "tcp"
  322. }
  323. // Set default address if empty
  324. if cfg.Addr == "" {
  325. switch cfg.Net {
  326. case "tcp":
  327. cfg.Addr = "127.0.0.1:3306"
  328. case "unix":
  329. cfg.Addr = "/tmp/mysql.sock"
  330. default:
  331. return nil, errors.New("default addr for network '" + cfg.Net + "' unknown")
  332. }
  333. }
  334. return
  335. }
  336. // parseDSNParams parses the DSN "query string"
  337. // Values must be url.QueryEscape'ed
  338. func parseDSNParams(cfg *Config, params string) (err error) {
  339. for _, v := range strings.Split(params, "&") {
  340. param := strings.SplitN(v, "=", 2)
  341. if len(param) != 2 {
  342. continue
  343. }
  344. // cfg params
  345. switch value := param[1]; param[0] {
  346. // Disable INFILE whitelist / enable all files
  347. case "allowAllFiles":
  348. var isBool bool
  349. cfg.AllowAllFiles, isBool = readBool(value)
  350. if !isBool {
  351. return errors.New("invalid bool value: " + value)
  352. }
  353. // Use cleartext authentication mode (MySQL 5.5.10+)
  354. case "allowCleartextPasswords":
  355. var isBool bool
  356. cfg.AllowCleartextPasswords, isBool = readBool(value)
  357. if !isBool {
  358. return errors.New("invalid bool value: " + value)
  359. }
  360. // Use native password authentication
  361. case "allowNativePasswords":
  362. var isBool bool
  363. cfg.AllowNativePasswords, isBool = readBool(value)
  364. if !isBool {
  365. return errors.New("invalid bool value: " + value)
  366. }
  367. // Use old authentication mode (pre MySQL 4.1)
  368. case "allowOldPasswords":
  369. var isBool bool
  370. cfg.AllowOldPasswords, isBool = readBool(value)
  371. if !isBool {
  372. return errors.New("invalid bool value: " + value)
  373. }
  374. // Switch "rowsAffected" mode
  375. case "clientFoundRows":
  376. var isBool bool
  377. cfg.ClientFoundRows, isBool = readBool(value)
  378. if !isBool {
  379. return errors.New("invalid bool value: " + value)
  380. }
  381. // Collation
  382. case "collation":
  383. cfg.Collation = value
  384. break
  385. case "columnsWithAlias":
  386. var isBool bool
  387. cfg.ColumnsWithAlias, isBool = readBool(value)
  388. if !isBool {
  389. return errors.New("invalid bool value: " + value)
  390. }
  391. // Compression
  392. case "compress":
  393. return errors.New("compression not implemented yet")
  394. // Enable client side placeholder substitution
  395. case "interpolateParams":
  396. var isBool bool
  397. cfg.InterpolateParams, isBool = readBool(value)
  398. if !isBool {
  399. return errors.New("invalid bool value: " + value)
  400. }
  401. // Time Location
  402. case "loc":
  403. if value, err = url.QueryUnescape(value); err != nil {
  404. return
  405. }
  406. cfg.Loc, err = time.LoadLocation(value)
  407. if err != nil {
  408. return
  409. }
  410. // multiple statements in one query
  411. case "multiStatements":
  412. var isBool bool
  413. cfg.MultiStatements, isBool = readBool(value)
  414. if !isBool {
  415. return errors.New("invalid bool value: " + value)
  416. }
  417. // time.Time parsing
  418. case "parseTime":
  419. var isBool bool
  420. cfg.ParseTime, isBool = readBool(value)
  421. if !isBool {
  422. return errors.New("invalid bool value: " + value)
  423. }
  424. // I/O read Timeout
  425. case "readTimeout":
  426. cfg.ReadTimeout, err = time.ParseDuration(value)
  427. if err != nil {
  428. return
  429. }
  430. // Reject read-only connections
  431. case "rejectReadOnly":
  432. var isBool bool
  433. cfg.RejectReadOnly, isBool = readBool(value)
  434. if !isBool {
  435. return errors.New("invalid bool value: " + value)
  436. }
  437. // Strict mode
  438. case "strict":
  439. var isBool bool
  440. cfg.Strict, isBool = readBool(value)
  441. if !isBool {
  442. return errors.New("invalid bool value: " + value)
  443. }
  444. // Dial Timeout
  445. case "timeout":
  446. cfg.Timeout, err = time.ParseDuration(value)
  447. if err != nil {
  448. return
  449. }
  450. // TLS-Encryption
  451. case "tls":
  452. boolValue, isBool := readBool(value)
  453. if isBool {
  454. if boolValue {
  455. cfg.TLSConfig = "true"
  456. cfg.tls = &tls.Config{}
  457. host, _, err := net.SplitHostPort(cfg.Addr)
  458. if err == nil {
  459. cfg.tls.ServerName = host
  460. }
  461. } else {
  462. cfg.TLSConfig = "false"
  463. }
  464. } else if vl := strings.ToLower(value); vl == "skip-verify" {
  465. cfg.TLSConfig = vl
  466. cfg.tls = &tls.Config{InsecureSkipVerify: true}
  467. } else {
  468. name, err := url.QueryUnescape(value)
  469. if err != nil {
  470. return fmt.Errorf("invalid value for TLS config name: %v", err)
  471. }
  472. if tlsConfig := getTLSConfigClone(name); tlsConfig != nil {
  473. if len(tlsConfig.ServerName) == 0 && !tlsConfig.InsecureSkipVerify {
  474. host, _, err := net.SplitHostPort(cfg.Addr)
  475. if err == nil {
  476. tlsConfig.ServerName = host
  477. }
  478. }
  479. cfg.TLSConfig = name
  480. cfg.tls = tlsConfig
  481. } else {
  482. return errors.New("invalid value / unknown config name: " + name)
  483. }
  484. }
  485. // I/O write Timeout
  486. case "writeTimeout":
  487. cfg.WriteTimeout, err = time.ParseDuration(value)
  488. if err != nil {
  489. return
  490. }
  491. case "maxAllowedPacket":
  492. cfg.MaxAllowedPacket, err = strconv.Atoi(value)
  493. if err != nil {
  494. return
  495. }
  496. default:
  497. // lazy init
  498. if cfg.Params == nil {
  499. cfg.Params = make(map[string]string)
  500. }
  501. if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil {
  502. return
  503. }
  504. }
  505. }
  506. return
  507. }