dsn.go 12 KB

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