| 1 | /* |
| 2 | Copyright (c) 2019, Percona LLC. |
| 3 | All rights reserved. |
| 4 | |
| 5 | Redistribution and use in source and binary forms, with or without |
| 6 | modification, are permitted provided that the following conditions are met: |
| 7 | |
| 8 | * Redistributions of source code must retain the above copyright notice, this |
| 9 | list of conditions and the following disclaimer. |
| 10 | |
| 11 | * Redistributions in binary form must reproduce the above copyright notice, |
| 12 | this list of conditions and the following disclaimer in the documentation |
| 13 | and/or other materials provided with the distribution. |
| 14 | |
| 15 | * Neither the name of the copyright holder nor the names of its |
| 16 | contributors may be used to endorse or promote products derived from |
| 17 | this software without specific prior written permission. |
| 18 | |
| 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
| 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | */ |
| 30 | |
| 31 | package dsn |
| 32 | |
| 33 | import ( |
| 34 | "bytes" |
| 35 | "context" |
| 36 | "database/sql" |
| 37 | "fmt" |
| 38 | "log" |
| 39 | "os" |
| 40 | "os/exec" |
| 41 | "path" |
| 42 | "regexp" |
| 43 | "strings" |
| 44 | |
| 45 | "github.com/pkg/errors" |
| 46 | "github.com/shirou/gopsutil/process" |
| 47 | ) |
| 48 | |
| 49 | type DSN struct { |
| 50 | Username string |
| 51 | Password string |
| 52 | Hostname string |
| 53 | Port string |
| 54 | Socket string |
| 55 | // |
| 56 | DefaultsFile string |
| 57 | Protocol string |
| 58 | // |
| 59 | DefaultDb string |
| 60 | Params []string |
| 61 | } |
| 62 | |
| 63 | const ( |
| 64 | ParseTimeParam = "parseTime=true" |
| 65 | TimezoneParam = `time_zone='%2b00%3a00'` |
| 66 | LocationParam = "loc=UTC" |
| 67 | OldPasswordsParam = "allowOldPasswords=true" |
| 68 | HiddenPassword = "***" |
| 69 | ) |
| 70 | |
| 71 | // ErrNoSocket is returned when GetSocketFromProcessLists can't locate socket. |
| 72 | var ErrNoSocket = errors.New("cannot auto-detect MySQL socket") |
| 73 | |
| 74 | func (dsn DSN) AutoDetect(ctx context.Context) (DSN, error) { |
| 75 | defaults, err := Defaults(dsn.DefaultsFile) |
| 76 | if err != nil { |
| 77 | return dsn, err |
| 78 | } |
| 79 | |
| 80 | if dsn.Username == "" { |
| 81 | if defaults.Username != "" { |
| 82 | dsn.Username = defaults.Username |
| 83 | } else { |
| 84 | dsn.Username = os.Getenv("USER") |
| 85 | if dsn.Username == "" { |
| 86 | dsn.Username = "root" |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | if dsn.Password == "" && defaults.Password != "" { |
| 92 | dsn.Password = defaults.Password |
| 93 | } |
| 94 | |
| 95 | if dsn.Hostname == "" { |
| 96 | if defaults.Hostname != "" { |
| 97 | dsn.Hostname = defaults.Hostname |
| 98 | } else { |
| 99 | dsn.Hostname = "localhost" |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | if dsn.Port == "" { |
| 104 | if defaults.Port != "" { |
| 105 | dsn.Port = defaults.Port |
| 106 | } else { |
| 107 | dsn.Port = "3306" |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | // MySQL magic: localhost means socket if socket isn't set and protocol isn't tcp. |
| 112 | if dsn.Hostname == "localhost" && dsn.Socket == "" && dsn.Protocol != "tcp" { |
| 113 | if defaults.Socket != "" { |
| 114 | dsn.Socket = defaults.Socket |
| 115 | } else { |
| 116 | socket, err := GetSocket(ctx, dsn.String()) |
| 117 | if err != nil { |
| 118 | return dsn, err |
| 119 | } |
| 120 | dsn.Socket = socket |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | return dsn, nil |
| 125 | } |
| 126 | |
| 127 | func Defaults(defaultsFile string) (DSN, error) { |
| 128 | versionParams := [][]string{ |
| 129 | {"-s", "client"}, |
| 130 | {"client"}, |
| 131 | } |
| 132 | if defaultsFile != "" { |
| 133 | versionParams = [][]string{ |
| 134 | {"--defaults-file=" + defaultsFile, "-s", "client"}, |
| 135 | {"--defaults-file=" + defaultsFile, "client"}, |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | var err error |
| 140 | var output []byte |
| 141 | for _, params := range versionParams { |
| 142 | cmd := exec.Command("my_print_defaults", params...) |
| 143 | output, err = cmd.Output() |
| 144 | if err == nil { |
| 145 | break |
| 146 | } |
| 147 | } |
| 148 | dsn := ParseMySQLDefaults(string(output)) |
| 149 | return dsn, nil |
| 150 | } |
| 151 | |
| 152 | func (dsn DSN) String() string { |
| 153 | dsnString := "" |
| 154 | |
| 155 | // Socket takes priority if set and protocol isn't tcp. |
| 156 | if dsn.Socket != "" && dsn.Protocol != "tcp" { |
| 157 | dsnString = fmt.Sprintf("%s:%s@unix(%s)", |
| 158 | dsn.Username, |
| 159 | dsn.Password, |
| 160 | dsn.Socket, |
| 161 | ) |
| 162 | } else { |
| 163 | if dsn.Hostname == "" { |
| 164 | dsn.Hostname = "localhost" |
| 165 | } |
| 166 | if dsn.Port == "" { |
| 167 | dsn.Port = "3306" |
| 168 | } |
| 169 | dsnString = fmt.Sprintf("%s:%s@tcp(%s:%s)", |
| 170 | dsn.Username, |
| 171 | dsn.Password, |
| 172 | dsn.Hostname, |
| 173 | dsn.Port, |
| 174 | ) |
| 175 | } |
| 176 | |
| 177 | dsnString += "/" + dsn.DefaultDb |
| 178 | |
| 179 | params := strings.Join(dsn.Params, "&") |
| 180 | if params != "" { |
| 181 | dsnString += "?" + params |
| 182 | } |
| 183 | |
| 184 | return dsnString |
| 185 | } |
| 186 | |
| 187 | func (dsn DSN) Verify() error { |
| 188 | // Open connection to MySQL but... |
| 189 | db, err := sql.Open("mysql", dsn.String()) |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | defer db.Close() |
| 194 | |
| 195 | // ...try to use the connection for real. |
| 196 | if err = db.Ping(); err != nil { |
| 197 | return err |
| 198 | } |
| 199 | |
| 200 | return nil |
| 201 | } |
| 202 | |
| 203 | func HidePassword(dsn string) string { |
| 204 | dsn = strings.TrimRight(strings.Split(dsn, "?")[0], "/") |
| 205 | if strings.Index(dsn, "@") > 0 { |
| 206 | dsnParts := strings.Split(dsn, "@") |
| 207 | userPart := dsnParts[0] |
| 208 | hostPart := "" |
| 209 | if len(dsnParts) > 1 { |
| 210 | hostPart = dsnParts[len(dsnParts)-1] |
| 211 | } |
| 212 | userPasswordParts := strings.Split(userPart, ":") |
| 213 | dsn = fmt.Sprintf("%s:***@%s", userPasswordParts[0], hostPart) |
| 214 | } |
| 215 | return dsn |
| 216 | } |
| 217 | |
| 218 | // GetSocketFromTCPConnection will try to get socket path by connecting to MySQL localhost TCP port. |
| 219 | // This is not reliable as TCP connections may be not allowed. |
| 220 | func GetSocketFromTCPConnection(ctx context.Context, dsn string) (socket string, err error) { |
| 221 | db, err := sql.Open("mysql", dsn) |
| 222 | if err != nil { |
| 223 | return "", ErrNoSocket |
| 224 | } |
| 225 | defer db.Close() |
| 226 | |
| 227 | err = db.QueryRowContext(ctx, "SELECT @@socket").Scan(socket) |
| 228 | if err != nil { |
| 229 | return "", ErrNoSocket |
| 230 | } |
| 231 | if !path.IsAbs(socket) { |
| 232 | return "", ErrNoSocket |
| 233 | } |
| 234 | if socket != "" { |
| 235 | return socket, nil |
| 236 | } |
| 237 | |
| 238 | return "", ErrNoSocket |
| 239 | } |
| 240 | |
| 241 | // GetSocketFromProcessList will loop through the list of PIDs until it finds a process |
| 242 | // named 'mysqld' and the it will try to get the socket by querying the open network |
| 243 | // connections for that process. |
| 244 | // Warning: this function returns the socket for the FIRST mysqld process it founds. |
| 245 | // If there are more than one MySQL instance, only the first one will be detected. |
| 246 | func GetSocketFromProcessList(ctx context.Context) (string, error) { |
| 247 | pids, err := process.Pids() |
| 248 | if err != nil { |
| 249 | return "", errors.Wrap(err, "Cannot get the list of PIDs") |
| 250 | } |
| 251 | socketsMap := map[string]struct{}{} |
| 252 | sockets := []string{} |
| 253 | mysqldPIDs := []string{} |
| 254 | for _, pid := range pids { |
| 255 | proc, err := process.NewProcess(pid) |
| 256 | if err != nil { |
| 257 | continue |
| 258 | } |
| 259 | procName, err := proc.Name() |
| 260 | if err != nil { |
| 261 | continue |
| 262 | } |
| 263 | if procName != "mysqld" { |
| 264 | continue |
| 265 | } |
| 266 | mysqlPID := fmt.Sprintf("%d", pid) |
| 267 | mysqldPIDs = append(mysqldPIDs, mysqlPID) |
| 268 | socketsFromPID, err := GetSocketsFromPID(ctx, mysqlPID) |
| 269 | if err != nil { |
| 270 | return "", errors.Wrapf(err, "Cannot get network connections for PID %d", pid) |
| 271 | } |
| 272 | for _, socket := range socketsFromPID { |
| 273 | if strings.HasPrefix(socket, "->") { |
| 274 | continue |
| 275 | } |
| 276 | if strings.HasSuffix(socket, "/mysqlx.sock") { |
| 277 | continue |
| 278 | } |
| 279 | if _, exist := socketsMap[socket]; !exist { |
| 280 | socketsMap[socket] = struct{}{} |
| 281 | sockets = append(sockets, socket) |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | if len(sockets) > 1 { |
| 286 | log.Printf("lsof: multiple sockets detected for pid(s) %v, choosing first one: %s\n", mysqldPIDs, strings.Join(sockets, ", ")) |
| 287 | } |
| 288 | if len(sockets) > 0 { |
| 289 | return sockets[0], nil |
| 290 | } |
| 291 | return "", ErrNoSocket |
| 292 | } |
| 293 | |
| 294 | // GetSocketFromNetstat will loop through list of open sockets |
| 295 | // and try to find one matching `mysql` word. |
| 296 | // Warning: this function returns the socket for the FIRST entry it founds. |
| 297 | // If there are more sockets containing `mysql` word, only the first one will be detected. |
| 298 | func GetSocketFromNetstat(ctx context.Context) (string, error) { |
| 299 | // Try to auto-detect MySQL socket from netstat output. |
| 300 | out, err := exec.CommandContext(ctx, "netstat", "-anp").Output() |
| 301 | if err != nil { |
| 302 | return "", ErrNoSocket |
| 303 | } |
| 304 | |
| 305 | socketsMap := map[string]struct{}{} |
| 306 | sockets := []string{} |
| 307 | lines := strings.Split(string(out), "\n") |
| 308 | for _, line := range lines { |
| 309 | if !strings.HasPrefix(line, "unix") { |
| 310 | continue |
| 311 | } |
| 312 | fields := strings.Fields(line) |
| 313 | if len(fields) == 0 { |
| 314 | continue |
| 315 | } |
| 316 | socket := fields[len(fields)-1] |
| 317 | if !path.IsAbs(socket) { |
| 318 | continue |
| 319 | } |
| 320 | if strings.HasSuffix(socket, "/mysqlx.sock") { |
| 321 | continue |
| 322 | } |
| 323 | if !strings.Contains(socket, "mysql") { |
| 324 | continue |
| 325 | } |
| 326 | if _, exist := socketsMap[socket]; !exist { |
| 327 | socketsMap[socket] = struct{}{} |
| 328 | sockets = append(sockets, socket) |
| 329 | } |
| 330 | } |
| 331 | if len(sockets) > 1 { |
| 332 | log.Println("netstat: multiple sockets detected, choosing first one:", strings.Join(sockets, ", ")) |
| 333 | } |
| 334 | if len(sockets) > 0 { |
| 335 | return sockets[0], nil |
| 336 | } |
| 337 | return "", ErrNoSocket |
| 338 | } |
| 339 | |
| 340 | // GetSocket tries to detect and return path to the MySQL socket. |
| 341 | func GetSocket(ctx context.Context, dsn string) (string, error) { |
| 342 | var socket string |
| 343 | var err error |
| 344 | socket, err = GetSocketFromTCPConnection(ctx, dsn) |
| 345 | if err != nil { |
| 346 | socket, err = GetSocketFromProcessList(ctx) |
| 347 | if err != nil { |
| 348 | socket, err = GetSocketFromNetstat(ctx) |
| 349 | } |
| 350 | } |
| 351 | return socket, err |
| 352 | } |
| 353 | |
| 354 | // GetSocketsFromPID returns currently open UNIX domain socket files by process identifier (PID). |
| 355 | func GetSocketsFromPID(ctx context.Context, pid string) ([]string, error) { |
| 356 | cmd := exec.CommandContext( |
| 357 | ctx, |
| 358 | "lsof", |
| 359 | "-a", |
| 360 | "-n", |
| 361 | "-P", |
| 362 | "-U", |
| 363 | "-F", |
| 364 | "n", |
| 365 | "-p", pid, |
| 366 | ) |
| 367 | output, err := cmd.Output() |
| 368 | if err != nil { |
| 369 | return nil, err |
| 370 | } |
| 371 | return parseLsofForSockets(output), nil |
| 372 | } |
| 373 | |
| 374 | // parseLsofForSockets parses `lsof -F n -p <pid>` output for open UNIX domain socket files. |
| 375 | func parseLsofForSockets(output []byte) (sockets []string) { |
| 376 | socketsMap := map[string]struct{}{} |
| 377 | lines := bytes.Split(output, []byte("\n")) |
| 378 | for _, line := range lines { |
| 379 | // `lsof -F n` |
| 380 | // When the -F option is specified, lsof produces output that is suitable for processing by another program |
| 381 | // - e.g, an awk or Perl script, or a C program. |
| 382 | // n file name, comment, Internet address |
| 383 | if !bytes.HasPrefix(line, []byte("n")) { |
| 384 | continue |
| 385 | } |
| 386 | line = bytes.TrimPrefix(line, []byte("n")) |
| 387 | |
| 388 | // lsof on trusty: `/var/run/mysqld/mysqld.sock` |
| 389 | // lsof on xenial, artful, bionic: `/var/run/mysqld/mysqld.sock type=STREAM` |
| 390 | line = bytes.TrimSuffix(line, []byte("type=STREAM")) |
| 391 | line = bytes.TrimSpace(line) |
| 392 | |
| 393 | // Skip empty lines. |
| 394 | if len(line) == 0 { |
| 395 | continue |
| 396 | } |
| 397 | socket := string(line) |
| 398 | |
| 399 | // @Nailya had a case on xenial where `lsof` returned `ntype=DGRAM` and `ntype=STREAM` without any path. |
| 400 | // I'm not sure what are those but we can try to avoid this by checking for absolute path. |
| 401 | // # lsof -a -n -P -U -F n -p $(pgrep -x mysqld | tr \\n ,) |
| 402 | // p952 |
| 403 | // f3 |
| 404 | // ntype=DGRAM |
| 405 | // f18 |
| 406 | // ntype=STREAM |
| 407 | // f19 |
| 408 | // ntype=STREAM |
| 409 | // f22 |
| 410 | // n/var/run/mysqld/mysqld.sock type=STREAM |
| 411 | // f24 |
| 412 | // n/var/run/mysqld/mysqlx.sock type=STREAM |
| 413 | if !path.IsAbs(socket) { |
| 414 | continue |
| 415 | } |
| 416 | |
| 417 | if _, exist := socketsMap[socket]; !exist { |
| 418 | socketsMap[socket] = struct{}{} |
| 419 | sockets = append(sockets, socket) |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | return sockets |
| 424 | } |
| 425 | |
| 426 | func ParseMySQLDefaults(output string) DSN { |
| 427 | var re *regexp.Regexp |
| 428 | var result [][]string // Result of FindAllStringSubmatch |
| 429 | var dsn DSN |
| 430 | |
| 431 | lines := strings.Split(output, "\n") |
| 432 | for _, line := range lines { |
| 433 | re = regexp.MustCompile("--user=(.*)") |
| 434 | result = re.FindAllStringSubmatch(line, -1) |
| 435 | if result != nil { |
| 436 | dsn.Username = result[len(result)-1][1] |
| 437 | } |
| 438 | |
| 439 | re = regexp.MustCompile("--password=(.*)") |
| 440 | result = re.FindAllStringSubmatch(line, -1) |
| 441 | if result != nil { |
| 442 | dsn.Password = result[len(result)-1][1] |
| 443 | } |
| 444 | |
| 445 | re = regexp.MustCompile("--socket=(.*)") |
| 446 | result = re.FindAllStringSubmatch(line, -1) |
| 447 | if result != nil { |
| 448 | dsn.Socket = result[len(result)-1][1] |
| 449 | } |
| 450 | |
| 451 | re = regexp.MustCompile("--host=(.*)") |
| 452 | result = re.FindAllStringSubmatch(line, -1) |
| 453 | if result != nil { |
| 454 | dsn.Hostname = result[len(result)-1][1] |
| 455 | } |
| 456 | |
| 457 | re = regexp.MustCompile("--port=(.*)") |
| 458 | result = re.FindAllStringSubmatch(line, -1) |
| 459 | if result != nil { |
| 460 | dsn.Port = result[len(result)-1][1] |
| 461 | } |
| 462 | } |
| 463 | if dsn.Socket != "" { // Cannot have socket & host |
| 464 | dsn.Port = "" |
| 465 | dsn.Hostname = "" |
| 466 | } |
| 467 | |
| 468 | // Hostname always defaults to localhost. If localhost means 127.0.0.1 or socket |
| 469 | // is handled by mysql/DSN.DSN(). |
| 470 | if dsn.Hostname == "" && dsn.Socket == "" { |
| 471 | dsn.Hostname = "localhost" |
| 472 | } |
| 473 | |
| 474 | return dsn |
| 475 | } |