dsn.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. "strconv"
  17. "strings"
  18. "time"
  19. )
  20. var (
  21. errInvalidDSNUnescaped = errors.New("invalid DSN: did you forget to escape a param value?")
  22. errInvalidDSNAddr = errors.New("invalid DSN: network address not terminated (missing closing brace)")
  23. errInvalidDSNNoSlash = errors.New("invalid DSN: missing the slash separating the database name")
  24. errInvalidDSNUnsafeCollation = errors.New("invalid DSN: interpolateParams can not be used with unsafe collations")
  25. )
  26. // Config is a configuration parsed from a DSN string
  27. type Config struct {
  28. User string // Username
  29. Passwd string // Password (requires User)
  30. Net string // Network type
  31. Addr string // Network address (requires Net)
  32. DBName string // Database name
  33. Params map[string]string // Connection parameters
  34. Collation string // Connection collation
  35. Loc *time.Location // Location for time.Time values
  36. MaxAllowedPacket int // Max packet size allowed
  37. TLSConfig string // TLS configuration name
  38. tls *tls.Config // TLS configuration
  39. Timeout time.Duration // Dial timeout
  40. ReadTimeout time.Duration // I/O read timeout
  41. WriteTimeout time.Duration // I/O write timeout
  42. AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE
  43. AllowCleartextPasswords bool // Allows the cleartext client side plugin
  44. AllowNativePasswords bool // Allows the native password authentication method
  45. AllowOldPasswords bool // Allows the old insecure password method
  46. ClientFoundRows bool // Return number of matching rows instead of rows changed
  47. ColumnsWithAlias bool // Prepend table alias to column names
  48. InterpolateParams bool // Interpolate placeholders into query string
  49. MultiStatements bool // Allow multiple statements in one query
  50. ParseTime bool // Parse time values to time.Time
  51. RejectReadOnly bool // Reject read-only connections
  52. Strict bool // Return warnings as errors
  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=true")
  96. } else {
  97. hasParam = true
  98. buf.WriteString("?allowNativePasswords=true")
  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.Strict {
  185. if hasParam {
  186. buf.WriteString("&strict=true")
  187. } else {
  188. hasParam = true
  189. buf.WriteString("?strict=true")
  190. }
  191. }
  192. if cfg.Timeout > 0 {
  193. if hasParam {
  194. buf.WriteString("&timeout=")
  195. } else {
  196. hasParam = true
  197. buf.WriteString("?timeout=")
  198. }
  199. buf.WriteString(cfg.Timeout.String())
  200. }
  201. if len(cfg.TLSConfig) > 0 {
  202. if hasParam {
  203. buf.WriteString("&tls=")
  204. } else {
  205. hasParam = true
  206. buf.WriteString("?tls=")
  207. }
  208. buf.WriteString(url.QueryEscape(cfg.TLSConfig))
  209. }
  210. if cfg.WriteTimeout > 0 {
  211. if hasParam {
  212. buf.WriteString("&writeTimeout=")
  213. } else {
  214. hasParam = true
  215. buf.WriteString("?writeTimeout=")
  216. }
  217. buf.WriteString(cfg.WriteTimeout.String())
  218. }
  219. if cfg.MaxAllowedPacket > 0 {
  220. if hasParam {
  221. buf.WriteString("&maxAllowedPacket=")
  222. } else {
  223. hasParam = true
  224. buf.WriteString("?maxAllowedPacket=")
  225. }
  226. buf.WriteString(strconv.Itoa(cfg.MaxAllowedPacket))
  227. }
  228. // other params
  229. if cfg.Params != nil {
  230. for param, value := range cfg.Params {
  231. if hasParam {
  232. buf.WriteByte('&')
  233. } else {
  234. hasParam = true
  235. buf.WriteByte('?')
  236. }
  237. buf.WriteString(param)
  238. buf.WriteByte('=')
  239. buf.WriteString(url.QueryEscape(value))
  240. }
  241. }
  242. return buf.String()
  243. }
  244. // ParseDSN parses the DSN string to a Config
  245. func ParseDSN(dsn string) (cfg *Config, err error) {
  246. // New config with some default values
  247. cfg = &Config{
  248. Loc: time.UTC,
  249. Collation: defaultCollation,
  250. }
  251. // [user[:password]@][net[(addr)]]/dbname[?param1=value1&paramN=valueN]
  252. // Find the last '/' (since the password or the net addr might contain a '/')
  253. foundSlash := false
  254. for i := len(dsn) - 1; i >= 0; i-- {
  255. if dsn[i] == '/' {
  256. foundSlash = true
  257. var j, k int
  258. // left part is empty if i <= 0
  259. if i > 0 {
  260. // [username[:password]@][protocol[(address)]]
  261. // Find the last '@' in dsn[:i]
  262. for j = i; j >= 0; j-- {
  263. if dsn[j] == '@' {
  264. // username[:password]
  265. // Find the first ':' in dsn[:j]
  266. for k = 0; k < j; k++ {
  267. if dsn[k] == ':' {
  268. cfg.Passwd = dsn[k+1 : j]
  269. break
  270. }
  271. }
  272. cfg.User = dsn[:k]
  273. break
  274. }
  275. }
  276. // [protocol[(address)]]
  277. // Find the first '(' in dsn[j+1:i]
  278. for k = j + 1; k < i; k++ {
  279. if dsn[k] == '(' {
  280. // dsn[i-1] must be == ')' if an address is specified
  281. if dsn[i-1] != ')' {
  282. if strings.ContainsRune(dsn[k+1:i], ')') {
  283. return nil, errInvalidDSNUnescaped
  284. }
  285. return nil, errInvalidDSNAddr
  286. }
  287. cfg.Addr = dsn[k+1 : i-1]
  288. break
  289. }
  290. }
  291. cfg.Net = dsn[j+1 : k]
  292. }
  293. // dbname[?param1=value1&...&paramN=valueN]
  294. // Find the first '?' in dsn[i+1:]
  295. for j = i + 1; j < len(dsn); j++ {
  296. if dsn[j] == '?' {
  297. if err = parseDSNParams(cfg, dsn[j+1:]); err != nil {
  298. return
  299. }
  300. break
  301. }
  302. }
  303. cfg.DBName = dsn[i+1 : j]
  304. break
  305. }
  306. }
  307. if !foundSlash && len(dsn) > 0 {
  308. return nil, errInvalidDSNNoSlash
  309. }
  310. if cfg.InterpolateParams && unsafeCollations[cfg.Collation] {
  311. return nil, errInvalidDSNUnsafeCollation
  312. }
  313. // Set default network if empty
  314. if cfg.Net == "" {
  315. cfg.Net = "tcp"
  316. }
  317. // Set default address if empty
  318. if cfg.Addr == "" {
  319. switch cfg.Net {
  320. case "tcp":
  321. cfg.Addr = "127.0.0.1:3306"
  322. case "unix":
  323. cfg.Addr = "/tmp/mysql.sock"
  324. default:
  325. return nil, errors.New("default addr for network '" + cfg.Net + "' unknown")
  326. }
  327. }
  328. return
  329. }
  330. // parseDSNParams parses the DSN "query string"
  331. // Values must be url.QueryEscape'ed
  332. func parseDSNParams(cfg *Config, params string) (err error) {
  333. for _, v := range strings.Split(params, "&") {
  334. param := strings.SplitN(v, "=", 2)
  335. if len(param) != 2 {
  336. continue
  337. }
  338. // cfg params
  339. switch value := param[1]; param[0] {
  340. // Disable INFILE whitelist / enable all files
  341. case "allowAllFiles":
  342. var isBool bool
  343. cfg.AllowAllFiles, isBool = readBool(value)
  344. if !isBool {
  345. return errors.New("invalid bool value: " + value)
  346. }
  347. // Use cleartext authentication mode (MySQL 5.5.10+)
  348. case "allowCleartextPasswords":
  349. var isBool bool
  350. cfg.AllowCleartextPasswords, isBool = readBool(value)
  351. if !isBool {
  352. return errors.New("invalid bool value: " + value)
  353. }
  354. // Use native password authentication
  355. case "allowNativePasswords":
  356. var isBool bool
  357. cfg.AllowNativePasswords, isBool = readBool(value)
  358. if !isBool {
  359. return errors.New("invalid bool value: " + value)
  360. }
  361. // Use old authentication mode (pre MySQL 4.1)
  362. case "allowOldPasswords":
  363. var isBool bool
  364. cfg.AllowOldPasswords, isBool = readBool(value)
  365. if !isBool {
  366. return errors.New("invalid bool value: " + value)
  367. }
  368. // Switch "rowsAffected" mode
  369. case "clientFoundRows":
  370. var isBool bool
  371. cfg.ClientFoundRows, isBool = readBool(value)
  372. if !isBool {
  373. return errors.New("invalid bool value: " + value)
  374. }
  375. // Collation
  376. case "collation":
  377. cfg.Collation = value
  378. break
  379. case "columnsWithAlias":
  380. var isBool bool
  381. cfg.ColumnsWithAlias, isBool = readBool(value)
  382. if !isBool {
  383. return errors.New("invalid bool value: " + value)
  384. }
  385. // Compression
  386. case "compress":
  387. return errors.New("compression not implemented yet")
  388. // Enable client side placeholder substitution
  389. case "interpolateParams":
  390. var isBool bool
  391. cfg.InterpolateParams, isBool = readBool(value)
  392. if !isBool {
  393. return errors.New("invalid bool value: " + value)
  394. }
  395. // Time Location
  396. case "loc":
  397. if value, err = url.QueryUnescape(value); err != nil {
  398. return
  399. }
  400. cfg.Loc, err = time.LoadLocation(value)
  401. if err != nil {
  402. return
  403. }
  404. // multiple statements in one query
  405. case "multiStatements":
  406. var isBool bool
  407. cfg.MultiStatements, isBool = readBool(value)
  408. if !isBool {
  409. return errors.New("invalid bool value: " + value)
  410. }
  411. // time.Time parsing
  412. case "parseTime":
  413. var isBool bool
  414. cfg.ParseTime, isBool = readBool(value)
  415. if !isBool {
  416. return errors.New("invalid bool value: " + value)
  417. }
  418. // I/O read Timeout
  419. case "readTimeout":
  420. cfg.ReadTimeout, err = time.ParseDuration(value)
  421. if err != nil {
  422. return
  423. }
  424. // Reject read-only connections
  425. case "rejectReadOnly":
  426. var isBool bool
  427. cfg.RejectReadOnly, isBool = readBool(value)
  428. if !isBool {
  429. return errors.New("invalid bool value: " + value)
  430. }
  431. // Strict mode
  432. case "strict":
  433. var isBool bool
  434. cfg.Strict, isBool = readBool(value)
  435. if !isBool {
  436. return errors.New("invalid bool value: " + value)
  437. }
  438. // Dial Timeout
  439. case "timeout":
  440. cfg.Timeout, err = time.ParseDuration(value)
  441. if err != nil {
  442. return
  443. }
  444. // TLS-Encryption
  445. case "tls":
  446. boolValue, isBool := readBool(value)
  447. if isBool {
  448. if boolValue {
  449. cfg.TLSConfig = "true"
  450. cfg.tls = &tls.Config{}
  451. host, _, err := net.SplitHostPort(cfg.Addr)
  452. if err == nil {
  453. cfg.tls.ServerName = host
  454. }
  455. } else {
  456. cfg.TLSConfig = "false"
  457. }
  458. } else if vl := strings.ToLower(value); vl == "skip-verify" {
  459. cfg.TLSConfig = vl
  460. cfg.tls = &tls.Config{InsecureSkipVerify: true}
  461. } else {
  462. name, err := url.QueryUnescape(value)
  463. if err != nil {
  464. return fmt.Errorf("invalid value for TLS config name: %v", err)
  465. }
  466. if tlsConfig, ok := tlsConfigRegister[name]; ok {
  467. tlsConfig = cloneTLSConfig(tlsConfig)
  468. if len(tlsConfig.ServerName) == 0 && !tlsConfig.InsecureSkipVerify {
  469. host, _, err := net.SplitHostPort(cfg.Addr)
  470. if err == nil {
  471. tlsConfig.ServerName = host
  472. }
  473. }
  474. cfg.TLSConfig = name
  475. cfg.tls = tlsConfig
  476. } else {
  477. return errors.New("invalid value / unknown config name: " + name)
  478. }
  479. }
  480. // I/O write Timeout
  481. case "writeTimeout":
  482. cfg.WriteTimeout, err = time.ParseDuration(value)
  483. if err != nil {
  484. return
  485. }
  486. case "maxAllowedPacket":
  487. cfg.MaxAllowedPacket, err = strconv.Atoi(value)
  488. if err != nil {
  489. return
  490. }
  491. default:
  492. // lazy init
  493. if cfg.Params == nil {
  494. cfg.Params = make(map[string]string)
  495. }
  496. if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil {
  497. return
  498. }
  499. }
  500. }
  501. return
  502. }