// initiMySQLProtocol starts the mysql protocol.
// It should be called only once in a process.
519188
func initMySQLProtocol() {
	log.Infof("initializing mysql protocol")

	// Flag is not set, just return.
	if *mysqlServerPort < 0 && *mysqlServerSocketPath == "" {
		return
	}

	// If no mysqlproxy was created, just return.
	if mysqlProxy == nil {
		log.Fatalf("mysqlProxy not initialized")
		return
	}

	// Initialize registered AuthServer implementations (or other plugins)
	for _, initFn := range pluginInitializers {
		initFn()
	}
	authServer := mysql.GetAuthServer(*mysqlAuthServerImpl)

	// Create a Listener.
	var err error
	mh := newProxyHandler(mysqlProxy)
	if *mysqlServerPort >= 0 {
		mysqlListener, err = mysql.NewListener("tcp", net.JoinHostPort(*mysqlServerBindAddress, fmt.Sprintf("%v", *mysqlServerPort)), authServer, mh, *mysqlConnReadTimeout, *mysqlConnWriteTimeout)
		if err != nil {
			log.Exitf("mysql.NewListener failed: %v", err)
		}
		if *mysqlSslCert != "" && *mysqlSslKey != "" {
			mysqlListener.TLSConfig, err = vttls.ServerConfig(*mysqlSslCert, *mysqlSslKey, *mysqlSslCa)
			if err != nil {
				log.Exitf("grpcutils.TLSServerConfig failed: %v", err)
				return
			}
		}
		mysqlListener.AllowClearTextWithoutTLS = *mysqlAllowClearTextWithoutTLS

		// Check for the connection threshold
		if *mysqlSlowConnectWarnThreshold != 0 {
			log.Infof("setting mysql slow connection threshold to %v", mysqlSlowConnectWarnThreshold)
			mysqlListener.SlowConnectWarnThreshold = *mysqlSlowConnectWarnThreshold
		}
		// Start listening for tcp
		go mysqlListener.Accept()
		log.Infof("listening on %s:%d", *mysqlServerBindAddress, *mysqlServerPort)
	}

	if *mysqlServerSocketPath != "" {
		// Let's create this unix socket with permissions to all users. In this way,
		// clients can connect to mysqlproxy mysql server without being mysqlproxy user
		oldMask := syscall.Umask(000)
		mysqlUnixListener, err = newMysqlUnixSocket(*mysqlServerSocketPath, authServer, mh)
		_ = syscall.Umask(oldMask)
		if err != nil {
			log.Exitf("mysql.NewListener failed: %v", err)
			return
		}
		// Listen for unix socket
		go mysqlUnixListener.Accept()
	}
}
92203
func PgAmprocByOid(db XODB, oid pgtypes.Oid) (*PgAmproc, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`tableoid, cmax, xmax, cmin, xmin, oid, ctid, amprocfamily, amproclefttype, amprocrighttype, amprocnum, amproc ` +
		`FROM pg_catalog.pg_amproc ` +
		`WHERE oid = $1`

	// run query
	XOLog(sqlstr, oid)
	pa := PgAmproc{}

	err = db.QueryRow(sqlstr, oid).Scan(&pa.Tableoid, &pa.Cmax, &pa.Xmax, &pa.Cmin, &pa.Xmin, &pa.Oid, &pa.Ctid, &pa.Amprocfamily, &pa.Amproclefttype, &pa.Amprocrighttype, &pa.Amprocnum, &pa.Amproc)
	if err != nil {
		return nil, err
	}

	return &pa, nil
}
253354
func Init() {
	if *ldapAuthConfigFile == "" && *ldapAuthConfigString == "" {
		log.Infof("Not configuring AuthServerLdap because mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are empty")
		return
	}
	if *ldapAuthConfigFile != "" && *ldapAuthConfigString != "" {
		log.Infof("Both mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are non-empty, can only use one.")
		return
	}
	if *ldapAuthMethod != mysql.MysqlClearPassword && *ldapAuthMethod != mysql.MysqlDialog {
		log.Exitf("Invalid mysql_ldap_auth_method value: only support mysql_clear_password or dialog")
	}
	ldapAuthServer := &AuthServerLdap{
		Client:       &ClientImpl{},
		ServerConfig: ServerConfig{},
		Method:       *ldapAuthMethod,
	}

	data := []byte(*ldapAuthConfigString)
	if *ldapAuthConfigFile != "" {
		var err error
		data, err = ioutil.ReadFile(*ldapAuthConfigFile)
		if err != nil {
			log.Exitf("Failed to read mysql_ldap_auth_config_file: %v", err)
		}
	}
	if err := json.Unmarshal(data, ldapAuthServer); err != nil {
		log.Exitf("Error parsing AuthServerLdap config: %v", err)
	}
	mysql.RegisterAuthServerImpl("ldap", ldapAuthServer)
}
1055107
func stringToProtocol(protocol string) uint16 {
	switch strings.ToLower(protocol) {
	case "tcp":
		return uint16(syscall.IPPROTO_TCP)
	case "udp":
		return uint16(syscall.IPPROTO_UDP)
	case "sctp":
		return uint16(syscall.IPPROTO_SCTP)
	}
	return uint16(0)
}
474162
func (s mysqlSource) MySQLConfig() (*mysql.Config, error) {
	cfg, err := mysql.ParseDSN(string(s))
	if err != nil {
		return nil, errors.Wrap(err, `failed to parse DSN`)
	}

	// because _I_ need support for tls, I'm going to handle setting up
	// the tls stuff, by using
	// tls=true&ssl-ca=file=...&ssl-cert=...&ssql-secret=...
	if v, err := strconv.ParseBool(cfg.TLSConfig); err == nil && v {
		sslCa := cfg.Params["ssl-ca"]
		sslCert := cfg.Params["ssl-cert"]
		sslSecret := cfg.Params["ssl-secret"]
		if sslCa == "" || sslCert == "" || sslSecret == "" {
			return nil, errors.New(`to enable tls, you must provide ssl-ca, ssl-cert, and ssl-secret parameters to the DSN`)
		}

		// When comparing two mysql schemas against eachother, we will have
		// multiple calls to RegisterTLSConfig, and in that case we need
		// unique names for both.
		//
		// Here, we do the poor man's UUID, and create a unique name
		b := make([]byte, 16)
		rand.Reader.Read(b)
		b[6] = (b[6] & 0x0F) | 0x40
		b[8] = (b[8] &^ 0x40) | 0x80
		tlsName := fmt.Sprintf("custom-tls-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

		rootCertPool := x509.NewCertPool()
		pem, err := ioutil.ReadFile(sslCa)
		if err != nil {
			return nil, errors.Wrap(err, `failed to read ssl-ca file`)
		}

		if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
			return nil, errors.New(`failed to append ssl-ca PEM to cert pool`)
		}
		certs, err := tls.LoadX509KeyPair(sslCert, sslSecret)
		if err != nil {
			return nil, errors.Wrap(err, `failed to load X509 key pair`)
		}
		mysql.RegisterTLSConfig(tlsName, &tls.Config{
			RootCAs:      rootCertPool,
			Certificates: []tls.Certificate{certs},
		})
		cfg.TLSConfig = tlsName
	}
	return cfg, nil
}
922104
func (c *client) RunMysqlUpgrade(ctx context.Context) error {
	return c.withRetry(ctx, func() error {
		_, err := c.c.RunMysqlUpgrade(ctx, &mysqlctlpb.RunMysqlUpgradeRequest{})
		return err
	})
}
798865
func init() {
	// Unset localhost defaults if certificate file can not be found.
	certFileExists, err := cfgutil.FileExists(opts.RPCCertificateFile)
	if err != nil {
		fatalf("%v", err)
	}
	if !certFileExists {
		opts.RPCConnect = ""
		opts.RPCCertificateFile = ""
	}

	_, err = flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	if opts.TestNet3 && opts.SimNet {
		fatalf("Multiple bitcoin networks may not be used simultaneously")
	}
	var activeNet = &netparams.MainNetParams
	if opts.TestNet3 {
		activeNet = &netparams.TestNet3Params
	} else if opts.SimNet {
		activeNet = &netparams.SimNetParams
	}

	if opts.RPCConnect == "" {
		fatalf("RPC hostname[:port] is required")
	}
	rpcConnect, err := cfgutil.NormalizeAddress(opts.RPCConnect, activeNet.RPCServerPort)
	if err != nil {
		fatalf("Invalid RPC network address `%v`: %v", opts.RPCConnect, err)
	}
	opts.RPCConnect = rpcConnect

	if opts.RPCUsername == "" {
		fatalf("RPC username is required")
	}

	certFileExists, err = cfgutil.FileExists(opts.RPCCertificateFile)
	if err != nil {
		fatalf("%v", err)
	}
	if !certFileExists {
		fatalf("RPC certificate file `%s` not found", opts.RPCCertificateFile)
	}

	if opts.FeeRate.Amount > 1e6 {
		fatalf("Fee rate `%v/kB` is exceptionally high", opts.FeeRate.Amount)
	}
	if opts.FeeRate.Amount < 1e2 {
		fatalf("Fee rate `%v/kB` is exceptionally low", opts.FeeRate.Amount)
	}
	if opts.SourceAccount == opts.DestinationAccount {
		fatalf("Source and destination accounts should not be equal")
	}
	if opts.RequiredConfirmations < 0 {
		fatalf("Required confirmations must be non-negative")
	}
}
1098751
func (dbGorp *DbGorp) dbInit() (err error) {
	if dbGorp.dbInitFn != nil {
		err = dbGorp.dbInitFn(dbGorp)
	}
	return
}
314112
func (p LogicalTableDual) Init(ctx sessionctx.Context) *LogicalTableDual {
	p.baseLogicalPlan = newBaseLogicalPlan(ctx, TypeDual, &p)
	return &p
}
424916
func Init() {
	// Read configuration.
	var found bool
	if Driver, found = revel.Config.String("db.driver"); !found {
		revel.RevelLog.Fatal("db.driver not configured")
	}
	if Spec, found = revel.Config.String("db.spec"); !found {
		revel.RevelLog.Fatal("db.spec not configured")
	}

	// Open a connection.
	var err error
	Db, err = sql.Open(Driver, Spec)
	if err != nil {
		revel.RevelLog.Fatal("Open database connection error", "error", err, "driver", Driver, "spec", Spec)
	}

	revel.OnAppStop(func() {
		revel.RevelLog.Info("Closing the database (from module)")
		if err := Db.Close(); err != nil {
			revel.AppLog.Error("Failed to close the database", "error", err)
		}
	})
}
954119
func initDBPrivEntry(ctx sessionctx.Context, user string, host string, db string) error {
	sql := fmt.Sprintf(`INSERT INTO %s.%s (Host, User, DB) VALUES ('%s', '%s', '%s')`, mysql.SystemDB, mysql.DBTable, host, user, db)
	_, _, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)
	return err
}
122576
func init() {
	addrmgr.UseLogger(amgrLog)
	connmgr.UseLogger(cmgrLog)
	database.UseLogger(bcdbLog)
	blockchain.UseLogger(chanLog)
	indexers.UseLogger(indxLog)
	mining.UseLogger(minrLog)
	cpuminer.UseLogger(minrLog)
	peer.UseLogger(peerLog)
	txscript.UseLogger(scrpLog)
	netsync.UseLogger(syncLog)
	mempool.UseLogger(txmpLog)
}
1100059
func init() {
	dcrsqlite.UseLogger(sqliteLog)
	dcrpg.UseLogger(postgresqlLog)
	stakedb.UseLogger(stakedbLog)
	blockdata.UseLogger(BlockdataLog)
	rpcclient.UseLogger(clientLog)
	rpcutils.UseLogger(clientLog)
	mempool.UseLogger(mempoolLog)
	explorer.UseLogger(expLog)
	api.UseLogger(apiLog)
	insight.UseLogger(iapiLog)
	middleware.UseLogger(apiLog)
	notify.UseLogger(notifyLog)
	pubsub.UseLogger(pubsubLog)
	exchanges.UseLogger(xcBotLog)
	agendas.UseLogger(agendasLog)
	politeia.UseLogger(proposalsLog)
}
463545
func (d MySQLDialect) CreateTableSuffix() string {
	if d.Engine == "" || d.Encoding == "" {
		msg := "gorp - undefined"

		if d.Engine == "" {
			msg += " MySQLDialect.Engine"
		}
		if d.Engine == "" && d.Encoding == "" {
			msg += ","
		}
		if d.Encoding == "" {
			msg += " MySQLDialect.Encoding"
		}
		msg += ". Check that your MySQLDialect was correctly initialized when declared."
		panic(msg)
	}

	return fmt.Sprintf(" engine=%s charset=%s", d.Engine, d.Encoding)
}
477243
func MySQLIP(tablet *topodatapb.Tablet) (string, error) {
	ipAddrs, err := net.LookupHost(MysqlHostname(tablet))
	if err != nil {
		return "", err
	}
	return ipAddrs[0], nil
}
1248144
func (p *Process) initPrimaryDB() error {
	logger := p.Logger.New("fn", "initPrimaryDB")
	logger.Info("initializing primary database")

	dsn := &DSN{
		Host:    "127.0.0.1:" + p.Port,
		User:    "root",
		Timeout: p.OpTimeout,
	}

	db, err := sql.Open("mysql", dsn.String())
	if err != nil {
		logger.Error("error acquiring connection", "err", err)
		return err
	}
	defer db.Close()

	if _, err := db.Exec(fmt.Sprintf(`CREATE USER 'flynn'@'%%' IDENTIFIED BY '%s'`, p.Password)); err != nil && MySQLErrorNumber(err) != 1396 {
		logger.Error("error creating database user", "err", err)
		return err
	}
	if _, err := db.Exec(`GRANT ALL ON *.* TO 'flynn'@'%' WITH GRANT OPTION`); err != nil {
		logger.Error("error granting privileges", "err", err)
		return err
	}
	if _, err := db.Exec(`INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so'`); err != nil && MySQLErrorNumber(err) != 1968 {
		logger.Error("error installing rpl_semi_sync_master", "err", err)
		return err
	}
	if _, err := db.Exec(`FLUSH PRIVILEGES`); err != nil {
		logger.Error("error flushing privileges", "err", err)
		return err
	}

	// If we are running in Singleton mode we don't need to setup replication
	if p.Singleton {
		return nil
	}
	// Enable semi-sync replication on the master.
	master_variables := map[string]string{
		"rpl_semi_sync_master_wait_point":    "AFTER_SYNC",
		"rpl_semi_sync_master_timeout":       "18446744073709551615",
		"rpl_semi_sync_master_enabled":       "1",
		"rpl_semi_sync_master_wait_no_slave": "1",
	}

	for v, val := range master_variables {
		if _, err := db.Exec(fmt.Sprintf(`SET GLOBAL %s = %s`, v, val)); err != nil {
			logger.Error("error setting system variable", "var", v, "val", val, "err", err)
			return err
		}
	}

	return nil
}
1254493
func initTablePrivEntry(ctx sessionctx.Context, user string, host string, db string, tbl string) error {
	sql := fmt.Sprintf(`INSERT INTO %s.%s (Host, User, DB, Table_name, Table_priv, Column_priv) VALUES ('%s', '%s', '%s', '%s', '', '')`, mysql.SystemDB, mysql.TablePrivTable, host, user, db, tbl)
	_, _, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)
	return err
}