dsn.go 12 KB

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