Ejemplo n.º 1
0
/* Opens a connection to the db server */
ConnHandle * db_connect(const char *db, const char *user, const char *password, 
		const char *host, int port, int ssl)
{
    ConnHandle *c = (ConnHandle *) malloc (sizeof(ConnHandle));
    if( mysql_init(&c->conn)==NULL ) {
	syslog(LOG_CRIT, "ERROR: [db_connect] Unable to initialize database.");
	free(c);
	return NULL;
    }
    
    if(ssl)
	mysql_ssl_set(&c->conn, NULL, NULL, NULL, NULL, NULL);    

    if( !mysql_real_connect(&c->conn,host,user,password,db,port,NULL,0) ) {
	syslog(LOG_CRIT,"ERROR: [db_connect] Unable to connect to database. %s", mysql_error(&c->conn));
        mysql_close(&c->conn);
	free(c);
	return NULL;
    }
    
    // SET NAMES utf8
    mysql_set_character_set(&c->conn, "utf8");
    
#ifdef DEBUG0
	syslog(LOG_INFO, "DEBUG: [lmsd] Connected with params: db='%s' host='%s' user='******' port='%d' passwd='*'.",
	    db, host, user, port);
#endif
    db_exec(c, "SET NAMES utf8");

    return c;
}
Ejemplo n.º 2
0
/*
 * Opens up a MySQL connection and returns the connection handle.
 */
MYSQL *db_conn(const char *host, const char *db, bool ssl)
{
	MYSQL *ret;
	MYSQL *mysql;

	if (MULTI_TENANT) {
		char tenant[TENANT_MAX + 1];
		char db[sizeof(tenant) + 3] = "rm_";

		get_tenant(env_vars.host, tenant);
		strncat(db, tenant, TENANT_MAX);
		free(db_name);
		db_name = strdup(db);
	}
	mysql = mysql_init(NULL);
	if (ssl)
		mysql_ssl_set(mysql, NULL, NULL, NULL, NULL,
				"DHE-RSA-AES256-SHA:AES128-SHA");
	ret = mysql_real_connect(mysql, host, DB_USER, DB_PASS, db,
			DB_PORT_NUM, DB_SOCKET_NAME, DB_FLAGS);

	if (!ret) {
		d_fprintf(error_log, "Failed to connect to database. Error: "
				"%s\n", mysql_error(mysql));
		mysql = NULL;
	}
	return mysql;
}
/**
 * Opens connection to DB: wropper over mysql_real_connect
 *
 * @param port	DB server port
 * @param ip	DB server IP address
 * @param db    name of DB to connect
 * @param User  User name
 * @param Password  Password
 * @param flag  Connections flags
 * @param ssl   true if ssl should be used
 * @return MYSQL struct or NULL in case of error
 */
MYSQL * open_conn_db_flags(int port, char * ip, char * db, char * User, char * Password, unsigned long flag, bool ssl)
{
    MYSQL * conn = mysql_init(NULL);

    if(conn == NULL)
    {
        fprintf(stdout, "Error: can't create MySQL-descriptor\n");
        return(NULL);
    }

    if (ssl) {mysql_ssl_set(conn, "client-key.pem", "client-cert.pem", "ca.pem", NULL, NULL);}

    if(!mysql_real_connect(conn,
                           ip,
                           User,
                           Password,
                           db,
                           port,
                           NULL,
                           flag
                           ))
    {
        printf("Error: can't connect to database %s\n", mysql_error(conn));
        return(NULL);
    }

    return(conn);
}
Ejemplo n.º 4
0
static MYSQL *doConnect(URL_T url, char **error) {
#define MYSQL_ERROR(e) do {*error = Str_dup(e); goto error;} while (0)
        int port;
        my_bool yes = 1;
        my_bool no = 0;
        volatile int connectTimeout = SQL_DEFAULT_TCP_TIMEOUT;
        unsigned long clientFlags = CLIENT_MULTI_STATEMENTS;
        const char *user, *password, *host, *database, *charset, *timeout;
        const char *unix_socket = URL_getParameter(url, "unix-socket");
        MYSQL *db = mysql_init(NULL);
        if (! db) {
                *error = Str_dup("unable to allocate mysql handler");
                return NULL;
        } 
        if (! (user = URL_getUser(url)))
                if (! (user = URL_getParameter(url, "user")))
                        MYSQL_ERROR("no username specified in URL");
        if (! (password = URL_getPassword(url)))
                if (! (password = URL_getParameter(url, "password")))
                        MYSQL_ERROR("no password specified in URL");
        if (unix_socket) {
		host = "localhost"; // Make sure host is localhost if unix socket is to be used
        } else if (! (host = URL_getHost(url)))
                MYSQL_ERROR("no host specified in URL");
        if ((port = URL_getPort(url)) <= 0)
                MYSQL_ERROR("no port specified in URL");
        if (! (database = URL_getPath(url)))
                MYSQL_ERROR("no database specified in URL");
        else
                database++;
        /* Options */
        if (IS(URL_getParameter(url, "compress"), "true"))
                clientFlags |= CLIENT_COMPRESS;
        if (IS(URL_getParameter(url, "use-ssl"), "true"))
                mysql_ssl_set(db, 0,0,0,0,0);
        if (IS(URL_getParameter(url, "secure-auth"), "true"))
                mysql_options(db, MYSQL_SECURE_AUTH, (const char*)&yes);
        else
                mysql_options(db, MYSQL_SECURE_AUTH, (const char*)&no);
        if ((timeout = URL_getParameter(url, "connect-timeout"))) {
                TRY connectTimeout = Str_parseInt(timeout); ELSE MYSQL_ERROR("invalid connect timeout value"); END_TRY;
        }
        mysql_options(db, MYSQL_OPT_CONNECT_TIMEOUT, (const char*)&connectTimeout);
        if ((charset = URL_getParameter(url, "charset")))
                mysql_options(db, MYSQL_SET_CHARSET_NAME, charset);
#if MYSQL_VERSION_ID >= 50013
        mysql_options(db, MYSQL_OPT_RECONNECT, (const char*)&yes);
#endif
        /* Connect */
        if (mysql_real_connect(db, host, user, password, database, port, unix_socket, clientFlags))
                return db;
        *error = Str_dup(mysql_error(db));
error:
        mysql_close(db);
        return NULL;
}
Ejemplo n.º 5
0
Logger::Level Logger::databaseLevel( Logger::Level databaseLevel ) {
  if ( databaseLevel > NOOPT ) {
    databaseLevel = limit(databaseLevel);
    if ( mDatabaseLevel != databaseLevel ) {
      if ( databaseLevel > NOLOG && mDatabaseLevel <= NOLOG ) {
        if ( !mDbConnected ) {
          if ( !mysql_init( &mDbConnection ) ) {
            Fatal( "Can't initialise database connection: %s", mysql_error( &mDbConnection ) );
            exit( mysql_errno( &mDbConnection ) );
          }
          my_bool reconnect = 1;
          if ( mysql_options( &mDbConnection, MYSQL_OPT_RECONNECT, &reconnect ) )
            Fatal( "Can't set database auto reconnect option: %s", mysql_error( &mDbConnection ) );
          if ( !staticConfig.DB_SSL_CA_CERT.empty() )
            mysql_ssl_set( &mDbConnection, staticConfig.DB_SSL_CLIENT_KEY.c_str(), staticConfig.DB_SSL_CLIENT_CERT.c_str(), staticConfig.DB_SSL_CA_CERT.c_str(), NULL, NULL );
          std::string::size_type colonIndex = staticConfig.DB_HOST.find( ":" );
          if ( colonIndex == std::string::npos ) {
            if ( !mysql_real_connect( &mDbConnection, staticConfig.DB_HOST.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, 0, NULL, 0 ) ) {
              Fatal( "Can't connect to database: %s", mysql_error( &mDbConnection ) );
              exit( mysql_errno( &mDbConnection ) );
            }
          } else {
            std::string dbHost = staticConfig.DB_HOST.substr( 0, colonIndex );
            std::string dbPortOrSocket = staticConfig.DB_HOST.substr( colonIndex+1 );
            if ( dbPortOrSocket[0] == '/' ) {
              if ( !mysql_real_connect( &mDbConnection, NULL, staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, 0, dbPortOrSocket.c_str(), 0 ) ) {
                Fatal( "Can't connect to database: %s", mysql_error( &mDbConnection ) );
                exit( mysql_errno( &mDbConnection ) );
              }  
            } else {
              if ( !mysql_real_connect( &mDbConnection, dbHost.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, atoi(dbPortOrSocket.c_str()), NULL, 0 ) ) {
                Fatal( "Can't connect to database: %s", mysql_error( &mDbConnection ) );
                exit( mysql_errno( &mDbConnection ) );
              }
            }
          } // end if has colon
          unsigned long mysqlVersion = mysql_get_server_version( &mDbConnection );
          if ( mysqlVersion < 50019 )
            if ( mysql_options( &mDbConnection, MYSQL_OPT_RECONNECT, &reconnect ) )
              Fatal( "Can't set database auto reconnect option: %s", mysql_error( &mDbConnection ) );
          if ( mysql_select_db( &mDbConnection, staticConfig.DB_NAME.c_str() ) ) {
            Fatal( "Can't select database: %s", mysql_error( &mDbConnection ) );
            exit( mysql_errno( &mDbConnection ) );
          }
          mDbConnected = true;
        } // end if ! mDbConnected
      } // end if ( databaseLevel > NOLOG && mDatabaseLevel <= NOLOG )
      mDatabaseLevel = databaseLevel;
    } // end if ( mDatabaseLevel != databaseLevel )
  } // end if ( databaseLevel > NOOPT )

  return( mDatabaseLevel );
}
Ejemplo n.º 6
0
static VALUE set_ssl_options(VALUE self, VALUE key, VALUE cert, VALUE ca, VALUE capath, VALUE cipher) {
  GET_CLIENT(self);

  mysql_ssl_set(wrapper->client,
      NIL_P(key)    ? NULL : StringValueCStr(key),
      NIL_P(cert)   ? NULL : StringValueCStr(cert),
      NIL_P(ca)     ? NULL : StringValueCStr(ca),
      NIL_P(capath) ? NULL : StringValueCStr(capath),
      NIL_P(cipher) ? NULL : StringValueCStr(cipher));

  return self;
}
Ejemplo n.º 7
0
/*	ssl_set(key=nil, cert=nil, ca=nil, capath=nil, cipher=nil)	*/
static VALUE ssl_set(int argc, VALUE* argv, VALUE obj)
{
    VALUE key, cert, ca, capath, cipher;
    char *s_key, *s_cert, *s_ca, *s_capath, *s_cipher;
    MYSQL* m = GetHandler(obj);
    rb_scan_args(argc, argv, "05", &key, &cert, &ca, &capath, &cipher);
    s_key = NILorSTRING(key);
    s_cert = NILorSTRING(cert);
    s_ca = NILorSTRING(ca);
    s_capath = NILorSTRING(capath);
    s_cipher = NILorSTRING(cipher);
    mysql_ssl_set(m, s_key, s_cert, s_ca, s_capath, s_cipher);
    return obj;
}
Ejemplo n.º 8
0
static VALUE set_ssl_options(VALUE self, VALUE key, VALUE cert, VALUE ca, VALUE capath, VALUE cipher)
{
  MYSQL * client;
  Data_Get_Struct(self, MYSQL, client);

  if(!NIL_P(ca) || !NIL_P(key)) {
    mysql_ssl_set(client,
        NIL_P(key) ? NULL : StringValuePtr(key),
        NIL_P(cert) ? NULL : StringValuePtr(cert),
        NIL_P(ca) ? NULL : StringValuePtr(ca),
        NIL_P(capath) ? NULL : StringValuePtr(capath),
        NIL_P(cipher) ? NULL : StringValuePtr(cipher));
  }

  return self;
}
Ejemplo n.º 9
0
/*
 * plmysql_connect_single -
 * used to reconnect to a single database when one is down or none is
 * connected yet. Log all errors and set the stat field of host accordingly
 */
static void plmysql_connect_single(DICT_MYSQL *dict_mysql, HOST *host)
{
    if ((host->db = mysql_init(NULL)) == NULL)
	msg_fatal("dict_mysql: insufficient memory");
    if (dict_mysql->option_file)
	mysql_options(host->db, MYSQL_READ_DEFAULT_FILE, dict_mysql->option_file);
    if (dict_mysql->option_group)
	mysql_options(host->db, MYSQL_READ_DEFAULT_GROUP, dict_mysql->option_group);
#if defined(MYSQL_VERSION_ID) && MYSQL_VERSION_ID >= 40000
    if (dict_mysql->tls_key_file || dict_mysql->tls_cert_file ||
	dict_mysql->tls_CAfile || dict_mysql->tls_CApath || dict_mysql->tls_ciphers)
	mysql_ssl_set(host->db,
		      dict_mysql->tls_key_file, dict_mysql->tls_cert_file,
		      dict_mysql->tls_CAfile, dict_mysql->tls_CApath,
		      dict_mysql->tls_ciphers);
#if MYSQL_VERSION_ID >= 50023
    if (dict_mysql->tls_verify_cert != -1)
	mysql_options(host->db, MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
		      &dict_mysql->tls_verify_cert);
#endif
#endif
    if (mysql_real_connect(host->db,
			   (host->type == TYPEINET ? host->name : 0),
			   dict_mysql->username,
			   dict_mysql->password,
			   dict_mysql->dbname,
			   host->port,
			   (host->type == TYPEUNIX ? host->name : 0),
			   0)) {
	if (msg_verbose)
	    msg_info("dict_mysql: successful connection to host %s",
		     host->hostname);
	host->stat = STATACTIVE;
    } else {
	msg_warn("connect to mysql server %s: %s",
		 host->hostname, mysql_error(host->db));
	plmysql_down_host(host);
    }
}
Ejemplo n.º 10
0
static bool my_open(void)
{
	MYSQL *db;
	my_bool reconnect = 1;

	if (mysql_library_init(0, NULL, NULL))
		goto err_out;

	db = mysql_init(NULL);
	if (!db)
		goto err_out_lib;

	mysql_ssl_set(db, NULL, NULL, NULL, NULL, NULL);
	mysql_options(db, MYSQL_OPT_RECONNECT, &reconnect);
	mysql_options(db, MYSQL_OPT_COMPRESS, NULL);

	if (!mysql_real_connect(db, srv.db_host, srv.db_username,
				srv.db_password, srv.db_name,
				srv.db_port > 0 ? srv.db_port : 0,
				NULL, 0))
		goto err_out_db;

	srv.db_cxn = db;
	if (srv.db_stmt_pwdb == NULL || !*srv.db_stmt_pwdb)
		srv.db_stmt_pwdb = strdup(DEFAULT_STMT_PWDB);
	if (srv.db_stmt_sharelog == NULL || !*srv.db_stmt_sharelog)
		srv.db_stmt_sharelog = strdup(DEFAULT_STMT_SHARELOG);
	return true;

err_out_db:
	mysql_close(db);
err_out_lib:
	mysql_library_end();
err_out:
	return false;
}
Ejemplo n.º 11
0
Archivo: do_mysql.c Proyecto: NZX/do
static void full_connect(VALUE self, MYSQL* db) {
  // Check to see if we're on the db machine.  If so, try to use the socket
  VALUE r_host, r_user, r_password, r_path, r_query, r_port;

  const char *host = "localhost", *user = "******"; 
  char *database = NULL, *socket = NULL, *password = NULL, *path = NULL;
  VALUE encoding = Qnil;

  MYSQL *result;

  int port = 3306;
  unsigned long client_flags = 0;
  int encoding_error;

  if((r_host = rb_iv_get(self, "@host")) != Qnil) {
    host     = StringValuePtr(r_host);
  }

  if((r_user = rb_iv_get(self, "@user")) != Qnil) {
    user     = StringValuePtr(r_user);
  }

  if((r_password = rb_iv_get(self, "@password")) != Qnil) {
    password = StringValuePtr(r_password);
  }

  if((r_port = rb_iv_get(self, "@port")) != Qnil) {
    port = NUM2INT(r_port);
  }

  if((r_path = rb_iv_get(self, "@path")) != Qnil) {
    path = StringValuePtr(r_path);
    database = strtok(path, "/");
  }

  if (NULL == database || 0 == strlen(database)) {
    rb_raise(eConnectionError, "Database must be specified");
  }

  r_query        = rb_iv_get(self, "@query");

  if (0 == strcasecmp(host, "localhost")) {
    socket = get_uri_option(r_query, "socket");
    if (NULL != socket) {
      rb_iv_set(self, "@using_socket", Qtrue);
    }
  }

#ifdef HAVE_MYSQL_SSL_SET
  char *ssl_client_key, *ssl_client_cert, *ssl_ca_cert, *ssl_ca_path, *ssl_cipher;
  VALUE r_ssl;

  if(rb_obj_is_kind_of(r_query, rb_cHash)) {
    r_ssl = rb_hash_aref(r_query, rb_str_new2("ssl"));

    if(rb_obj_is_kind_of(r_ssl, rb_cHash)) {
      ssl_client_key  = get_uri_option(r_ssl, "client_key");
      ssl_client_cert = get_uri_option(r_ssl, "client_cert");
      ssl_ca_cert     = get_uri_option(r_ssl, "ca_cert");
      ssl_ca_path     = get_uri_option(r_ssl, "ca_path");
      ssl_cipher      = get_uri_option(r_ssl, "cipher");

      assert_file_exists(ssl_client_key,  "client_key doesn't exist");
      assert_file_exists(ssl_client_cert, "client_cert doesn't exist");
      assert_file_exists(ssl_ca_cert,     "ca_cert doesn't exist");

      mysql_ssl_set(db, ssl_client_key, ssl_client_cert, ssl_ca_cert, ssl_ca_path, ssl_cipher);
    } else if(r_ssl != Qnil) {
      rb_raise(rb_eArgError, "ssl must be passed a hash");
    }
  }
#endif

  result = (MYSQL *)mysql_real_connect(
    db,
    host,
    user,
    password,
    database,
    port,
    socket,
    client_flags
  );

  if (NULL == result) {
    raise_error(self, db, Qnil);
  }

#ifdef HAVE_MYSQL_SSL_SET
  const char *ssl_cipher_used = mysql_get_ssl_cipher(db);

  if (NULL != ssl_cipher_used) {
    rb_iv_set(self, "@ssl_cipher", rb_str_new2(ssl_cipher_used));
  }
#endif

#ifdef MYSQL_OPT_RECONNECT
  my_bool reconnect = 1;
  mysql_options(db, MYSQL_OPT_RECONNECT, &reconnect);
#endif

  // Set the connections character set
  encoding = rb_iv_get(self, "@encoding");

  VALUE my_encoding = rb_hash_aref(CONST_GET(mEncoding, "MAP"), encoding);
  if(my_encoding != Qnil) {
    encoding_error = mysql_set_character_set(db, rb_str_ptr_readonly(my_encoding));
    if (0 != encoding_error) {
      raise_error(self, db, Qnil);
    } else {
#ifdef HAVE_RUBY_ENCODING_H
      rb_iv_set(self, "@encoding_id", INT2FIX(rb_enc_find_index(rb_str_ptr_readonly(encoding))));
#endif
      rb_iv_set(self, "@my_encoding", my_encoding);
    }
  } else {
    rb_warn("Encoding %s is not a known Ruby encoding for MySQL\n", rb_str_ptr_readonly(encoding));
    rb_iv_set(self, "@encoding", rb_str_new2("UTF-8"));
#ifdef HAVE_RUBY_ENCODING_H
    rb_iv_set(self, "@encoding_id", INT2FIX(rb_enc_find_index("UTF-8")));
#endif
    rb_iv_set(self, "@my_encoding", rb_str_new2("utf8"));
  }

  // Disable sql_auto_is_null
  cCommand_execute(Qnil, self, db, rb_str_new2("SET sql_auto_is_null = 0"));
  // removed NO_AUTO_VALUE_ON_ZERO because of MySQL bug http://bugs.mysql.com/bug.php?id=42270
  // added NO_BACKSLASH_ESCAPES so that backslashes should not be escaped as in other databases
   
  //4.x versions do not support certain session parameters  
  if(mysql_get_server_version(db) < 50000 ){
    cCommand_execute(Qnil, self, db, rb_str_new2("SET SESSION sql_mode = 'ANSI,NO_DIR_IN_CREATE,NO_UNSIGNED_SUBTRACTION'"));
  }else{
    cCommand_execute(Qnil, self, db, rb_str_new2("SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'"));
  }
 
  rb_iv_set(self, "@connection", Data_Wrap_Struct(rb_cObject, 0, 0, db));
}
Ejemplo n.º 12
0
void do_mysql_full_connect(VALUE self, MYSQL *db) {
  VALUE r_host = rb_iv_get(self, "@host");
  const char *host = "localhost";

  if (r_host != Qnil) {
    host = StringValuePtr(r_host);
  }

  VALUE r_user = rb_iv_get(self, "@user");
  const char *user = "******";

  if (r_user != Qnil) {
    user = StringValuePtr(r_user);
  }

  VALUE r_password = rb_iv_get(self, "@password");
  char *password = NULL;

  if (r_password != Qnil) {
    password = StringValuePtr(r_password);
  }

  VALUE r_port = rb_iv_get(self, "@port");
  int port = 3306;

  if (r_port != Qnil) {
    port = NUM2INT(r_port);
  }

  VALUE r_path = rb_iv_get(self, "@path");
  char *path = NULL;
  char *database = NULL;

  if (r_path != Qnil) {
    path = StringValuePtr(r_path);
    database = strtok(path, "/"); // not threadsafe
  }

  if (!database || !*database) {
    rb_raise(eConnectionError, "Database must be specified");
  }

  VALUE r_query = rb_iv_get(self, "@query");
  char *socket = NULL;

  // Check to see if we're on the db machine.  If so, try to use the socket
  if (strcasecmp(host, "localhost") == 0) {
    socket = data_objects_get_uri_option(r_query, "socket");

    if (socket) {
      rb_iv_set(self, "@using_socket", Qtrue);
    }
  }

#ifdef HAVE_MYSQL_SSL_SET
  char *ssl_client_key, *ssl_client_cert, *ssl_ca_cert, *ssl_ca_path, *ssl_cipher;
  VALUE r_ssl;

  if (rb_obj_is_kind_of(r_query, rb_cHash)) {
    r_ssl = rb_hash_aref(r_query, rb_str_new2("ssl"));

    if (rb_obj_is_kind_of(r_ssl, rb_cHash)) {
      ssl_client_key  = data_objects_get_uri_option(r_ssl, "client_key");
      ssl_client_cert = data_objects_get_uri_option(r_ssl, "client_cert");
      ssl_ca_cert     = data_objects_get_uri_option(r_ssl, "ca_cert");
      ssl_ca_path     = data_objects_get_uri_option(r_ssl, "ca_path");
      ssl_cipher      = data_objects_get_uri_option(r_ssl, "cipher");

      data_objects_assert_file_exists(ssl_client_key,  "client_key doesn't exist");
      data_objects_assert_file_exists(ssl_client_cert, "client_cert doesn't exist");
      data_objects_assert_file_exists(ssl_ca_cert,     "ca_cert doesn't exist");

      mysql_ssl_set(db, ssl_client_key, ssl_client_cert, ssl_ca_cert, ssl_ca_path, ssl_cipher);
    }
    else if (r_ssl != Qnil) {
      rb_raise(rb_eArgError, "ssl must be passed a hash");
    }
  }
#endif

  unsigned long client_flags = 0;

  MYSQL *result = mysql_real_connect(
    db,
    host,
    user,
    password,
    database,
    port,
    socket,
    client_flags
  );

  if (!result) {
    do_mysql_raise_error(self, db, Qnil);
  }

#ifdef HAVE_MYSQL_GET_SSL_CIPHER
  const char *ssl_cipher_used = mysql_get_ssl_cipher(db);

  if (ssl_cipher_used) {
    rb_iv_set(self, "@ssl_cipher", rb_str_new2(ssl_cipher_used));
  }
#endif

#ifdef MYSQL_OPT_RECONNECT
  my_bool reconnect = 1;
  mysql_options(db, MYSQL_OPT_RECONNECT, &reconnect);
#endif

  // We only support encoding for MySQL versions providing mysql_set_character_set.
  // Without this function there are potential issues with mysql_real_escape_string
  // since that doesn't take the character set into consideration when setting it
  // using a SET CHARACTER SET query. Since we don't want to stimulate these possible
  // issues we simply ignore it and assume the user has configured this correctly.

#ifdef HAVE_MYSQL_SET_CHARACTER_SET
  // Set the connections character set
  VALUE encoding = rb_iv_get(self, "@encoding");
  VALUE my_encoding = rb_hash_aref(data_objects_const_get(mEncoding, "MAP"), encoding);

  if (my_encoding != Qnil) {
    int encoding_error = mysql_set_character_set(db, rb_str_ptr_readonly(my_encoding));

    if (encoding_error != 0) {
      do_mysql_raise_error(self, db, Qnil);
    }
    else {
#ifdef HAVE_RUBY_ENCODING_H
      rb_iv_set(self, "@encoding_id", INT2FIX(rb_enc_find_index(rb_str_ptr_readonly(encoding))));
#endif

      rb_iv_set(self, "@my_encoding", my_encoding);
    }
  }
  else {
    rb_warn("Encoding %s is not a known Ruby encoding for MySQL\n", rb_str_ptr_readonly(encoding));
    rb_iv_set(self, "@encoding", rb_str_new2("UTF-8"));
#ifdef HAVE_RUBY_ENCODING_H
    rb_iv_set(self, "@encoding_id", INT2FIX(rb_enc_find_index("UTF-8")));
#endif
    rb_iv_set(self, "@my_encoding", rb_str_new2("utf8"));
  }
#endif

  // Disable sql_auto_is_null
  do_mysql_cCommand_execute(Qnil, self, db, rb_str_new2("SET sql_auto_is_null = 0"));
  // removed NO_AUTO_VALUE_ON_ZERO because of MySQL bug http://bugs.mysql.com/bug.php?id=42270
  // added NO_BACKSLASH_ESCAPES so that backslashes should not be escaped as in other databases

// For really anscient MySQL versions we don't attempt any strictness
#ifdef HAVE_MYSQL_GET_SERVER_VERSION
  //4.x versions do not support certain session parameters
  if (mysql_get_server_version(db) < 50000) {
    do_mysql_cCommand_execute(Qnil, self, db, rb_str_new2("SET SESSION sql_mode = 'ANSI,NO_DIR_IN_CREATE,NO_UNSIGNED_SUBTRACTION'"));
  }
  else {
    do_mysql_cCommand_execute(Qnil, self, db, rb_str_new2("SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'"));
  }
#endif

  rb_iv_set(self, "@connection", Data_Wrap_Struct(rb_cObject, 0, 0, db));
}
Ejemplo n.º 13
0
int main (int argc, char *argv[])
{


    trace(argc, argv);

    int opt_err;

    MY_INIT (argv[0]);
    load_defaults ("my", client_groups, &argc, &argv);

    if ((opt_err = handle_options (&argc, &argv, my_opts, get_one_option)))
        exit (opt_err);

    /* solicit password if necessary */
    if (ask_password)
        opt_password = get_tty_password (NULL);

    /* get database name if present on command line */
    if (argc > 0)
    {
        opt_db_name = argv[0];
        --argc;
        ++argv;
    }

    /* initialize client library */
    if (mysql_library_init (0, NULL, NULL))
    {
        print_error (NULL, "mysql_library_init() failed");
        exit (1);
    }

    /* initialize connection handler */
    conn = mysql_init (NULL);
    if (conn == NULL)
    {
        print_error (NULL, "mysql_init() failed (probably out of memory)");
        exit (1);
    }

#ifdef HAVE_OPENSSL
    /* pass SSL information to client library */
    if (opt_use_ssl)
        mysql_ssl_set (conn, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
                       opt_ssl_capath, opt_ssl_cipher);
#if (MYSQL_VERSION_ID >= 50023 && MYSQL_VERSION_ID < 50100) \
    || MYSQL_VERSION_ID >= 50111
    mysql_options (conn,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                   (char*)&opt_ssl_verify_server_cert);
#endif
#endif

    /* connect to server */
    if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
                            opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL)
    {
        print_error (conn, "mysql_real_connect() failed");
        mysql_close (conn);
        exit (1);
    }

    process_prepared_statements (conn);

    /* disconnect from server, terminate client library */
    mysql_close (conn);
    mysql_library_end ();
    exit (0);
}
Ejemplo n.º 14
0
int MysqlDatabase::connect(bool create_new) {
  if (host.empty() || db.empty())
    return DB_CONNECTION_NONE;

  //CLog::Log(LOGDEBUG, "Connecting to mysql:%s:%s", host.c_str(), db.c_str());

  try
  {
    disconnect();

    if (conn == NULL) {
      conn = mysql_init(conn);
      mysql_ssl_set(
        conn, 
        key.empty() ? NULL : key.c_str(), 
        cert.empty() ? NULL : cert.c_str(), 
        ca.empty() ? NULL : ca.c_str(), 
        capath.empty() ? NULL : capath.c_str(), 
        ciphers.empty() ? NULL : ciphers.c_str());
    }

    if (!CWakeOnAccess::GetInstance().WakeUpHost(host, "MySQL : " + db))
      return DB_CONNECTION_NONE;

    // establish connection with just user credentials
    if (mysql_real_connect(conn, host.c_str(),
                                 login.c_str(),
                                 passwd.c_str(),
                                 NULL,
                                 atoi(port.c_str()),
                                 NULL,
                                 compression ? CLIENT_COMPRESS : 0) != NULL)
    {
      // disable mysql autocommit since we handle it
      //mysql_autocommit(conn, false);

      // enforce utf8 charset usage
      default_charset = mysql_character_set_name(conn);
      if(mysql_set_character_set(conn, "utf8")) // returns 0 on success
      {
        CLog::Log(LOGERROR, "Unable to set utf8 charset: %s [%d](%s)",
                  db.c_str(), mysql_errno(conn), mysql_error(conn));
      }

      // check existence
      if (exists())
      {
        // nothing to see here
      }
      else if (create_new)
      {
        char sqlcmd[512];
        int ret;

        sprintf(sqlcmd, "CREATE DATABASE `%s` CHARACTER SET utf8 COLLATE utf8_general_ci", db.c_str());
        if ( (ret=query_with_reconnect(sqlcmd)) != MYSQL_OK )
        {
          throw DbErrors("Can't create new database: '%s' (%d)", db.c_str(), ret);
        }
      }

      if (mysql_select_db(conn, db.c_str()) == 0)
      {
        active = true;
        return DB_CONNECTION_OK;
      }
    }

    // if we failed above, either credentials were incorrect or the database didn't exist
    if (mysql_errno(conn) == ER_BAD_DB_ERROR && create_new)
    {

      if (create() == MYSQL_OK)
      {
        active = true;

        return DB_CONNECTION_OK;
      }
    }

    CLog::Log(LOGERROR, "Unable to open database: %s [%d](%s)",
              db.c_str(), mysql_errno(conn), mysql_error(conn));

    return DB_CONNECTION_NONE;
  }
  catch(...)
  {
    CLog::Log(LOGERROR, "Unable to open database: %s (%u)",
              db.c_str(), GetLastError());
  }
  return DB_CONNECTION_NONE;
}
Ejemplo n.º 15
0
int main(int argc, char **argv)
{
  int error;
  my_bool first_argument_uses_wildcards=0;
  char *wild;
  MYSQL mysql;
  MY_INIT(argv[0]);
  sf_leaking_memory=1; /* don't report memory leaks on early exits */
  if (load_defaults("my",load_default_groups,&argc,&argv))
    exit(1);

  get_options(&argc,&argv);

  sf_leaking_memory=0; /* from now on we cleanup properly */
  wild=0;
  if (argc)
  {
    char *pos= argv[argc-1], *to;
    for (to= pos ; *pos ; pos++, to++)
    {
      switch (*pos) {
      case '*':
	*pos= '%';
	first_argument_uses_wildcards= 1;
	break;
      case '?':
	*pos= '_';
	first_argument_uses_wildcards= 1;
	break;
      case '%':
      case '_':
	first_argument_uses_wildcards= 1;
	break;
      case '\\':
	pos++;
      default: break;
      }
      *to= *pos;
    }    
    *to= *pos; /* just to copy a '\0'  if '\\' was used */
  }
  if (first_argument_uses_wildcards)
    wild= argv[--argc];
  else if (argc == 3)			/* We only want one field */
    wild= argv[--argc];

  if (argc > 2)
  {
    fprintf(stderr,"%s: Too many arguments\n",my_progname);
    exit(1);
  }
  mysql_init(&mysql);
  if (opt_compress)
    mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
    mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
		  opt_ssl_capath, opt_ssl_cipher);
  mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                (char*)&opt_ssl_verify_server_cert);
#endif
  if (opt_protocol)
    mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#ifdef HAVE_SMEM
  if (shared_memory_base_name)
    mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
  mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);

  if (opt_plugin_dir && *opt_plugin_dir)
    mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);

  if (opt_default_auth && *opt_default_auth)
    mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);

  if (!(mysql_real_connect(&mysql,host,user,opt_password,
			   (first_argument_uses_wildcards) ? "" :
                           argv[0],opt_mysql_port,opt_mysql_unix_port,
			   0)))
  {
    fprintf(stderr,"%s: %s\n",my_progname,mysql_error(&mysql));
    exit(1);
  }
  mysql.reconnect= 1;

  switch (argc) {
  case 0:  error=list_dbs(&mysql,wild); break;
  case 1:
    if (opt_status)
      error=list_table_status(&mysql,argv[0],wild);
    else
      error=list_tables(&mysql,argv[0],wild);
    break;
  default:
    if (opt_status && ! wild)
      error=list_table_status(&mysql,argv[0],argv[1]);
    else
      error=list_fields(&mysql,argv[0],argv[1],wild);
    break;
  }
  mysql_close(&mysql);			/* Close & free connection */
  my_free(opt_password);
#ifdef HAVE_SMEM
  my_free(shared_memory_base_name);
#endif
  my_end(my_end_arg);
  exit(error ? 1 : 0);
  return 0;				/* No compiler warnings */
}
Ejemplo n.º 16
0
/*++

ConnectionOpen

    Opens a server connection.

Arguments:
    context - Opaque context passed to <PoolCreate>.

    data    - Pointer to a pointer that receives the DB_CONTEXT structure.

Return Values:
    If the function succeeds, the return value is nonzero (true).

    If the function fails, the return value is zero (false).

--*/
static BOOL FCALL ConnectionOpen(VOID *context, VOID **data)
{
    DB_CONTEXT          *db;
    DB_CONFIG_SERVER    *server;
    DWORD               error;
    DWORD               i;
    INT                 attempt;
    INT                 attemptMax;
    LONG                serverIndex;
    LONG                serverNextIndex;
    MYSQL               *connection;
    my_bool             optReconnect;
    UINT                optTimeout;

    UNREFERENCED_PARAMETER(context);
    ASSERT(data != NULL);
    TRACE("context=%p data=%p", context, data);

    db = MemAllocate(sizeof(DB_CONTEXT));
    if (db == NULL) {
        LOG_ERROR("Unable to allocate memory for database context.");

        error = ERROR_NOT_ENOUGH_MEMORY;
        goto failed;
    }
    ZeroMemory(db, sizeof(DB_CONTEXT));

    //
    // Have the MySQL client library allocate the handle structure for us. This is
    // in case the MYSQL structure changes in a future version of the client library.
    //
    db->handle = mysql_init(NULL);
    if (db->handle == NULL) {
        LOG_ERROR("Unable to allocate memory for MySQL handle.");

        error = ERROR_NOT_ENOUGH_MEMORY;
        goto failed;
    }

    // If the maximum number of attempts were not specified, try all servers
    if (dbConfigGlobal.connAttempts > 0) {
        attemptMax = dbConfigGlobal.connAttempts;
    } else {
        attemptMax = dbConfigServerCount;
    }

    for (attempt = 0; attempt < attemptMax; attempt++) {
        // Use the most recent server for the connection attempt
        serverIndex = dbIndex;
        server      = &dbConfigServers[serverIndex];

        TRACE("Connecting to server #%d [%s] on attempt %lu/%lu.",
            serverIndex, server->name, attempt+1, attemptMax);

        // Set connection options
        optTimeout = (UINT)dbConfigGlobal.connTimeout;
        if (mysql_options(db->handle, MYSQL_OPT_CONNECT_TIMEOUT, &optTimeout) != 0) {
            TRACE("Failed to set connection timeout option.");
        }

        optReconnect = FALSE;
        if (mysql_options(db->handle, MYSQL_OPT_RECONNECT, &optReconnect) != 0) {
            TRACE("Failed to set reconnection option.");
        }

        if (server->compression) {
            if (mysql_options(db->handle, MYSQL_OPT_COMPRESS, 0) != 0) {
                TRACE("Failed to set compression option.");
            }
        }

        if (server->sslEnable) {
            //
            // This function always returns 0. If the SSL setup is incorrect,
            // the call to mysql_real_connect() will return an error.
            //
            mysql_ssl_set(db->handle, server->sslKeyFile, server->sslCertFile,
                server->sslCAFile, server->sslCAPath, server->sslCiphers);
        }

        // Attempt connection with server
        connection = mysql_real_connect(db->handle,
            server->host, server->user, server->password,
            server->database, server->port, NULL, CLIENT_INTERACTIVE);

        if (connection == NULL) {
            LOG_ERROR("Unable to connect to server [%s]: %s",
                server->name, mysql_error(db->handle));

        } else if (mysql_get_server_version(db->handle) < 50019) {
            LOG_ERROR("Unsupported version of MySQL Server [%s]: running v%s, must be v5.0.19 or newer.",
                server->name, mysql_get_server_info(db->handle));

        } else {
            // Pointer values should be the same as from mysql_init()
            ASSERT(connection == db->handle);

            // Allocate pre-compiled statement structures
            for (i = 0; i < ELEMENT_COUNT(db->stmt); i++) {
                db->stmt[i] = mysql_stmt_init(db->handle);
                if (db->stmt[i] == NULL) {
                    LOG_ERROR("Unable to allocate memory for statement structure.");

                    error = ERROR_NOT_ENOUGH_MEMORY;
                    goto failed;
                }
            }

            // Successfully connected, set the global server index
            InterlockedExchange(&dbIndex, serverIndex);

            // Update context's server index and time stamps
            db->index = serverIndex;
            GetSystemTimeAsFileTime(&db->created.fileTime);
            db->used.value = db->created.value;

            LOG_INFO("Connected to %s [%s], running MySQL Server v%s.",
                mysql_get_host_info(db->handle), server->name,
                mysql_get_server_info(db->handle));

            *data = db;
            return TRUE;
        }

        // Unsuccessful connection, continue to the next server
        serverNextIndex = serverIndex + 1;
        if (serverNextIndex >= (LONG)dbConfigServerCount) {
            serverNextIndex = 0;
        }

        //
        // Compare the current server index before swapping values in the
        // event that another thread has already changed the index.
        //
        InterlockedCompareExchange(&dbIndex, serverNextIndex, serverIndex);
    }

    // Unable to connect to any servers
    error = ERROR_CONNECTION_REFUSED;

failed:
    if (db != NULL) {
        ConnectionClose(NULL, db);
    }
    SetLastError(error);
    return FALSE;
}
Ejemplo n.º 17
0
static int driver_mysql_connect(struct sql_db *_db)
{
	struct mysql_db *db = (struct mysql_db *)_db;
	const char *unix_socket, *host;
	unsigned long client_flags = db->client_flags;
	unsigned int secs_used;
	bool failed;

	i_assert(db->api.state == SQL_DB_STATE_DISCONNECTED);

	sql_db_set_state(&db->api, SQL_DB_STATE_CONNECTING);

	if (*db->host == '/') {
		unix_socket = db->host;
		host = NULL;
	} else {
		unix_socket = NULL;
		host = db->host;
	}

	if (db->option_file != NULL) {
		mysql_options(db->mysql, MYSQL_READ_DEFAULT_FILE,
			      db->option_file);
	}

	mysql_options(db->mysql, MYSQL_READ_DEFAULT_GROUP,
		      db->option_group != NULL ? db->option_group : "client");

	if (!db->ssl_set && (db->ssl_ca != NULL || db->ssl_ca_path != NULL)) {
#ifdef HAVE_MYSQL_SSL
		mysql_ssl_set(db->mysql, db->ssl_key, db->ssl_cert,
			      db->ssl_ca, db->ssl_ca_path
#ifdef HAVE_MYSQL_SSL_CIPHER
			      , db->ssl_cipher
#endif
			     );
		db->ssl_set = TRUE;
#else
		i_fatal("mysql: SSL support not compiled in "
			"(remove ssl_ca and ssl_ca_path settings)");
#endif
	}

	alarm(SQL_CONNECT_TIMEOUT_SECS);
#ifdef CLIENT_MULTI_RESULTS
	client_flags |= CLIENT_MULTI_RESULTS;
#endif
	/* CLIENT_MULTI_RESULTS allows the use of stored procedures */
	failed = mysql_real_connect(db->mysql, host, db->user, db->password,
				    db->dbname, db->port, unix_socket,
				    client_flags) == NULL;
	secs_used = SQL_CONNECT_TIMEOUT_SECS - alarm(0);
	if (failed) {
		/* connecting could have taken a while. make sure that any
		   timeouts that get added soon will get a refreshed
		   timestamp. */
		io_loop_time_refresh();

		if (db->api.connect_delay < secs_used)
			db->api.connect_delay = secs_used;
		sql_db_set_state(&db->api, SQL_DB_STATE_DISCONNECTED);
		i_error("%s: Connect failed to database (%s): %s - "
			"waiting for %u seconds before retry",
			mysql_prefix(db), db->dbname,
			mysql_error(db->mysql), db->api.connect_delay);
		return -1;
	} else {
		db->last_success = ioloop_time;
		sql_db_set_state(&db->api, SQL_DB_STATE_IDLE);
		return 1;
	}
}
Ejemplo n.º 18
0
int wsql_connection__init__(wsql_connection *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {
        "host", "user", "password", "database",
        "port", "socket_name", "connect_timeout", "compress",
        "init_command", "read_default_file", "read_default_group", "client_flag",
        "ssl", "local_infile", "nonblocking", NULL
    };

    TRACE1("%p", self);

    MYSQL *conn = NULL;
    PyObject *ssl = NULL;
#if HAVE_OPENSSL
    char *key = NULL, *cert = NULL, *ca = NULL, *capath = NULL, *cipher = NULL;
#endif
    char *host = NULL, *user = NULL, *password = NULL,
          *database = NULL, *socket_name = NULL,
           *init_command=NULL, *read_default_file=NULL, *read_default_group=NULL;

    unsigned int port = 0, client_flag = 0, connect_timeout = 0;
    int nonblocking = 0, compress = -1, local_infile = -1;

    self->open = 0;
    self->autocommit = 0;
    self->connected = 0;
    CHECK_SERVER(-1);

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ssssIsIisssIOii:connect",
                                     kwlist,
                                     &host, &user, &password, &database,
                                     &port, &socket_name, &connect_timeout, &compress,
                                     &init_command, &read_default_file, &read_default_group,
                                     &client_flag, &ssl, &local_infile, &nonblocking))
    {
        return -1;
    }


    if (nonblocking)
    {
#ifndef HAVE_ASYNCIO
        PyErr_SetString(wsql_not_supported_error, "The asynchronous operations does not supported.");
        return -1;
#endif
    }

#define GET_ITEM_STRING(k, t, d) \
{ t = PyMapping_GetItemString(d, #k);\
  if (t) { k = PyString_AsString(t); Py_DECREF(t);} \
  PyErr_Clear(); \
}

    if (ssl)
    {
#if HAVE_OPENSSL
        PyObject *value = NULL;
        GET_ITEM_STRING(ca, value, ssl);
        GET_ITEM_STRING(capath, value, ssl);
        GET_ITEM_STRING(cert, value, ssl);
        GET_ITEM_STRING(key, value, ssl);
        GET_ITEM_STRING(cipher, value, ssl);
#else
        PyErr_SetString(wsql_not_supported_error, "client library does not have SSL support");
        return -1;
#endif
    }
#undef GET_ITEM_STRING

    Py_BEGIN_ALLOW_THREADS ;
    conn = mysql_init(&(self->connection));

    if (conn != NULL)
    {
        if (compress != -1)
        {
            mysql_options(conn, MYSQL_OPT_COMPRESS, 0);
            client_flag |= CLIENT_COMPRESS;
        }
        if (connect_timeout)
            mysql_options(conn, MYSQL_OPT_CONNECT_TIMEOUT, (char *)&connect_timeout);
        if (init_command != NULL)
            mysql_options(conn, MYSQL_INIT_COMMAND, init_command);
        if (read_default_file != NULL)
            mysql_options(conn, MYSQL_READ_DEFAULT_FILE, read_default_file);
        if (read_default_group != NULL)
            mysql_options(conn, MYSQL_READ_DEFAULT_GROUP, read_default_group);
        if (local_infile != -1)
            mysql_options(conn, MYSQL_OPT_LOCAL_INFILE, (char *) &local_infile);

#ifdef _WIN32
        if (socket_name != NULL)
            mysql_options(conn, MYSQL_OPT_NAMED_PIPE, 0);
#endif

#if HAVE_OPENSSL
        if (ssl)
            mysql_ssl_set(conn, key, cert, ca, capath, cipher);
#endif

        if (nonblocking)
        {
#ifdef HAVE_ASYNCIO
            if (!mysql_real_connect_nonblocking_init(
                        conn, host, user, password, database, port, socket_name, client_flag))
            {
                conn = NULL;
            }
#endif
        }
        else
        {
            conn = mysql_real_connect(conn, host, user, password, database, port, socket_name, client_flag);
        }
    }

    self->autocommit = self->connection.server_capabilities & CLIENT_TRANSACTIONS ? 1 : 0;
    Py_END_ALLOW_THREADS ;

    if (conn == NULL)
    {
        wsql_raise_error(self);
        return -1;
    }

    self->open = 1;
    if (!nonblocking)
    {
        self->connected = 1;
    }
    return 0;
}
Ejemplo n.º 19
0
int mysql_drv_connect(db_conn_t *sb_conn)
{
  MYSQL          *con;
  char           *host;
  char           *ssl_key;
  char           *ssl_cert;
  char           *ssl_ca;
  
  con = (MYSQL *)malloc(sizeof(MYSQL));
  if (con == NULL)
    return 1;
  sb_conn->ptr = con;
  
  mysql_init(con);
  DEBUG("mysql_init(%p)", con);

  pthread_mutex_lock(&hosts_mutex);
  hosts_pos = SB_LIST_ITEM_NEXT(hosts_pos);
  if (hosts_pos == args.hosts)
    hosts_pos = SB_LIST_ITEM_NEXT(hosts_pos);
  host = SB_LIST_ENTRY(hosts_pos, value_t, listitem)->data;
  pthread_mutex_unlock(&hosts_mutex);
  
#if 0
  /*
    FIXME: the following leads to crash in the client lib.
    http://bugs.mysql.com/?id=40552
  */
  mysql_options(con, MYSQL_READ_DEFAULT_GROUP, "sysbench");
  DEBUG("mysql_options(%p, MYSQL_READ_DEFAULT_GROUP, \"sysbench\")", con);
#endif
  
  if (args.use_ssl)
  {
    ssl_key= "client-key.pem";
    ssl_cert= "client-cert.pem";
    ssl_ca= "cacert.pem";

    DEBUG("mysql_ssl_set(%p,\"%s\", \"%s\", \"%s\", NULL, NULL)", con, ssl_key,
          ssl_cert, ssl_ca);
    mysql_ssl_set(con, ssl_key, ssl_cert, ssl_ca, NULL, NULL);
  }
  
  DEBUG("mysql_real_connect(%p, \"%s\", \"%s\", \"%s\", \"%s\", %u, \"%s\", %s)",
        con,
        host,
        args.user,
        args.password,
        args.db,
        args.port,
        args.socket,
        (MYSQL_VERSION_ID >= 50000) ? "CLIENT_MULTI_STATEMENTS" : "0"
        );
  if (!mysql_real_connect(con,
                         host,
                         args.user,
                         args.password,
                         args.db,
                         args.port,
                         args.socket,
#if MYSQL_VERSION_ID >= 50000
                          CLIENT_MULTI_STATEMENTS)
#else
                          0)
#endif
      )
  {
    log_text(LOG_FATAL, "unable to connect to MySQL server, aborting...");
    log_text(LOG_FATAL, "error %d: %s", mysql_errno(con),
           mysql_error(con));
    free(con);
    return 1;
  }

  return 0;
}
Ejemplo n.º 20
0
int
main (int argc, char **argv)
{

	MYSQL mysql;
	MYSQL_RES *res;
	MYSQL_ROW row;

	/* should be status */

	char *result = NULL;
	char *error = NULL;
	char slaveresult[SLAVERESULTSIZE];
	char* perf;

        perf = strdup ("");

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	/* initialize mysql  */
	mysql_init (&mysql);
	
	if (opt_file != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_FILE,opt_file);

	if (opt_group != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
	else
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");

	if (ssl)
		mysql_ssl_set(&mysql,key,cert,ca_cert,ca_dir,ciphers);
	/* establish a connection to the server and error checking */
	if (!mysql_real_connect(&mysql,db_host,db_user,db_pass,db,db_port,db_socket,0)) {
		if (mysql_errno (&mysql) == CR_UNKNOWN_HOST)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_VERSION_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_OUT_OF_MEMORY)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_IPSOCK_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_SOCKET_CREATE_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
	}

	/* get the server stats */
	result = strdup (mysql_stat (&mysql));

	/* error checking once more */
	if (mysql_error (&mysql)) {
		if (mysql_errno (&mysql) == CR_SERVER_GONE_ERROR)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_SERVER_LOST)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_UNKNOWN_ERROR)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
	}

	/* try to fetch some perf data */
	if (mysql_query (&mysql, "show global status") == 0) {
		if ( (res = mysql_store_result (&mysql)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("status store_result error: %s\n"), error);
		}

		while ( (row = mysql_fetch_row (res)) != NULL) {
			int i;

			for(i = 0; i < LENGTH_METRIC_UNIT; i++) {
				if (strcmp(row[0], metric_unit[i]) == 0) {
					xasprintf(&perf, "%s%s ", perf, perfdata(metric_unit[i],
						atol(row[1]), "", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0));
					continue;
				}
			}
			for(i = 0; i < LENGTH_METRIC_COUNTER; i++) {
				if (strcmp(row[0], metric_counter[i]) == 0) {
					xasprintf(&perf, "%s%s ", perf, perfdata(metric_counter[i],
						atol(row[1]), "c", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0));
					continue;
				}
			}
		}
		/* remove trailing space */
                if (strlen(perf) > 0)
                    perf[strlen(perf) - 1] = '\0';
	}

	if(check_slave) {
		/* check the slave status */
		if (mysql_query (&mysql, "show slave status") != 0) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave query error: %s\n"), error);
		}

		/* store the result */
		if ( (res = mysql_store_result (&mysql)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave store_result error: %s\n"), error);
		}

		/* Check there is some data */
		if (mysql_num_rows(res) == 0) {
			mysql_close(&mysql);
			die (STATE_WARNING, "%s\n", _("No slaves defined"));
		}

		/* fetch the first row */
		if ( (row = mysql_fetch_row (res)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_free_result (res);
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave fetch row error: %s\n"), error);
		}

		if (mysql_field_count (&mysql) == 12) {
			/* mysql 3.23.x */
			snprintf (slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
			if (strcmp (row[6], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

		} else {
			/* mysql 4.x.x and mysql 5.x.x */
			int slave_io_field = -1 , slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
			MYSQL_FIELD* fields;

			num_fields = mysql_num_fields(res);
			fields = mysql_fetch_fields(res);
			for(i = 0; i < num_fields; i++) {
				if (strcmp(fields[i].name, "Slave_IO_Running") == 0) {
					slave_io_field = i;
					continue;
				}
				if (strcmp(fields[i].name, "Slave_SQL_Running") == 0) {
					slave_sql_field = i;
					continue;
				}
				if (strcmp(fields[i].name, "Seconds_Behind_Master") == 0) {
					seconds_behind_field = i;
					continue;
				}
			}

			/* Check if slave status is available */
			if ((slave_io_field < 0) || (slave_sql_field < 0) || (num_fields == 0)) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "Slave status unavailable\n");
			}

			/* Save slave status in slaveresult */
			snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field], row[slave_sql_field], seconds_behind_field!=-1?row[seconds_behind_field]:"Unknown");

			/* Raise critical error if SQL THREAD or IO THREAD are stopped */
			if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

			if (verbose >=3) {
				if (seconds_behind_field == -1) {
					printf("seconds_behind_field not found\n");
				} else {
					printf ("seconds_behind_field(index %d)=%s\n", seconds_behind_field, row[seconds_behind_field]);
				}
			}

			/* Check Seconds Behind against threshold */
			if ((seconds_behind_field != -1) && (strcmp (row[seconds_behind_field], "NULL") != 0)) {
				double value = atof(row[seconds_behind_field]);
				int status;

				status = get_status(value, my_threshold);

				xasprintf (&perf, "%s %s", perf, fperfdata ("seconds behind master", value, "s",
        	                        TRUE, (double) warning_time,
                	                TRUE, (double) critical_time,
                        	        FALSE, 0,
                                	FALSE, 0));

				if (status == STATE_WARNING) {
					printf("SLOW_SLAVE %s: %s|%s\n", _("WARNING"), slaveresult, perf);
					exit(STATE_WARNING);
				} else if (status == STATE_CRITICAL) {
					printf("SLOW_SLAVE %s: %s|%s\n", _("CRITICAL"), slaveresult, perf);
					exit(STATE_CRITICAL);
				}
			}
		}

		/* free the result */
		mysql_free_result (res);
	}

	/* close the connection */
	mysql_close (&mysql);

	/* print out the result of stats */
	if (check_slave) {
		printf ("%s %s|%s\n", result, slaveresult, perf);
	} else {
		printf ("%s|%s\n", result, perf);
	}

	return STATE_OK;
}
Ejemplo n.º 21
0
int
main (int argc, char *argv[])
{
int        opt_err;
MYSQL      *conn;   /* pointer to connection handler */
MYSQL_STMT *stmt;   /* pointer to statement handler */

  MY_INIT (argv[0]);
  load_defaults ("my", client_groups, &argc, &argv);

  if ((opt_err = handle_options (&argc, &argv, my_opts, get_one_option)))
    exit (opt_err);

  /* solicit password if necessary */
  if (ask_password)
    opt_password = get_tty_password (NULL);

  /* get database name if present on command line */
  if (argc > 0)
  {
    opt_db_name = argv[0];
    --argc; ++argv;
  }

  /* initialize client library */
  if (mysql_library_init (0, NULL, NULL))
  {
    print_error (NULL, "mysql_library_init() failed");
    exit (1);
  }

  /* initialize connection handler */
  conn = mysql_init (NULL);
  if (conn == NULL)
  {
    print_error (NULL, "mysql_init() failed (probably out of memory)");
    exit (1);
  }

#ifdef HAVE_OPENSSL
  /* pass SSL information to client library */
  if (opt_use_ssl)
    mysql_ssl_set (conn, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
                   opt_ssl_capath, opt_ssl_cipher);
  mysql_options (conn,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                 (char*)&opt_ssl_verify_server_cert);
#endif

  /* connect to server */
  if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
      opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL)
  {
    print_error (conn, "mysql_real_connect() failed");
    mysql_close (conn);
    exit (1);
  }

/* #@ _VERIFY_SERVER_VERSION_ */
  if (mysql_get_server_version (conn) < 50503)
  {
    print_error (NULL, "Prepared CALL requires MySQL 5.5.3 or higher");
    mysql_close (conn);
    exit (1);
  }
/* #@ _VERIFY_SERVER_VERSION_ */

  /* initialize statement handler, execute prepared CALL, close handler */
/* #@ _CALL_PROCEDURE_ */
  stmt = mysql_stmt_init (conn);
  if (!stmt)
    print_error (NULL, "Could not initialize statement handler");
  else
  {
    if (exec_prepared_call (stmt) == 0)
      process_call_result (conn, stmt);
    mysql_stmt_close (stmt);
  }
/* #@ _CALL_PROCEDURE_ */

  /* disconnect from server, terminate client library */
  mysql_close (conn);
  mysql_library_end ();
  exit (0);
}
Ejemplo n.º 22
0
/*************************************************************************
 *
 *	Function: sql_create_socket
 *
 *	Purpose: Establish connection to the db
 *
 *************************************************************************/
static sql_rcode_t sql_socket_init(rlm_sql_handle_t *handle, rlm_sql_config_t *config)
{
	rlm_sql_mysql_conn_t *conn;
	rlm_sql_mysql_config_t *driver = config->driver;
	unsigned long sql_flags;

	MEM(conn = handle->conn = talloc_zero(handle, rlm_sql_mysql_conn_t));
	talloc_set_destructor(conn, _sql_socket_destructor);

	DEBUG("rlm_sql_mysql: Starting connect to MySQL server");

	mysql_init(&(conn->db));

	/*
	 *	If any of the TLS options are set, configure TLS
	 *
	 *	According to MySQL docs this function always returns 0, so we won't
	 *	know if ssl setup succeeded until mysql_real_connect is called below.
	 */
	if (driver->tls_ca_file || driver->tls_ca_path ||
	    driver->tls_certificate_file || driver->tls_private_key_file) {
		mysql_ssl_set(&(conn->db), driver->tls_private_key_file, driver->tls_certificate_file,
			      driver->tls_ca_file, driver->tls_ca_path, driver->tls_cipher);
	}

	mysql_options(&(conn->db), MYSQL_READ_DEFAULT_GROUP, "freeradius");

#if (MYSQL_VERSION_ID >= 50000)
	if (config->query_timeout) {
		unsigned int timeout = config->query_timeout;

		/*
		 *	3 retries are hard-coded into the MySQL library.
		 *	We ensure that the REAL timeout is what the user
		 *	set by accounting for that.
		 */
		if (timeout > 3) timeout /= 3;

		mysql_options(&(conn->db), MYSQL_OPT_CONNECT_TIMEOUT,
			      &timeout);
		mysql_options(&(conn->db), MYSQL_OPT_READ_TIMEOUT,
			      &timeout);
		mysql_options(&(conn->db), MYSQL_OPT_WRITE_TIMEOUT,
			      &timeout);
	}
#endif

#if (MYSQL_VERSION_ID >= 40100)
	sql_flags = CLIENT_MULTI_RESULTS | CLIENT_FOUND_ROWS;
#else
	sql_flags = CLIENT_FOUND_ROWS;
#endif

#ifdef CLIENT_MULTI_STATEMENTS
	sql_flags |= CLIENT_MULTI_STATEMENTS;
#endif
	conn->sock = mysql_real_connect(&(conn->db),
					config->sql_server,
					config->sql_login,
					config->sql_password,
					config->sql_db,
					atoi(config->sql_port),
					NULL,
					sql_flags);
	if (!conn->sock) {
		ERROR("rlm_sql_mysql: Couldn't connect socket to MySQL "
		       "server %s@%s:%s", config->sql_login, config->sql_server,
		       config->sql_db);
		ERROR("rlm_sql_mysql: Mysql error '%s'",
		       mysql_error(&conn->db));

		conn->sock = NULL;

		return -1;
	}


	return 0;
}
Ejemplo n.º 23
0
int
main (int argc, char *argv[])
{
int opt_err;

  MY_INIT (argv[0]);
  load_defaults ("my", client_groups, &argc, &argv);

  if ((opt_err = handle_options (&argc, &argv, my_opts, get_one_option)))
    exit (opt_err);

  /* solicit password if necessary */
  if (ask_password)
    opt_password = get_tty_password (NULL);

  /* get database name if present on command line */
  if (argc > 0)
  {
    opt_db_name = argv[0];
    --argc; ++argv;
  }

  /* initialize client library */
  if (mysql_library_init (0, NULL, NULL))
  {
    print_error (NULL, "mysql_library_init() failed");
    exit (1);
  }

/* #@ _SET_UP_SSL_ */
  /* initialize connection handler */
  conn = mysql_init (NULL);
  if (conn == NULL)
  {
    print_error (NULL, "mysql_init() failed (probably out of memory)");
    exit (1);
  }

#ifdef HAVE_OPENSSL
  /* pass SSL information to client library */
  if (opt_use_ssl)
    mysql_ssl_set (conn, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
                   opt_ssl_capath, opt_ssl_cipher);
  mysql_options (conn,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                 (char*)&opt_ssl_verify_server_cert);
#endif

  /* connect to server */
  if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
      opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL)
  {
    print_error (conn, "mysql_real_connect() failed");
    mysql_close (conn);
    exit (1);
  }
/* #@ _SET_UP_SSL_ */

  printf ("Testing connection...\n");
  process_statement (conn, "SHOW STATUS LIKE 'Ssl_cipher'");
  printf ("If Ssl_cipher is non-blank, the connection is secure.\n");

  while (1)
  {
    char  buf[10000];

    fprintf (stderr, "query> ");                  /* print prompt */
    if (fgets (buf, sizeof (buf), stdin) == NULL) /* read statement */
      break;
    if (strcmp (buf, "quit\n") == 0 || strcmp (buf, "\\q\n") == 0)
      break;
    process_statement (conn, buf);                /* execute it */
  }

  /* disconnect from server, terminate client library */
  mysql_close (conn);
  mysql_library_end ();
  exit (0);
}
Ejemplo n.º 24
0
/* {{{ pdo_mysql_handle_factory */
static int pdo_mysql_handle_factory(pdo_dbh_t *dbh, zval *driver_options)
{
	pdo_mysql_db_handle *H;
	size_t i;
	int ret = 0;
	char *host = NULL, *unix_socket = NULL;
	unsigned int port = 3306;
	char *dbname;
	struct pdo_data_src_parser vars[] = {
		{ "charset",  NULL,	0 },
		{ "dbname",   "",	0 },
		{ "host",   "localhost",	0 },
		{ "port",   "3306",	0 },
		{ "unix_socket",  PDO_DEFAULT_MYSQL_UNIX_ADDR,	0 },
	};
	int connect_opts = 0
#ifdef CLIENT_MULTI_RESULTS
		|CLIENT_MULTI_RESULTS
#endif
		;
#if defined(PDO_USE_MYSQLND)
	size_t dbname_len = 0;
	size_t password_len = 0;
#endif

#ifdef CLIENT_MULTI_STATEMENTS
	if (!driver_options) {
		connect_opts |= CLIENT_MULTI_STATEMENTS;
	} else if (pdo_attr_lval(driver_options, PDO_MYSQL_ATTR_MULTI_STATEMENTS, 1)) {
		connect_opts |= CLIENT_MULTI_STATEMENTS;
	}
#endif

	PDO_DBG_ENTER("pdo_mysql_handle_factory");
	PDO_DBG_INF_FMT("dbh=%p", dbh);
#ifdef CLIENT_MULTI_RESULTS
	PDO_DBG_INF("multi results");
#endif

	php_pdo_parse_data_source(dbh->data_source, dbh->data_source_len, vars, 5);

	H = pecalloc(1, sizeof(pdo_mysql_db_handle), dbh->is_persistent);

	H->einfo.errcode = 0;
	H->einfo.errmsg = NULL;

	/* allocate an environment */

	/* handle for the server */
	if (!(H->server = pdo_mysql_init(dbh->is_persistent))) {
		pdo_mysql_error(dbh);
		goto cleanup;
	}
#if defined(PDO_USE_MYSQLND)
	if (dbh->is_persistent) {
		mysqlnd_restart_psession(H->server);
	}
#endif

	dbh->driver_data = H;

#ifndef PDO_USE_MYSQLND
	H->max_buffer_size = 1024*1024;
#endif

	H->assume_national_character_set_strings = 0;
	H->buffered = H->emulate_prepare = 1;

	/* handle MySQL options */
	if (driver_options) {
		zend_long connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30);
		zend_long local_infile = pdo_attr_lval(driver_options, PDO_MYSQL_ATTR_LOCAL_INFILE, 0);
		zend_string *init_cmd = NULL;
#ifndef PDO_USE_MYSQLND
		zend_string *default_file = NULL, *default_group = NULL;
#endif
		zend_long compress = 0;
		zend_string *ssl_key = NULL, *ssl_cert = NULL, *ssl_ca = NULL, *ssl_capath = NULL, *ssl_cipher = NULL;
		H->buffered = pdo_attr_lval(driver_options, PDO_MYSQL_ATTR_USE_BUFFERED_QUERY, 1);

		H->emulate_prepare = pdo_attr_lval(driver_options,
			PDO_MYSQL_ATTR_DIRECT_QUERY, H->emulate_prepare);
		H->emulate_prepare = pdo_attr_lval(driver_options,
			PDO_ATTR_EMULATE_PREPARES, H->emulate_prepare);

		H->assume_national_character_set_strings = pdo_attr_lval(driver_options,
			PDO_ATTR_DEFAULT_STR_PARAM, 0) == PDO_PARAM_STR_NATL;

#ifndef PDO_USE_MYSQLND
		H->max_buffer_size = pdo_attr_lval(driver_options, PDO_MYSQL_ATTR_MAX_BUFFER_SIZE, H->max_buffer_size);
#endif

		if (pdo_attr_lval(driver_options, PDO_MYSQL_ATTR_FOUND_ROWS, 0)) {
			connect_opts |= CLIENT_FOUND_ROWS;
		}

		if (pdo_attr_lval(driver_options, PDO_MYSQL_ATTR_IGNORE_SPACE, 0)) {
			connect_opts |= CLIENT_IGNORE_SPACE;
		}

		if (mysql_options(H->server, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&connect_timeout)) {
			pdo_mysql_error(dbh);
			goto cleanup;
		}

#ifndef PDO_USE_MYSQLND
		if (PG(open_basedir) && PG(open_basedir)[0] != '\0') {
			local_infile = 0;
		}
#endif
#if defined(MYSQL_OPT_LOCAL_INFILE) || defined(PDO_USE_MYSQLND)
		if (mysql_options(H->server, MYSQL_OPT_LOCAL_INFILE, (const char *)&local_infile)) {
			pdo_mysql_error(dbh);
			goto cleanup;
		}
#endif
#ifdef MYSQL_OPT_RECONNECT
		/* since 5.0.3, the default for this option is 0 if not specified.
		 * we want the old behaviour
		 * mysqlnd doesn't support reconnect, thus we don't have "|| defined(PDO_USE_MYSQLND)"
		*/
		{
			zend_long reconnect = 1;
			mysql_options(H->server, MYSQL_OPT_RECONNECT, (const char*)&reconnect);
		}
#endif
		init_cmd = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_INIT_COMMAND, NULL);
		if (init_cmd) {
			if (mysql_options(H->server, MYSQL_INIT_COMMAND, (const char *)ZSTR_VAL(init_cmd))) {
				zend_string_release_ex(init_cmd, 0);
				pdo_mysql_error(dbh);
				goto cleanup;
			}
			zend_string_release_ex(init_cmd, 0);
		}
#ifndef PDO_USE_MYSQLND
		default_file = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_READ_DEFAULT_FILE, NULL);
		if (default_file) {
			if (mysql_options(H->server, MYSQL_READ_DEFAULT_FILE, (const char *)ZSTR_VAL(default_file))) {
				zend_string_release_ex(default_file, 0);
				pdo_mysql_error(dbh);
				goto cleanup;
			}
			zend_string_release_ex(default_file, 0);
		}

		default_group = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_READ_DEFAULT_GROUP, NULL);
		if (default_group) {
			if (mysql_options(H->server, MYSQL_READ_DEFAULT_GROUP, (const char *)ZSTR_VAL(default_group))) {
				zend_string_release_ex(default_group, 0);
				pdo_mysql_error(dbh);
				goto cleanup;
			}
			zend_string_release_ex(default_group, 0);
		}
#endif
		compress = pdo_attr_lval(driver_options, PDO_MYSQL_ATTR_COMPRESS, 0);
		if (compress) {
			if (mysql_options(H->server, MYSQL_OPT_COMPRESS, 0)) {
				pdo_mysql_error(dbh);
				goto cleanup;
			}
		}

		ssl_key = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_SSL_KEY, NULL);
		ssl_cert = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_SSL_CERT, NULL);
		ssl_ca = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_SSL_CA, NULL);
		ssl_capath = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_SSL_CAPATH, NULL);
		ssl_cipher = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_SSL_CIPHER, NULL);

		if (ssl_key || ssl_cert || ssl_ca || ssl_capath || ssl_cipher) {
			mysql_ssl_set(H->server,
					ssl_key? ZSTR_VAL(ssl_key) : NULL,
					ssl_cert? ZSTR_VAL(ssl_cert) : NULL,
					ssl_ca? ZSTR_VAL(ssl_ca) : NULL,
					ssl_capath? ZSTR_VAL(ssl_capath) : NULL,
					ssl_cipher? ZSTR_VAL(ssl_cipher) : NULL);
			if (ssl_key) {
				zend_string_release_ex(ssl_key, 0);
			}
			if (ssl_cert) {
				zend_string_release_ex(ssl_cert, 0);
			}
			if (ssl_ca) {
				zend_string_release_ex(ssl_ca, 0);
			}
			if (ssl_capath) {
				zend_string_release_ex(ssl_capath, 0);
			}
			if (ssl_cipher) {
				zend_string_release_ex(ssl_cipher, 0);
			}
		}

#if MYSQL_VERSION_ID > 50605 || defined(PDO_USE_MYSQLND)
		{
			zend_string *public_key = pdo_attr_strval(driver_options, PDO_MYSQL_ATTR_SERVER_PUBLIC_KEY, NULL);
			if (public_key) {
				if (mysql_options(H->server, MYSQL_SERVER_PUBLIC_KEY, ZSTR_VAL(public_key))) {
					pdo_mysql_error(dbh);
					zend_string_release_ex(public_key, 0);
					goto cleanup;
				}
				zend_string_release_ex(public_key, 0);
			}
		}
#endif

#ifdef PDO_USE_MYSQLND
		{
			zend_long ssl_verify_cert = pdo_attr_lval(driver_options,
					PDO_MYSQL_ATTR_SSL_VERIFY_SERVER_CERT, -1);
			if (ssl_verify_cert != -1) {
				connect_opts |= ssl_verify_cert ?
					CLIENT_SSL_VERIFY_SERVER_CERT:
					CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
			}
		}
#endif
	}

#ifdef PDO_MYSQL_HAS_CHARSET
	if (vars[0].optval && mysql_options(H->server, MYSQL_SET_CHARSET_NAME, vars[0].optval)) {
		pdo_mysql_error(dbh);
		goto cleanup;
	}
#endif

	dbname = vars[1].optval;
	host = vars[2].optval;
	if(vars[3].optval) {
		port = atoi(vars[3].optval);
	}

#ifdef PHP_WIN32
	if (vars[2].optval && !strcmp(".", vars[2].optval)) {
#else
	if (vars[2].optval && !strcmp("localhost", vars[2].optval)) {
#endif
		unix_socket = vars[4].optval;
	}

	/* TODO: - Check zval cache + ZTS */
#ifdef PDO_USE_MYSQLND
	if (dbname) {
		dbname_len = strlen(dbname);
	}

	if (dbh->password) {
		password_len = strlen(dbh->password);
	}

	if (mysqlnd_connect(H->server, host, dbh->username, dbh->password, password_len, dbname, dbname_len,
						port, unix_socket, connect_opts, MYSQLND_CLIENT_NO_FLAG) == NULL) {
#else
	if (mysql_real_connect(H->server, host, dbh->username, dbh->password, dbname, port, unix_socket, connect_opts) == NULL) {
#endif
		pdo_mysql_error(dbh);
		goto cleanup;
	}

	if (!dbh->auto_commit) {
		mysql_handle_autocommit(dbh);
	}

	H->attached = 1;

	dbh->alloc_own_columns = 1;
	dbh->max_escaped_char_length = 2;
	dbh->methods = &mysql_methods;

	ret = 1;

cleanup:
	for (i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) {
		if (vars[i].freeme) {
			efree(vars[i].optval);
		}
	}

	dbh->methods = &mysql_methods;

	PDO_DBG_RETURN(ret);
}
/* }}} */

const pdo_driver_t pdo_mysql_driver = {
	PDO_DRIVER_HEADER(mysql),
	pdo_mysql_handle_factory
};
Ejemplo n.º 25
0
static int do_connect()
{
const	char *server;
const	char *userid;
const	char *password;
const	char *database;
const	char *server_socket=0;
unsigned int server_port=0;
unsigned int server_opt=0;
const	char *p;

const	char *sslkey;
const	char *sslcert;
const	char *sslcacert;
const	char *sslcapath;
const	char *sslcipher;
unsigned int  use_ssl=0;

/*
** Periodically detect dead connections.
*/
	if (mysql)
	{
		static time_t last_time=0;
		time_t t_check;

		time(&t_check);

		if (t_check < last_time)
			last_time=t_check;	/* System clock changed */

		if (t_check < last_time + 60)
			return (0);

		last_time=t_check;
			
		if (mysql_ping(mysql) == 0) return (0);

		DPRINTF("authmysqllib: mysql_ping failed, connection lost");
		mysql_close(mysql);
		mysql=0;
	}

	server=read_env("MYSQL_SERVER");
	userid=read_env("MYSQL_USERNAME");
	password=read_env("MYSQL_PASSWORD");
	database=read_env("MYSQL_DATABASE");

#if MYSQL_VERSION_ID >= 32200
	sslkey=read_env("MYSQL_SSL_KEY");
	sslcert=read_env("MYSQL_SSL_CERT");
	sslcacert=read_env("MYSQL_SSL_CACERT");
	sslcapath=read_env("MYSQL_SSL_CAPATH");
	sslcipher=read_env("MYSQL_SSL_CIPHER");

	if ((sslcert != NULL) && ((sslcacert != NULL) || (sslcapath != NULL)))
	{
		use_ssl=1;
	}
#endif

	server_socket=(char *) read_env("MYSQL_SOCKET");

	if ((p=read_env("MYSQL_PORT")) != 0)
	{
		server_port=(unsigned int) atoi(p);
	}

	if ((p=read_env("MYSQL_OPT")) != 0)
	{
		server_opt=(unsigned int) atol(p);
	}

	if (!server && !server_socket)
	{
		err("authmysql: MYSQL_SERVER nor MYSQL_SOCKET set in"
			AUTHMYSQLRC ".");
		return (-1);
	}

	if (!userid)
	{
		err("authmysql: MYSQL_USERNAME not set in "
			AUTHMYSQLRC ".");
		return (-1);
	}

	if (!database)
	{
		err("authmysql: MYSQL_DATABASE not set in "
			AUTHMYSQLRC ".");
		return (-1);
	}

#if MYSQL_VERSION_ID >= 32200
	mysql_init(&mysql_buf);
	if (use_ssl)
	{
		mysql_ssl_set(&mysql_buf, sslkey, sslcert, sslcacert,
			      sslcapath, sslcipher);
	}
	mysql=mysql_real_connect(&mysql_buf, server, userid, password,
				 NULL,
				 server_port,
				 server_socket,
				 server_opt);
#else
	mysql=mysql_connect(&mysql_buf, server, userid, password);
#endif
	if (!mysql)
	{
		err("failed to connect to mysql server (server=%s, userid=%s): %s",
			server ? server : "<null>",
			userid ? userid : "<null>",
			mysql_error(&mysql_buf));
		return (-1);
	}

	if (mysql_select_db(mysql, database))
	{
		err("authmysql: mysql_select_db(%s) error: %s",
			database, mysql_error(mysql));
		mysql_close(mysql);
		mysql=0;
		return (-1);
	}
	
	DPRINTF("authmysqllib: connected. Versions: "
		"header %lu, "
		"client %lu, "
		"server %lu",
		(long)MYSQL_VERSION_ID,
		mysql_get_client_version(),
		mysql_get_server_version(mysql));

	set_session_options();	
	return (0);
}