Exemplo n.º 1
0
DatabaseWorkerPool<T>::DatabaseWorkerPool()
	: _queue(new ProducerConsumerQueue<SQLOperation*>()),
	_async_threads(0), _synch_threads(0)
{
	WPFatal(mysql_thread_safe(), "Used MySQL library isn't thread-safe.");
	WPFatal(mysql_get_client_version() >= MIN_MYSQL_CLIENT_VERSION, "TrinityCore does not support MySQL versions below 5.1");
	WPFatal(mysql_get_client_version() == MYSQL_VERSION_ID, "Used MySQL library version (%s) does not match the version used to compile TrinityCore (%s).",
		mysql_get_client_info(), MYSQL_SERVER_VERSION);
}
Exemplo n.º 2
0
static int mysql_mod_init(void)
{
#if MYSQL_VERSION_ID >= 40101
	my_client_ver = mysql_get_client_version();
	if ((my_client_ver >= 50025) || 
		((my_client_ver >= 40122) && 
		 (my_client_ver < 50000))) {
		if (my_send_to == 0) {
			my_send_to= DEFAULT_MY_SEND_TO;
		}
		if (my_recv_to == 0) {
			my_recv_to= DEFAULT_MY_RECV_TO;
		}
	} else if (my_recv_to || my_send_to) {
		LOG(L_WARN, "WARNING: mysql send or received timeout set, but "
			" not supported by the installed mysql client library"
			" (needed at least 4.1.22 or 5.0.25, but installed %ld)\n",
			my_client_ver);
	}
#else
	if (my_recv_to || my_send_to) {
		LOG(L_WARN, "WARNING: mysql send or received timeout set, but "
			" not supported by the mysql client library used to compile"
			" the mysql module (needed at least 4.1.1 but "
			" compiled against %ld)\n", MYSQL_VERSION_ID);
	}
#endif
	return 0;
}
Exemplo n.º 3
0
static VALUE rb_mysql_client_info(VALUE self) {
  VALUE version, client_info;
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *default_internal_enc;
  rb_encoding *conn_enc;
#endif
  GET_CLIENT(self);
  version = rb_hash_new();

#ifdef HAVE_RUBY_ENCODING_H
  default_internal_enc = rb_default_internal_encoding();
  conn_enc = rb_to_encoding(wrapper->encoding);
#endif

  rb_hash_aset(version, sym_id, LONG2NUM(mysql_get_client_version()));
  client_info = rb_str_new2(mysql_get_client_info());
#ifdef HAVE_RUBY_ENCODING_H
  rb_enc_associate(client_info, conn_enc);
  if (default_internal_enc) {
    client_info = rb_str_export_to_enc(client_info, default_internal_enc);
  }
#endif
  rb_hash_aset(version, sym_version, client_info);
  return version;
}
Exemplo n.º 4
0
DatabaseMySQL::DatabaseMySQL() :
	m_timeoutTask(0)
{
	m_connected = false;
	if(!mysql_init(&m_handle))
	{
		std::clog << std::endl << "Failed to initialize MySQL connection handler." << std::endl;
		return;
	}

	uint32_t timeout = g_config.getNumber(ConfigManager::MYSQL_READ_TIMEOUT);
	if(timeout)
		mysql_options(&m_handle, MYSQL_OPT_READ_TIMEOUT, (const char*)&timeout);

	timeout = g_config.getNumber(ConfigManager::MYSQL_WRITE_TIMEOUT);
	if(timeout)
		mysql_options(&m_handle, MYSQL_OPT_WRITE_TIMEOUT, (const char*)&timeout);

	my_bool reconnect = true;
	mysql_options(&m_handle, MYSQL_OPT_RECONNECT, &reconnect);
	if(!mysql_real_connect(&m_handle, g_config.getString(ConfigManager::SQL_HOST).c_str(), g_config.getString(
		ConfigManager::SQL_USER).c_str(), g_config.getString(ConfigManager::SQL_PASS).c_str(), g_config.getString(
		ConfigManager::SQL_DB).c_str(), g_config.getNumber(ConfigManager::SQL_PORT), NULL, 0))
	{
		std::clog << "Failed connecting to database - MYSQL ERROR: " << mysql_error(&m_handle) << " (" << mysql_errno(&m_handle) << ")" << std::endl;
		return;
	}

	m_connected = true;
	if(mysql_get_client_version() <= 50019)
		//MySQL servers <= 5.0.19 have a bug where MYSQL_OPT_RECONNECT option is reset by mysql_real_connect calls.
		//Read this http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html for more information.
		std::clog << std::endl << "> WARNING: Outdated MySQL server detected, consider upgrading to a newer version." << std::endl;

	timeout = g_config.getNumber(ConfigManager::SQL_KEEPALIVE) * 1000;
	if(timeout)
		m_timeoutTask = Scheduler::getInstance().addEvent(createSchedulerTask(timeout,
			boost::bind(&DatabaseMySQL::keepAlive, this)));

	if(!g_config.getBool(ConfigManager::HOUSE_STORAGE))
		return;

	//we cannot lock mutex here :)
	DBResult* result = storeQuery("SHOW variables LIKE 'max_allowed_packet';");
	if(!result)
		return;

	if(result->getDataLong("Value") < 16776192)
		std::clog << std::endl << "> WARNING: max_allowed_packet might be set too low for binary map storage." << std::endl
			<< "Use the following query to raise max_allow_packet: SET GLOBAL max_allowed_packet = 16776192;" << std::endl;

	result->free();
}
Exemplo n.º 5
0
void CDataBase::Connect()
{
	ADDTOCALLSTACK("CDataBase::Connect");
	SimpleThreadLock lock(m_connectionMutex);
	if ( m_connected )
		return;

	if ( mysql_get_client_version() < LIBMYSQL_VERSION_ID )
	{
#ifdef _WIN32
		g_Log.EventWarn("Your MySQL client library %s is outdated. For better compatibility, update your 'libmysql.dll' file to version %s\n", mysql_get_client_info(), LIBMYSQL_VERSION);
#else
		g_Log.EventWarn("Your MySQL client library %s is outdated. For better compatibility, update your 'libmysqlclient' package to version %s\n", mysql_get_client_info(), LIBMYSQL_VERSION);
#endif
	}

	m_socket = mysql_init(NULL);
	if ( !m_socket )
	{
		g_Log.EventError("Insufficient memory to initialize MySQL client socket\n");
		return;
	}

	const char *user = g_Cfg.m_sMySqlUser;
	const char *password = g_Cfg.m_sMySqlPass;
	const char *db = g_Cfg.m_sMySqlDB;
	const char *host = g_Cfg.m_sMySqlHost;
	unsigned int port = MYSQL_PORT;

	// If user define server port using hostname:port format, split values into different variables
	const char *pszArgs = strchr(host, ':');
	if ( pszArgs != NULL )
	{
		char *pszTemp = Str_GetTemp();
		strcpy(pszTemp, host);
		*(strchr(pszTemp, ':')) = 0;
		port = ATOI(pszArgs + 1);
		host = pszTemp;
	}

	if ( mysql_real_connect(m_socket, host, user, password, db, port, NULL, CLIENT_MULTI_STATEMENTS) )
	{
		m_connected = true;
		if ( mysql_get_server_version(m_socket) < MYSQL_VERSION_ID )
			g_Log.EventWarn("Your MySQL server %s is outdated. For better compatibility, update your MySQL server to version %s\n", mysql_get_server_info(m_socket), MYSQL_SERVER_VERSION);
	}
	else
	{
		g_Log.EventError("MySQL error #%u: %s\n", mysql_errno(m_socket), mysql_error(m_socket));
		mysql_close(m_socket);
		m_socket = NULL;
	}
}
Exemplo n.º 6
0
SEXP rmysql_version() {
  SEXP output = PROTECT(allocVector(INTSXP, 2));
  SEXP output_nms = PROTECT(allocVector(STRSXP, 2));
  SET_NAMES(output, output_nms);
  UNPROTECT(1);

  SET_STRING_ELT(output_nms, 0, mkChar(MYSQL_SERVER_VERSION));
  INTEGER(output)[0] = MYSQL_VERSION_ID;

  SET_STRING_ELT(output_nms, 1, mkChar(mysql_get_client_info()));
  INTEGER(output)[1] = mysql_get_client_version();

  UNPROTECT(1);
  return output;
}
Exemplo n.º 7
0
static VALUE rb_mysql_client_info(RB_MYSQL_UNUSED VALUE self) {
  VALUE version = rb_hash_new(), client_info;
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *default_internal_enc = rb_default_internal_encoding();
  rb_encoding *conn_enc = rb_to_encoding(rb_iv_get(self, "@encoding"));
#endif

  rb_hash_aset(version, sym_id, LONG2NUM(mysql_get_client_version()));
  client_info = rb_str_new2(mysql_get_client_info());
#ifdef HAVE_RUBY_ENCODING_H
  rb_enc_associate(client_info, conn_enc);
  if (default_internal_enc) {
    client_info = rb_str_export_to_enc(client_info, default_internal_enc);
  }
#endif
  rb_hash_aset(version, sym_version, client_info);
  return version;
}
Exemplo n.º 8
0
/* call-seq:
 *    client.info
 *
 * Returns a string that represents the client library version.
 */
static VALUE rb_mysql_client_info(RB_MYSQL_UNUSED VALUE klass) {
  VALUE version_info, version, header_version;
  version_info = rb_hash_new();

  version = rb_str_new2(mysql_get_client_info());
  header_version = rb_str_new2(MYSQL_LINK_VERSION);

#ifdef HAVE_RUBY_ENCODING_H
  rb_enc_associate(version, rb_usascii_encoding());
  rb_enc_associate(header_version, rb_usascii_encoding());
#endif

  rb_hash_aset(version_info, sym_id, LONG2NUM(mysql_get_client_version()));
  rb_hash_aset(version_info, sym_version, version);
  rb_hash_aset(version_info, sym_header_version, header_version);

  return version_info;
}
Exemplo n.º 9
0
static VALUE rb_set_ssl_mode_option(VALUE self, VALUE setting) {
  unsigned long version = mysql_get_client_version();

  if (version < 50703) {
    rb_warn( "Your mysql client library does not support setting ssl_mode; full support comes with 5.7.11." );
    return Qnil;
  }
#ifdef HAVE_CONST_MYSQL_OPT_SSL_ENFORCE
  GET_CLIENT(self);
  int val = NUM2INT( setting );
  if (version >= 50703 && version < 50711) {
    if (val == SSL_MODE_DISABLED || val == SSL_MODE_REQUIRED) {
      bool b = ( val == SSL_MODE_REQUIRED );
      int result = mysql_options( wrapper->client, MYSQL_OPT_SSL_ENFORCE, &b );
      return INT2NUM(result);
    } else {
      rb_warn( "MySQL client libraries between 5.7.3 and 5.7.10 only support SSL_MODE_DISABLED and SSL_MODE_REQUIRED" );
      return Qnil;
    }
  }
#endif
#ifdef FULL_SSL_MODE_SUPPORT
  GET_CLIENT(self);
  int val = NUM2INT( setting );

  if (val != SSL_MODE_DISABLED && val != SSL_MODE_PREFERRED && val != SSL_MODE_REQUIRED && val != SSL_MODE_VERIFY_CA && val != SSL_MODE_VERIFY_IDENTITY) {
    rb_raise(cMysql2Error, "ssl_mode= takes DISABLED, PREFERRED, REQUIRED, VERIFY_CA, VERIFY_IDENTITY, you passed: %d", val );
  }
  int result = mysql_options( wrapper->client, MYSQL_OPT_SSL_MODE, &val );

  return INT2NUM(result);
#endif
#ifdef NO_SSL_MODE_SUPPORT
  return Qnil;
#endif
}
Exemplo n.º 10
0
/* 主要功能:得到客户版本信息 */
const unsigned long  CppMySQL3DB::getClientVersion()
{
	return mysql_get_client_version();
}
Exemplo n.º 11
0
bool MySQLConnection::Open()
{
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog->outError("Could not initialize Mysql connection to database `%s`", m_connectionInfo.database.c_str());
        return false;
    }

    int port;
    char const* unix_socket;

    mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8");
    #ifdef _WIN32
    if (m_connectionInfo.host == ".")                                           // named pipe use option (Windows)
    {
        unsigned int opt = MYSQL_PROTOCOL_PIPE;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        port = 0;
        unix_socket = 0;
    }
    else                                                    // generic case
    {
        port = atoi(m_connectionInfo.port_or_socket.c_str());
        unix_socket = 0;
    }
    #else
    if (m_connectionInfo.host == ".")                                           // socket use option (Unix/Linux)
    {
        unsigned int opt = MYSQL_PROTOCOL_SOCKET;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        m_connectionInfo.host = "localhost";
        port = 0;
        unix_socket = m_connectionInfo.port_or_socket.c_str();
    }
    else                                                    // generic case
    {
        port = atoi(m_connectionInfo.port_or_socket.c_str());
        unix_socket = 0;
    }
    #endif

    m_Mysql = mysql_real_connect(mysqlInit, m_connectionInfo.host.c_str(), m_connectionInfo.user.c_str(),
        m_connectionInfo.password.c_str(), m_connectionInfo.database.c_str(), port, unix_socket, 0);

    if (m_Mysql)
    {
        if (!m_reconnecting)
        {
            sLog->outSQLDriver("MySQL client library: %s", mysql_get_client_info());
            sLog->outSQLDriver("MySQL server ver: %s ", mysql_get_server_info(m_Mysql));
            if (mysql_get_server_version(m_Mysql) != mysql_get_client_version())
                sLog->outSQLDriver("[WARNING] MySQL client/server version mismatch; may conflict with behaviour of prepared statements.");
        }

        sLog->outDetail("Connected to MySQL database at %s", m_connectionInfo.host.c_str());
        mysql_autocommit(m_Mysql, 1);

        // set connection properties to UTF8 to properly handle locales for different
        // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
        mysql_set_character_set(m_Mysql, "utf8");
        return true;
    }
    else
    {
        sLog->outError("Could not connect to MySQL database at %s: %s\n", m_connectionInfo.host.c_str(), mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Exemplo n.º 12
0
int main(int argc, const char *argv[])
{
	MYSQL *dbc=NULL;
	long i=0,err=0;

	srand48((unsigned long)1);
	time_t timestart=0,timenow=0;

	unsigned int counter=0;
	counter=0;
	char shortquery[1024]={0};
	char *longquery=NULL;
	longquery=NULL;
	char *c=NULL;
	/* my_init(); */
	if (!(dbc = mysql_init(NULL)))
	{
		printf("mysql_init\n");
		dbc=NULL;
		goto threadexit;
	}
	else
	{
		if (!mysql_real_connect(dbc,host,username,password,database,port, NULL, CLIENT_FOUND_ROWS|CLIENT_MULTI_STATEMENTS|CLIENT_MULTI_RESULTS))
		{
			printf("mysql_real_connect failed: %s (%d)", mysql_error(dbc),mysql_errno(dbc));
			dbc=NULL;
			goto threadexit;
		}
	}

	printf("running initializations..\n");
	client_version=mysql_get_client_version();
	server_version=mysql_get_server_version(dbc);
	printf("client version=%lu\n",client_version);
	printf("server version=%lu\n",server_version);
	if((client_version/10000) < (server_version/10000))
	{
		printf("incompatible client and server version!  please upgrade client library!\n");
		goto threadexit;
	}

	if (!mysql_thread_safe())
	{
		printf("non-threadsafe client detected!  please rebuild and link with libmysql_r!\n");
	}

	c=shortquery;
	c+=sprintf(c,"%s","drop table if exists t1");
	db_query(dbc,shortquery,1);

	c=shortquery;
	c+=sprintf(c,"%s","create table t1(id int)");
	db_query(dbc,shortquery,1);

	mysql_close(dbc);

	printf("about to spawn %d threads\n",NUMTHREADS);
	for (i=0;i<NUMTHREADS;i++)
	{
		err=pthread_create(&pthreads[i], NULL, worker_thread, (void *)i);
		if(err!=0)
		{
			printf("error spawning thread %lu, pthread_create returned %lu\n",(unsigned long)i,(unsigned long)err);
		}
		printf(".");
	}
	printf("\n");
	printf("completed spawning new database worker threads\n");

	printf("testcase is now running, so watch for server crash\n");

	timestart=time(NULL);
	timenow=time(NULL);
	for(i=0;(timenow-timestart) < TESTTIME;timenow=time(NULL))
	{
		usleep(1000*1000);
		printf("queries: %09lu\n",num_queries);
	}
	threaddone=1;

	printf("waiting for worker threads to finish...\n");

	for (i=0;i<NUMTHREADS;i++)
	{
		pthread_join(pthreads[i], NULL);
	}

	exit(0);
threadexit:
	exit(-1);
}
Exemplo n.º 13
0
MYSQL* MySQL_Connect(
    const char cszDBAddr[], const char cszDBName[], int nPort, 
    const char cszUserName[], const char cszPassword[]
)
{
    MYSQL*        pResult                   = NULL;
    int           nRetCode                  = false;
    MYSQL*        pDBHandle                 = NULL;
    MYSQL*        pTmpHandle                = NULL;
    my_bool       bReconnectFlag            = 0;
    unsigned long ulMySQLClientVersionID    = 0;
    int           nStrLen                   = 0;
    char          szSQL[1024];

    pDBHandle = mysql_init(NULL);
    KGLOG_PROCESS_ERROR(pDBHandle);
    
    // enable reconnect if MySQL client version > 5
    ulMySQLClientVersionID = mysql_get_client_version();
    if (ulMySQLClientVersionID >= MYSQL5_VERSION_ID)
    {
        bReconnectFlag = 1;
        nRetCode = mysql_options(pDBHandle, MYSQL_OPT_RECONNECT, &bReconnectFlag);
        KGLOG_PROCESS_ERROR(nRetCode == 0);
    }

    pTmpHandle = mysql_real_connect(
        pDBHandle, cszDBAddr, cszUserName, cszPassword, "", nPort, NULL, 0
    );
    if (pTmpHandle == NULL)
    {
        KGLogPrintf(
            KGLOG_ERR, 
            "[DB] Can't open database \"%s\" at \"%s\", db error : \"%s\"\n", 
            cszDBName, cszDBAddr, mysql_error(pDBHandle)
        );
        goto Exit0;
    }
    
    nStrLen = snprintf(
        szSQL, sizeof(szSQL), "create database if not exists %s", cszDBName
    );
    KGLOG_PROCESS_ERROR(nStrLen > 0 && nStrLen < (int)sizeof(szSQL));

    nRetCode = MySQL_Query(pDBHandle, szSQL);
    KGLOG_PROCESS_ERROR(nRetCode);

    nRetCode = mysql_select_db(pDBHandle, cszDBName);
    KGLOG_PROCESS_ERROR(nRetCode == 0);

    nRetCode = MySQL_CheckCaseInsensitive(pDBHandle);
    KGLOG_PROCESS_ERROR(nRetCode);

    nRetCode = MySQL_CheckCharacterSet(pDBHandle);
    KGLOG_PROCESS_ERROR(nRetCode);

    pResult = pDBHandle;
Exit0:
    if (!pResult)
    {
        if (pDBHandle)
        {
            KGLogPrintf(KGLOG_ERR, "%d:%s\n", mysql_errno(pDBHandle), mysql_error(pDBHandle));

            mysql_close(pDBHandle);
            pDBHandle = NULL;
        }
    }
    return pResult;
}
Exemplo n.º 14
0
MYSQL *KG_ConnectMySQLDatabase(const KG_MYSQL_PARAM &crParam)
{
    int nResult  = false;
    int nRetCode = false;
    MYSQL *pMySQL   = NULL;
    MYSQL *pRetConnect = NULL;
    unsigned long ulVersion = 0;
    MYSQL_RES* pMySQLResult = NULL;
    MYSQL_ROW Row = NULL;
    const char *pcszHost = "localhost";
    const char SQL_QUERY_CHARACTER[] = "show variables like 'character_set_database'";

    ASSERT(crParam.szServer[0]);
    ASSERT(crParam.szDatabase[0]);
    ASSERT(crParam.szUserName[0]);
    ASSERT(crParam.szPassword[0]);

    ulVersion = mysql_get_client_version();
    KGLOG_PROCESS_ERROR(ulVersion == MYSQL_VERSION_ID &&"MySQL library is not the appropriate version.");

    pMySQL = mysql_init(NULL);
    KGLOG_PROCESS_ERROR(pMySQL);

    if (strcmp(crParam.szServer, "127.0.0.1") != 0)
        pcszHost = crParam.szServer;

    pRetConnect = mysql_real_connect(
        pMySQL, pcszHost, crParam.szUserName, crParam.szPassword, NULL, 3306, NULL, 
        CLIENT_FOUND_ROWS // Return the number of found (matched) rows, not affected.
    );
    KGD_MYSQL_PROCESS_ERROR(pRetConnect, pMySQL, "mysql_real_connect()");
    KGLOG_PROCESS_ERROR(pRetConnect == pMySQL);
    pRetConnect = NULL; // Used for judge success or failed, now is useless.

    // Set current database.
    nRetCode = mysql_select_db(pMySQL, crParam.szDatabase);
    KGD_MYSQL_PROCESS_ERROR(nRetCode == 0, pMySQL, "mysql_select_db()");

    // Set connection character.
    nRetCode = mysql_real_query(pMySQL, SQL_QUERY_CHARACTER, (unsigned long)strlen(SQL_QUERY_CHARACTER));
    KGD_MYSQL_PROCESS_ERROR(nRetCode == 0, pMySQL, SQL_QUERY_CHARACTER);

    pMySQLResult = mysql_store_result(pMySQL);
    KGD_MYSQL_PROCESS_ERROR(pMySQLResult, pMySQL, "mysql_store_result()");

    Row = mysql_fetch_row(pMySQLResult);
    KGD_MYSQL_PROCESS_ERROR(Row != NULL, pMySQL, "mysql_fetch_row()");

    nRetCode = mysql_set_character_set(pMySQL, Row[1]);
    KGD_MYSQL_PROCESS_ERROR(nRetCode == 0, pMySQL, "mysql_set_character_set()");

    nResult = true;
Exit0:
    if (!nResult) 
    {
        if (pMySQL)
        {
            mysql_close(pMySQL);
            pMySQL = NULL;    
        }
    }
    return pMySQL;
}
Exemplo n.º 15
0
unsigned long	GSqlDatabase::GetClientVersion(void)
{
	return (mysql_get_client_version());
}
Exemplo n.º 16
0
unsigned long CDatabase_Connection::get_client_version()
{
	return mysql_get_client_version();
}
Exemplo n.º 17
0
/* Class method: MySQL client library finalization */
void MysqlConnection_onstop(void) {
        if (mysql_get_client_version() >= 50003)
                mysql_library_end();
        else
                mysql_server_end();
}
Exemplo n.º 18
0
/*	client_version()	*/
static VALUE client_version(VALUE obj)
{
    return INT2NUM(mysql_get_client_version());
}
Exemplo n.º 19
0
void mysqli_common_connect(INTERNAL_FUNCTION_PARAMETERS, zend_bool is_real_connect, zend_bool in_ctor) /* {{{ */
{
	MY_MYSQL			*mysql = NULL;
	MYSQLI_RESOURCE		*mysqli_resource = NULL;
	zval				*object = getThis();
	char				*hostname = NULL, *username=NULL, *passwd=NULL, *dbname=NULL, *socket=NULL;
	size_t					hostname_len = 0, username_len = 0, passwd_len = 0, dbname_len = 0, socket_len = 0;
	zend_bool			persistent = FALSE;
	zend_long				port = 0, flags = 0;
	zend_string			*hash_key = NULL;
	zend_bool			new_connection = FALSE;
	zend_resource		*le;
	mysqli_plist_entry *plist = NULL;
	zend_bool			self_alloced = 0;


#if !defined(MYSQL_USE_MYSQLND)
	if ((MYSQL_VERSION_ID / 100) != (mysql_get_client_version() / 100)) {
		php_error_docref(NULL, E_WARNING,
						"Headers and client library minor version mismatch. Headers:%d Library:%ld",
						MYSQL_VERSION_ID, mysql_get_client_version());
	}
#endif

	if (getThis() && !ZEND_NUM_ARGS() && in_ctor) {
		php_mysqli_init(INTERNAL_FUNCTION_PARAM_PASSTHRU, in_ctor);
		return;
	}
	hostname = username = dbname = passwd = socket = NULL;

	if (!is_real_connect) {
		if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ssssls", &hostname, &hostname_len, &username, &username_len,
									&passwd, &passwd_len, &dbname, &dbname_len, &port, &socket, &socket_len) == FAILURE) {
			return;
		}

		if (object && instanceof_function(Z_OBJCE_P(object), mysqli_link_class_entry)) {
			mysqli_resource = (Z_MYSQLI_P(object))->ptr;
			if (mysqli_resource && mysqli_resource->ptr) {
				mysql = (MY_MYSQL*) mysqli_resource->ptr;
			}
		}
		if (!mysql) {
			mysql = (MY_MYSQL *) ecalloc(1, sizeof(MY_MYSQL));
			self_alloced = 1;
		}
		flags |= CLIENT_MULTI_RESULTS; /* needed for mysql_multi_query() */
	} else {
		/* We have flags too */
		if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O|sssslsl", &object, mysqli_link_class_entry,
										&hostname, &hostname_len, &username, &username_len, &passwd, &passwd_len, &dbname, &dbname_len, &port, &socket, &socket_len,
										&flags) == FAILURE) {
			return;
		}

		mysqli_resource = (Z_MYSQLI_P(object))->ptr;
		MYSQLI_FETCH_RESOURCE_CONN(mysql, object, MYSQLI_STATUS_INITIALIZED);

		/* set some required options */
		flags |= CLIENT_MULTI_RESULTS; /* needed for mysql_multi_query() */
		/* remove some insecure options */
		flags &= ~CLIENT_MULTI_STATEMENTS;   /* don't allow multi_queries via connect parameter */
#if !defined(MYSQLI_USE_MYSQLND)
		if (PG(open_basedir) && PG(open_basedir)[0] != '\0') {
			flags &= ~CLIENT_LOCAL_FILES;
		}
#endif
	}

	if (!socket_len || !socket) {
		socket = MyG(default_socket);
	}
	if (!port){
		port = MyG(default_port);
	}
	if (!passwd) {
		passwd = MyG(default_pw);
		passwd_len = strlen(SAFE_STR(passwd));
	}
	if (!username){
		username = MyG(default_user);
	}
	if (!hostname || !hostname_len) {
		hostname = MyG(default_host);
	}

	if (mysql->mysql && mysqli_resource &&
		(mysqli_resource->status > MYSQLI_STATUS_INITIALIZED))
	{
		/* already connected, we should close the connection */
		php_mysqli_close(mysql, MYSQLI_CLOSE_IMPLICIT, mysqli_resource->status);
	}

	if (strlen(SAFE_STR(hostname)) > 2 && !strncasecmp(hostname, "p:", 2)) {
		hostname += 2;
		if (!MyG(allow_persistent)) {
			php_error_docref(NULL, E_WARNING, "Persistent connections are disabled. Downgrading to normal");
		} else {
			mysql->persistent = persistent = TRUE;

			hash_key = strpprintf(0, "mysqli_%s_%s" ZEND_LONG_FMT "%s%s%s", SAFE_STR(hostname), SAFE_STR(socket),
								port, SAFE_STR(username), SAFE_STR(dbname),
								SAFE_STR(passwd));

			mysql->hash_key = hash_key;

			/* check if we can reuse existing connection ... */
			if ((le = zend_hash_find_ptr(&EG(persistent_list), hash_key)) != NULL) {
				if (le->type == php_le_pmysqli()) {
					plist = (mysqli_plist_entry *) le->ptr;

					do {
						if (zend_ptr_stack_num_elements(&plist->free_links)) {
							mysql->mysql = zend_ptr_stack_pop(&plist->free_links);

							MyG(num_inactive_persistent)--;
							/* reset variables */

#ifndef MYSQLI_NO_CHANGE_USER_ON_PCONNECT
							if (!mysqli_change_user_silent(mysql->mysql, username, passwd, dbname, passwd_len)) {
#else
							if (!mysql_ping(mysql->mysql)) {
#endif
#ifdef MYSQLI_USE_MYSQLND
								mysqlnd_restart_psession(mysql->mysql);
#endif
								MyG(num_active_persistent)++;

								/* clear error */
								php_mysqli_set_error(mysql_errno(mysql->mysql), (char *) mysql_error(mysql->mysql));

								goto end;
							} else {
								mysqli_close(mysql->mysql, MYSQLI_CLOSE_IMPLICIT);
								mysql->mysql = NULL;
							}
						}
					} while (0);
				}
			} else {
				plist = calloc(1, sizeof(mysqli_plist_entry));

				zend_ptr_stack_init_ex(&plist->free_links, 1);
				zend_register_persistent_resource(ZSTR_VAL(hash_key), ZSTR_LEN(hash_key), plist, php_le_pmysqli());
			}
		}
Exemplo n.º 20
0
bool MySQLConnection::Open(const std::string& infoString)
{
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog.outError("Could not initialize Mysql connection");
        return false;
    }

    Tokens tokens = StrSplit(infoString, ";");

    Tokens::iterator iter;

    std::string host, port_or_socket, user, password, database;
    int port;
    char const* unix_socket;

    iter = tokens.begin();

    if (iter != tokens.end())
        host = *iter++;
    if (iter != tokens.end())
        port_or_socket = *iter++;
    if (iter != tokens.end())
        user = *iter++;
    if (iter != tokens.end())
        password = *iter++;
    if (iter != tokens.end())
        database = *iter++;

    mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8");
    #ifdef _WIN32
    if (host==".")                                           // named pipe use option (Windows)
    {
        unsigned int opt = MYSQL_PROTOCOL_PIPE;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        port = 0;
        unix_socket = 0;
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
    #else
    if (host==".")                                           // socket use option (Unix/Linux)
    {
        unsigned int opt = MYSQL_PROTOCOL_SOCKET;
        mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
        host = "localhost";
        port = 0;
        unix_socket = port_or_socket.c_str();
    }
    else                                                    // generic case
    {
        port = atoi(port_or_socket.c_str());
        unix_socket = 0;
    }
    #endif

    m_Mysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(),
        password.c_str(), database.c_str(), port, unix_socket, 0);

    if (m_Mysql)
    {
        sLog.outSQLDriver("MySQL client library: %s", mysql_get_client_info());
        sLog.outSQLDriver("MySQL server ver: %s ", mysql_get_server_info(m_Mysql));
        if (mysql_get_server_version(m_Mysql) != mysql_get_client_version())
            sLog.outSQLDriver("[WARNING] MySQL client/server version mismatch; may conflict with behaviour of prepared statements.");

        sLog.outDetail("Connected to MySQL database at %s", host.c_str());
        if (!mysql_autocommit(m_Mysql, 1))
            sLog.outSQLDriver("AUTOCOMMIT SUCCESSFULLY SET TO 1");
        else
            sLog.outSQLDriver("AUTOCOMMIT NOT SET TO 1");

        // set connection properties to UTF8 to properly handle locales for different
        // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
        Execute("SET NAMES `utf8`");
        Execute("SET CHARACTER SET `utf8`");

    #if MYSQL_VERSION_ID >= 50003
        my_bool my_true = (my_bool)1;
        if (mysql_options(m_Mysql, MYSQL_OPT_RECONNECT, &my_true))
            sLog.outSQLDriver("Failed to turn on MYSQL_OPT_RECONNECT.");
        else
            sLog.outSQLDriver("Successfully turned on MYSQL_OPT_RECONNECT.");
    #else
        #warning "Your mySQL client lib version does not support reconnecting after a timeout.\nIf this causes you any trouble we advice you to upgrade your mySQL client libs to at least mySQL 5.0.13 to resolve this problem."
    #endif
        return true;
    }
    else
    {
        sLog.outError("Could not connect to MySQL database at %s: %s\n", host.c_str(), mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Exemplo n.º 21
0
static JSVAL get_client_version(JSARGS args) {
	HandleScope scope;
	return scope.Close(Integer::New(mysql_get_client_version()));
}
Exemplo n.º 22
0
// unsigned long   STDCALL mysql_get_client_version(void);
static IDL_VPTR IDL_mg_mysql_get_client_version(int argc, IDL_VPTR *argv) {
    unsigned long version = mysql_get_client_version();
    return IDL_GettmpULong64(version);
}
Exemplo n.º 23
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);
}