You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dsn.go 13KB

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