MYSQL *_database::initialize(MYSQL *conn)
{
	return mysql_init(conn);
}
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;
    }
}
bool MySQLConnection::Initialize(const char* infoString)
{
    MYSQL* 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

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

    if (!mMysql)
    {
        sLog.outError("Could not connect to MySQL database at %s: %s\n",
                      host.c_str(), mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }

    DETAIL_LOG("Connected to MySQL database %s@%s:%s/%s", user.c_str(), host.c_str(), port_or_socket.c_str(), database.c_str());
    sLog.outString("MySQL client library: %s", mysql_get_client_info());
    sLog.outString("MySQL server ver: %s ", mysql_get_server_info(mMysql));

    /*----------SET AUTOCOMMIT ON---------*/
    // It seems mysql 5.0.x have enabled this feature
    // by default. In crash case you can lose data!!!
    // So better to turn this off
    // ---
    // This is wrong since mangos use transactions,
    // autocommit is turned of during it.
    // Setting it to on makes atomic updates work
    // ---
    // LEAVE 'AUTOCOMMIT' MODE ALWAYS ENABLED!!!
    // W/O IT EVEN 'SELECT' QUERIES WOULD REQUIRE TO BE WRAPPED INTO 'START TRANSACTION'<>'COMMIT' CLAUSES!!!
    if (!mysql_autocommit(mMysql, 1))
        DETAIL_LOG("AUTOCOMMIT SUCCESSFULLY SET TO 1");
    else
        DETAIL_LOG("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`");

    return true;
}
Beispiel #4
0
int main(int argc, char* argv[])
{
    char sPGhost[26], sPGport[26], sPGdb[26], sPGuser[26], sPGpass[26];
    printf("Postgres connection settings\n Host>");
    scanf("%s",sPGhost);
    printf(" Port>");
    scanf("%s",sPGport);
    printf(" Base>");
    scanf("%s",sPGdb);
    printf(" User>");
    scanf("%s",sPGuser);
    printf(" Pass>");
    scanf("%s",sPGpass);

    ///////////////////////////////
    ///////PGSQL Connect///////////
    ///////////////////////////////
    PGconn *mPGconn=NULL;
    mPGconn = PQsetdbLogin(sPGhost,sPGport, NULL, NULL, sPGdb, sPGuser, sPGpass);

    if (PQstatus(mPGconn) != CONNECTION_OK)
    {
        printf("Could not connect to Postgre database at [%s]: \n %s\n",sPGhost, PQerrorMessage(mPGconn));
        PQfinish(mPGconn);
        return 1;
    }
    else
    {
        printf("Connected to Postgre database at [%s]\n", sPGhost);
        printf(" PostgreSQL server ver: [%d]\n\n",PQserverVersion(mPGconn));
    }

    /// Set dummy notice processor
    PQsetNoticeProcessor(mPGconn, pg_notice, mPGconn);

    ///////////////////////////////
    ///////MySQL Connect///////////
    ///////////////////////////////
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        printf( "Could not initialize Mysql connection\n" );
        return 1;
    }

    char sMYhost[26], sMYdb[26], sMYuser[26], sMYpass[26];
    int    iMYport;
    printf("Mysql connection settings \n Host>");
    scanf("%s",sMYhost);
    printf(" Port>");
    scanf("%d",&iMYport);
    printf(" Base>");
    scanf("%s",sMYdb);
    printf(" User>");
    scanf("%s",sMYuser);
    printf(" Pass>");
    scanf("%s",sMYpass);

    mysql_options(mysqlInit,MYSQL_SET_CHARSET_NAME,"utf8");

    MYSQL *mMysql;
    mMysql = mysql_real_connect(mysqlInit, sMYhost, sMYuser,  sMYpass, sMYdb, iMYport, NULL, 0);

    if (mMysql)
    {
        printf( "Connected to MySQL database at [%s] \n", sMYhost);
        printf( " MySQL client library: [%s] \n", mysql_get_client_info());
        printf( " MySQL server ver: [%s] \n\n", mysql_get_server_info( mMysql));
    }
    else
    {
        printf("Could not connect to MySQL database at [%s]:\n %s\n", sMYhost ,mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return 1;
    }

    //////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////
    MYSQL_RES *result = NULL;
    MYSQL_ROW row;
    MYSQL_FIELD *fields = NULL;
    uint64 rowCount = 0;
    uint32 fieldCount =0;
    result = mysql_list_tables( mMysql , NULL );
    rowCount   = mysql_num_rows(result);

    /***********************/
    /* get list of tables  */
    /***********************/
    T_TableList mTableList;
    mTableList.reserve((size_t)rowCount);
    while( (row = mysql_fetch_row(result)) !=NULL )
    {
        for (uint32 i = 0;i<mysql_num_fields(result);i++)
        {
            mTableList.push_back(row[i]);
        }
    }
    mysql_free_result(result);

    /****************************************/
    /* convert filed type and default type  */
    /****************************************/
    T_Table m_Table;
    TDataBase m_DataBase_Map;
    m_DataBase_Map.clear();
    for (uint32 j=0; j<mTableList.size();++j)
    {
        result     = mysql_list_fields(mMysql, mTableList[j].c_str(), NULL);
        fieldCount = mysql_num_fields(result);
        fields     = mysql_fetch_fields(result);

        for (uint32 i=0; i<fieldCount;++i)
        {
            sField mfield;
            mfield.name   = fields[i].name;
            if (!fields[i].def)
            {
                mfield.def = "NULL";
            }
            else if (!strcmp(fields[i].def,"0000-00-00 00:00:00"))
            {
                /// Convert MySQL Default timestamp to PGSQL Default timestamp
                mfield.def.append("'1970-01-01 00:00:00'");
            }
            else
            {
                /// Append '
                mfield.def.append("'");
                mfield.def.append(fields[i].def);;
                mfield.def.append("'");
            }
            mfield.type = ConvertNativeType(fields[i].type,fields[i].length);
            mfield.flags  = fields[i].flags;
            m_Table.push_back(mfield);
        }
        m_DataBase_Map[mTableList[j]] = m_Table;
        m_Table.clear();
        mysql_free_result(result);
    }

    /******************************************/
    /* Conversion of the layout of the tables */
    /******************************************/

    uint32 count = 0;
    TDataBase::const_iterator citr;
    for (citr = m_DataBase_Map.begin(); citr != m_DataBase_Map.end(); ++citr)
    {
        ostringstream sql_str;
        sql_str<<"DROP TABLE IF EXISTS "<<(*citr).first.c_str()<<";\n";
        sql_str<<"CREATE TABLE "<<(*citr).first.c_str()<<"(\n";

        T_Table::const_iterator v_iter;
        ostringstream prim_key_str;
        ostringstream index_str;
        for (v_iter = (*citr).second.begin();
            v_iter != (*citr).second.end();
            ++v_iter)
        {
            sql_str<<" "<<(*v_iter).name;
            if (((*v_iter).flags & AUTO_INCREMENT_FLAG)!=0)
            {
                /// AUTO_INCREMENT fields not have "default" data
                sql_str<<" bigserial";
            }
            else
            {
                sql_str<<" "<<(*v_iter).type;
                sql_str<<" default "<<(*v_iter).def;
            }
            /// IF column have PRIMARY KEY flag then use column in PRIMARY KEY
            if (IS_PRI_KEY( (*v_iter).flags )!=0)
            {
                if( prim_key_str.str().size())
                    prim_key_str << ", ";
                else
                {
                    prim_key_str << "ALTER TABLE ";
                    prim_key_str << (*citr).first.c_str();
                    prim_key_str << " ADD CONSTRAINT pk_";
                    prim_key_str << (*citr).first.c_str();
                    prim_key_str << "_";
                    prim_key_str << (*v_iter).name;
                    prim_key_str << " PRIMARY KEY (";
                }
                prim_key_str<<(*v_iter).name;
            }
            else if (((*v_iter).flags & MULTIPLE_KEY_FLAG)!=0)
            {
                /// IF column have INDEX flag then create INDEX
                index_str << "CREATE INDEX  idx_";
                index_str << (*citr).first.c_str();
                index_str << "_";
                index_str << (*v_iter).name;
                index_str << " ON ";
                index_str << (*citr).first.c_str();
                index_str << " USING btree (";
                index_str << (*v_iter).name;
                index_str << ");\n";
            }
            else if (((*v_iter).flags & UNIQUE_KEY_FLAG)!=0)
            {
                /// IF column have UNIQUE INDEX flag then create INDEX
                index_str << "CREATE UNIQUE INDEX  uidx_";
                index_str << (*citr).first.c_str();
                index_str << "_";
                index_str << (*v_iter).name;
                index_str << " ON ";
                index_str << (*citr).first.c_str();
                index_str << " USING btree (";
                index_str << (*v_iter).name;
                index_str << ");\n";
            }
            /// don't output "," for last column
            if(v_iter + 1 != (*citr).second.end())
                sql_str<< ",\n";
            else
                sql_str<< "\n";
        }
        sql_str<< ")\n";

        /// Out Table structure
        PG_Exec_str(sql_str.str(),mPGconn);

        /// out PRIMARY KEY
        if(prim_key_str.str().size())
        {
            prim_key_str<<")";
            PG_Exec_str(prim_key_str.str(),mPGconn);
        }

        /// out INDEX's
        if (index_str.str().size())
            PG_Exec_str(index_str.str(),mPGconn);

        ++count;
        printf("Convert [%d] tables...\r",count);
    }
    printf("Completed the conversion of [%d] tables!\n", count);

    /****************/
    /* Copying data */
    /****************/

    count = 0;
    for (uint32 j=0; j<mTableList.size();++j)
    {
        ostringstream sql_str;
        sql_str << "SELECT * FROM ";
        sql_str << mTableList[j].c_str();

        if (mysql_query(mysqlInit,sql_str.str().c_str()) )
            continue;
        if (!(result = mysql_store_result(mysqlInit)))
            continue;

        while ((row = mysql_fetch_row(result))!=NULL)
        {
            ostringstream insert_str;
            insert_str << "INSERT INTO ";
            insert_str << mTableList[j].c_str();
            insert_str << " VALUES (";

            fieldCount = mysql_num_fields(result);
            fields     = mysql_fetch_fields(result);
            for (uint32 i = 0 ; i < fieldCount ; ++i)
            {
                if (!row[i])
                    insert_str << "NULL";
                else
                {
                    if (IsNeeedEscapeString(fields[i].type))
                    {
                        string field_str = row[i];
                        PG_Escape_Str(field_str);
                        insert_str << "E'";
                        insert_str << field_str.c_str();
                        insert_str << "'";
                    }
                    else if (!strcmp(row[i],"0000-00-00 00:00:00"))
                    {
                        /// Convert MySQL  timestamp to PGSQL timestamp
                        insert_str << "'1970-01-01 00:00:00'";
                    }
                    else
                    {
                        insert_str << "'";
                        insert_str << row[i];
                        insert_str << "'";
                    }
                }

                /// don't output "," for last column
                if(i + 1 != fieldCount )
                    insert_str<< ",";
                else
                    insert_str<< ")\n";
            }
            PG_Exec_str(insert_str.str(), mPGconn);
        }
        mysql_free_result(result);
        ++count;
        printf("Copied data from [%d] tables...\r",count);
    }
    printf("Finished copying the data from [%d] tables!\n",count);
    mTableList.clear();
    m_DataBase_Map.clear();

    /// Close connections
    mysql_close(mMysql);
    PQfinish(mPGconn);

    printf("end\n");
    return 0;

}
Beispiel #5
0
TC_Mysql::TC_Mysql()
:_bConnected(false)
{
    _pstMql = mysql_init(NULL);
}
Beispiel #6
0
/** connection to database */
fsal_posixdb_status_t fsal_posixdb_connect(fsal_posixdb_conn_params_t * dbparams,
        fsal_posixdb_conn ** p_conn)
{
    my_bool reconnect = 1;
    char password[1024] = "";
    int rc;
    unsigned int port;

    /* read password from password file */
    rc = ReadPasswordFromFile(dbparams->passwdfile, password);
    if(rc)
        ReturnCodeDB(ERR_FSAL_POSIXDB_CMDFAILED, rc);

    /* resolve the port number */
    if(dbparams->port[0] != '\0')
    {
        if(!isdigit(dbparams->port[0]))
        {
            LogCrit(COMPONENT_FSAL,
                    "Numerical value expected for database port number (invalid value: %s)",
                    dbparams->port);
            ReturnCodeDB(ERR_FSAL_POSIXDB_CMDFAILED, 0);
        }

        port = atoi(dbparams->port);
    }
    else
        port = 0;

    *p_conn = gsh_malloc(sizeof(fsal_posixdb_conn));
    if(*p_conn == NULL)
    {
        LogCrit(COMPONENT_FSAL, "ERROR: failed to allocate memory");
        ReturnCodeDB(ERR_FSAL_POSIXDB_NO_MEM, errno);
    }

    /* Init client structure */
    if(mysql_init(&(*p_conn)->db_conn) == NULL)
    {
        gsh_free(*p_conn);
        LogCrit(COMPONENT_FSAL, "ERROR: failed to create MySQL client struct");
        ReturnCodeDB(ERR_FSAL_POSIXDB_BADCONN, errno);
    }
#if ( MYSQL_VERSION_ID >= 50013 )
    /* set auto-reconnect option */
    mysql_options(&(*p_conn)->db_conn, MYSQL_OPT_RECONNECT, &reconnect);
#else
    /* older version */
    (*p_conn)->db_conn->reconnect = 1;
#endif

    /* connect to server */
    if(!mysql_real_connect(&(*p_conn)->db_conn, dbparams->host, dbparams->login,
                           password, dbparams->dbname, port, NULL, 0))
    {
        int rc;
        LogCrit(COMPONENT_FSAL, "Failed to connect to MySQL server: Error: %s",
                mysql_error(&(*p_conn)->db_conn));
        rc = mysql_errno(&(*p_conn)->db_conn);
        gsh_free(*p_conn);
        ReturnCodeDB(ERR_FSAL_POSIXDB_BADCONN, rc);
    }

    /* Note [MySQL reference guide]: mysql_real_connect()  incorrectly reset
     * the MYSQL_OPT_RECONNECT  option to its default value before MySQL 5.1.6.
     * Therefore, prior to that version, if you want reconnect to be enabled for
     * each connection, you must call mysql_options() with the MYSQL_OPT_RECONNECT
     * option after each call to mysql_real_connect().
     */
#if (MYSQL_VERSION_ID >= 50013) && (MYSQL_VERSION_ID < 50106)
    /* reset auto-reconnect option */
    mysql_options(&(*p_conn)->db_conn, MYSQL_OPT_RECONNECT, &reconnect);
#endif

    LogEvent(COMPONENT_FSAL, "Logged on to database sucessfully");

    /* Create prepared statements */
    return fsal_posixdb_initPreparedQueries(*p_conn);

}
/*%
 * Create an instance of the module.
 */
isc_result_t
dlz_create(const char *dlzname, unsigned int argc, char *argv[],
	   void **dbdata, ...)
{
	isc_result_t result = ISC_R_FAILURE;
	mysql_instance_t *mysql = NULL;
	dbinstance_t *dbi = NULL;
	MYSQL *dbc;
	char *tmp = NULL;
	char *endp;
	int j;
	const char *helper_name;
#if MYSQL_VERSION_ID >= 50000
        my_bool auto_reconnect = 1;
#endif
#if PTHREADS
	int dbcount;
	int i;
#endif /* PTHREADS */
	va_list ap;

	UNUSED(dlzname);

	/* allocate memory for MySQL instance */
	mysql = calloc(1, sizeof(mysql_instance_t));
	if (mysql == NULL)
		return (ISC_R_NOMEMORY);
	memset(mysql, 0, sizeof(mysql_instance_t));

	/* Fill in the helper functions */
	va_start(ap, dbdata);
	while ((helper_name = va_arg(ap, const char*)) != NULL)
		b9_add_helper(mysql, helper_name, va_arg(ap, void*));
	va_end(ap);

#if PTHREADS
	/* if debugging, let user know we are multithreaded. */
	mysql->log(ISC_LOG_DEBUG(1), "MySQL module running multithreaded");
#else /* PTHREADS */
	/* if debugging, let user know we are single threaded. */
	mysql->log(ISC_LOG_DEBUG(1), "MySQL module running single threaded");
#endif /* PTHREADS */

	/* verify we have at least 4 arg's passed to the module */
	if (argc < 4) {
		mysql->log(ISC_LOG_ERROR,
			   "MySQL module requires "
			   "at least 4 command line args.");
		return (ISC_R_FAILURE);
	}

	/* no more than 8 arg's should be passed to the module */
	if (argc > 8) {
		mysql->log(ISC_LOG_ERROR,
			   "MySQL module cannot accept "
			   "more than 7 command line args.");
		return (ISC_R_FAILURE);
	}

	/* get db name - required */
	mysql->dbname = get_parameter_value(argv[1], "dbname=");
	if (mysql->dbname == NULL) {
		mysql->log(ISC_LOG_ERROR,
			   "MySQL module requires a dbname parameter.");
		result = ISC_R_FAILURE;
		goto cleanup;
	}

	/* get db port.  Not required, but must be > 0 if specified */
	tmp = get_parameter_value(argv[1], "port=");
	if (tmp == NULL)
		mysql->port = 0;
	else {
		mysql->port = strtol(tmp, &endp, 10);
		if (*endp != '\0' || mysql->port < 0) {
			mysql->log(ISC_LOG_ERROR,
				   "Mysql module: port "
				   "must be a positive number.");
			free(tmp);
			result = ISC_R_FAILURE;
			goto cleanup;
		}
		free(tmp);
	}

	mysql->host = get_parameter_value(argv[1], "host=");
	mysql->user = get_parameter_value(argv[1], "user="******"pass="******"socket=");

	mysql->flags = CLIENT_REMEMBER_OPTIONS;

	tmp = get_parameter_value(argv[1], "compress=");
	if (tmp != NULL) {
		if (strcasecmp(tmp, "true") == 0)
			mysql->flags |= CLIENT_COMPRESS;
		free(tmp);
	}

	tmp = get_parameter_value(argv[1], "ssl=");
	if (tmp != NULL) {
		if (strcasecmp(tmp, "true") == 0)
			mysql->flags |= CLIENT_SSL;
		free(tmp);
	}

	tmp = get_parameter_value(argv[1], "space=");
	if (tmp != NULL) {
		if (strcasecmp(tmp, "ignore") == 0)
			mysql->flags |= CLIENT_IGNORE_SPACE;
		free(tmp);
	}

#if PTHREADS
	/* multithreaded build can have multiple DB connections */
	tmp = get_parameter_value(argv[1], "threads=");
	if (tmp == NULL)
		dbcount = 1;
	else {
		dbcount = strtol(tmp, &endp, 10);
		if (*endp != '\0' || dbcount < 1) {
			mysql->log(ISC_LOG_ERROR,
				   "MySQL database connection count "
				   "must be positive.");
			free(tmp);
			result = ISC_R_FAILURE;
			goto cleanup;
		}
		free(tmp);
	}

	/* allocate memory for database connection list */
	mysql->db = calloc(1, sizeof(db_list_t));
	if (mysql->db == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}

	/* initialize DB connection list */
	DLZ_LIST_INIT(*(mysql->db));

	/*
	 * create the appropriate number of database instances (DBI)
	 * append each new DBI to the end of the list
	 */
	for (i = 0; i < dbcount; i++) {
#endif /* PTHREADS */
		switch(argc) {
		case 4:
			result = build_dbinstance(NULL, NULL, NULL,
						  argv[2], argv[3], NULL,
						  &dbi, mysql->log);
			break;
		case 5:
			result = build_dbinstance(NULL, NULL, argv[4],
						  argv[2], argv[3], NULL,
						  &dbi, mysql->log);
			break;
		case 6:
			result = build_dbinstance(argv[5], NULL, argv[4],
						  argv[2], argv[3], NULL,
						  &dbi, mysql->log);
			break;
		case 7:
			result = build_dbinstance(argv[5], argv[6], argv[4],
						  argv[2], argv[3], NULL,
						  &dbi, mysql->log);
			break;
		case 8:
			result = build_dbinstance(argv[5], argv[6], argv[4],
						  argv[2], argv[3], argv[7],
						  &dbi, mysql->log);
			break;
		default:
			result = ISC_R_FAILURE;
		}


		if (result != ISC_R_SUCCESS) {
			mysql->log(ISC_LOG_ERROR,
				   "MySQL module could not create "
				   "database instance object.");
			result = ISC_R_FAILURE;
			goto cleanup;
		}

#if PTHREADS
		/* when multithreaded, build a list of DBI's */
		DLZ_LINK_INIT(dbi, link);
		DLZ_LIST_APPEND(*(mysql->db), dbi, link);
#else
		/*
		 * when single threaded, hold onto the one connection
		 * instance.
		 */
		mysql->db = dbi;
#endif

		/* create and set db connection */
		dbi->dbconn = mysql_init(NULL);
		if (dbi->dbconn == NULL) {
			mysql->log(ISC_LOG_ERROR,
				   "MySQL module could not allocate "
				   "memory for database connection");
			result = ISC_R_FAILURE;
			goto cleanup;
		}

		dbc = NULL;

#if MYSQL_VERSION_ID >= 50000
		/* enable automatic reconnection. */
		if (mysql_options((MYSQL *) dbi->dbconn, MYSQL_OPT_RECONNECT,
				  &auto_reconnect) != 0) {
			mysql->log(ISC_LOG_WARNING,
				   "MySQL module failed to set "
				   "MYSQL_OPT_RECONNECT option, continuing");
		}
#endif

		for (j = 0; dbc == NULL && j < 4; j++) {
			dbc = mysql_real_connect((MYSQL *) dbi->dbconn,
						 mysql->host, mysql->user,
						 mysql->pass, mysql->dbname,
						 mysql->port, mysql->socket,
						 mysql->flags);
			if (dbc == NULL)
				mysql->log(ISC_LOG_ERROR,
					   "MySQL connection failed: %s",
					   mysql_error((MYSQL *) dbi->dbconn));
		}

		if (dbc == NULL) {
			mysql->log(ISC_LOG_ERROR,
				   "MySQL module failed to create "
				   "database connection after 4 attempts");
			result = ISC_R_FAILURE;
			goto cleanup;
		}

#if PTHREADS
		/* set DBI = null for next loop through. */
		dbi = NULL;
	}
#endif /* PTHREADS */

	*dbdata = mysql;

	return (ISC_R_SUCCESS);

 cleanup:
	dlz_destroy(mysql);

	return (result);
}
Beispiel #8
0
int
main(int argc,char **argv)
{
    int opt;
    int digit_optind = 0;
    char *dbprofile = "/etc/my.cnf";

	int lc,lcw,lt,prs,conferr;	//Innodb locks number.

    CNF cnf;
    cnf.host = (char *)malloc(sizeof(char)*128);
    cnf.user = (char *)malloc(sizeof(char)*128);
    cnf.password = (char *)malloc(sizeof(char)*128);
    cnf.port = 0;
    cnf.socket = (char *)malloc(sizeof(char)*128);
    cnf.pidfile = (char *)malloc(sizeof(char)*128);

    memset(cnf.host,0,128);
    memset(cnf.user,0,128);
    memset(cnf.password,0,128);
    memset(cnf.socket,0,128);
    memset(cnf.pidfile,0,128);

    if(argc <=  1){
	    //如果没有给参数,就去/etc/my.cnf中取
	    parse_cnf(dbprofile,&cnf);
    }else{
	    while(1){
		    int this_option_optind = optind? optind: 1;
		    int option_index = 0;
		    static struct option long_options[] = {
			    {"osinfo",no_argument,0,'o'},
			    {"appls",no_argument,0,'a'},
			    {"bufps",no_argument,0,'b'}
		    };
		    opt = getopt_long(argc,argv,"h:P:u:p:s:",long_options,&option_index);
		    if(opt == -1)
			    break;

		    switch(opt){
			    case 'h':
				    sprintf(cnf.host,"%s",optarg);
				    break;
			    case 'P':
				    cnf.port = atoi(optarg);
				    break;
			    case 'u':
				    sprintf(cnf.user,optarg);
				    break;
			    case 'p':
				    sprintf(cnf.password,optarg);
				    break;
			    case 's':
				    sprintf(cnf.socket,optarg);
				    break;
			    default:
				    fprintf(stdout,"Parametera Error");
		    }

	    }	
    }

    PLA *pla;
    pla = (PLA*)malloc(sizeof(PLA));


	//定义Osinfo的一个实例
	Osinfo *os;
	int get_os_info_res = 0;
	os = (Osinfo *)malloc(sizeof(Osinfo));
	malloc_os_info(os);
        os->port = cnf.port;

    //获取操作系统状态信息
    get_os_info_res = get_os_info(os);
    if(get_os_info_res == -1){
        perror("get_os_info()");
        exit(1);
    }


	/*创建一个数据库快照实例并初始化这个实例。*/
	MysqlSnapshot ms;
	malloc_ms(&ms);

	/*性能指标信息*/
	PERF perf;
	malloc_perf(&perf);

	/*Innodb Locks Summary*/
	INNODB_LOCK ail[]={0};
	INNODB_LOCK **il;
	il = (INNODB_LOCK **)&ail;
	INNODB_LOCKWAIT ailw[]={0};
	INNODB_LOCKWAIT **ilw;
	ilw = (INNODB_LOCKWAIT **)&ailw;
	INNODB_TRX ait[]={0};
	INNODB_TRX **it;
	it = (INNODB_TRX **)&ait;
	MYPS amps[]={0};
	MYPS **procs;
	procs = (MYPS **)&amps;

	//得到CPU硬件信息
	get_cpu_hardinfo(os);
	//得到内存信息
	get_mem_info(os);
	//得到系统负载信息
	get_loadavg_info(os);
	//得到CPU运行状态
	get_cpuavg_info(os);


	/*创建一个MySQL数据库连接*/
	MYSQL *conn = NULL;
	conn = mysql_init(NULL);

	//连接到MySQL服务。
	mysql_real_connect(conn,cnf.host,cnf.user,cnf.password,NULL,cnf.port,cnf.socket,0);
	if(conn->net.last_errno != 0){
		fprintf(stdout,"%s,host=%s,port=%d,region=%s,sport=%d Connection_ErrMsg=\"%s\",Connection_Errno=%d\n","ParateraDB",os->hostname,os->port,"DatabaseConnection",cnf.port,conn->net.last_error,conn->net.last_errno);
		exit(conn->net.last_errno);
	}

	fprintf(stdout,"%s,host=%s,port=%d,region=%s,sport=%d Connection_errMsg=\"OK\",Connection_Errno=%d\n","ParateraDB",os->hostname,os->port,"DatabaseConnection",cnf.port,conn->net.last_errno);
	//if(strstr(mysql_get_server_info(conn),"5.6") == NULL){
	//	fprintf(stderr,"Server Unknown\n");
	//	exit(0);
	//}

  	//得到数据库服务器快照信息
	get_mysql_snapshot(&ms,conn);
	//获取系统性能信息
	get_perf(&ms,&perf,conn);
	//打印数据库服务器快照信息
	get_process_summary(conn,procs,&prs);
	//打印数据库服务器快照信息
	get_innodb_locks_summary(conn,il,&lc);
	get_innodb_lockwait_summary(conn,ilw,&lcw);
	//获取INNODB存储引擎的SQL查询内容.
	get_innodb_transactions_summary(conn,it,&lt);
	//得到文件系统使用信息
	get_fsusage(&ms);
	processlist_analysis(conn,pla);
	influx_files_output(os,&ms,&perf);
	influx_appls_output(os,&ms,&perf,pla);
	influx_locks_output(os,&ms);
	influx_bufps_output(os,&ms,&perf);
	influx_query_output(os,&ms,&perf);
	influx_threads_output(os,&ms,&perf);
	influx_logs_output(os,&ms,&perf);
	if(strstr(ms.version,"5.6") != NULL){
		ShowSlaveStatus(&ms,conn);
		influx_slave_status_output(&ms,os);
	}
	else if(strstr(ms.version,"5.7") != NULL){
		ShowSlaveStatus7(&ms,conn);
		influx_slave_status_output7(&ms,os);
	}
	else{
		fprintf(stderr,"Not Support Database Version\n");
	}

	influx_mmtrk_output(os,&ms);
	influx_wsrep_output(&ms,os);

	exit(0);
}
Beispiel #9
0
int cgiMain() {
#ifdef MYSQL_DB
  static MYSQL *dbh;              /* database connect handle */
  static MYSQL_RES *result;       /* database query results  */
  static MYSQL_ROW values;        /* query data returned     */
  unsigned int colcount    =0;    /* number of returned columns */
  int server_version;             /* returned server version */
#endif
#ifdef ORACLE_DB
  sqlo_db_handle_t dbh;           /* database handle */
  sqlo_stmt_handle_t sth1;        /* statement handle 1 */
  char server_version[1024]="";   /* string for returned server version */
  int stat                 =0;    /* status of sqlo calls */
  int handle               =0;    /* handle of the interrupt handler */
  //const char ** colnames;         /* column names */
  const char ** values;           /* values */
#endif
  char sqlquery_str[1024]  ="";   /* SQL query string */
  char **form_data;               /* string array for query data */
  char username[49]        ="";   /* selected username */
  char first_start_date[11]="";   /* first connect start date */
  char first_start_time[6] ="";   /* first connect start time */
  char first_end_date[11]  ="";   /* first connect end date */
  char first_end_time[6]   ="";   /* first connect end time */
  char last_start_date[11] ="";   /* last connect start date */
  char last_start_time[6]  ="";   /* last connect start time */
  char last_end_date[11]   ="";   /* last connect end date */
  char last_end_time[6]    ="";   /* last connect end time */
  char title[256]          = "";  /* cgi title string */
  int allrows              =0;    /* number of returned rows */
  int rowcount             =0;    /* row iteration counter */
  div_t oddline_calc;             /* calculates even/odd row color */
  char err_str[2048]       ="";   /* use for combined error string */
  _abort_flag     = 0;

  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
  /* ------------------------------------------------------------------- *
   * If we are not called with arguments, we display a error message.    *
   * ------------------------------------------------------------------- */
    cgi_error("Error: Could not retrieve form data.");

  /* ------------------------------------------------------------------- *
   * check if we got all information to make the SQL query               *
   * --------------------------------------------------------------------*/
  if ( cgiFormString("username", username, sizeof(username))
                                                     != cgiFormSuccess )
    cgi_error("Error retrieving the username.");

#ifdef ORACLE_DB
  /* ------------------------------------------------------------------- * 
   * ORACLE_HOME is needed for OCI8 to find tnsnames.ora                 *
   * ------------------------------------------------------------------- */
  putenv(WEB_ORACLE_ENV);

  /* initialize the connection */
  if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100))
    cgi_error("Error: Failed to init libsqlora8.");

  /* register the interrupt handler */
  sqlo_register_int_handler(&handle, sigint_handler);

  /* login to the database */
  if (SQLO_SUCCESS != sqlo_connect(&dbh, WEB_TNS_STRING))
    cgi_error("Error: Cannot connect to database.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  if (SQLO_SUCCESS != sqlo_server_version(dbh, server_version,
                                        sizeof(server_version)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* enable autocommit, each statement is commited as a single transaction */
  stat = sqlo_set_autocommit(dbh, 1);

  /* define the SQL query */
  snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s FROM %s.EDACS_REMOTE WHERE USERNAME='******' ORDER BY IP_OR_PHONE",
           "IP_OR_PHONE",                                              /* 00 */
           "TO_CHAR(FIRST_CONNECT, 'dd-mm-yyyy')",                     /* 01 */
           "TO_CHAR(FIRST_CONNECT, 'hh24:mi:ss')",                     /* 02 */
           "TO_CHAR(FIRST_CONNECT+INTERVAL '1' MINUTE, 'dd-mm-yyyy')", /* 03 */
           "TO_CHAR(FIRST_CONNECT+INTERVAL '1' MINUTE, 'hh24:mi')",    /* 04 */
           "TO_CHAR(LAST_CONNECT, 'dd-mm-yyyy')",                      /* 05 */
           "TO_CHAR(LAST_CONNECT, 'hh24:mi:ss')",                      /* 06 */
           "TO_CHAR(LAST_CONNECT+INTERVAL '1' MINUTE, 'dd-mm-yyyy')",  /* 07 */
           "TO_CHAR(LAST_CONNECT+INTERVAL '1' MINUTE, 'hh24:mi')",     /* 08 */
	   EDACSADMIN, username);
	   // cgi_error(sqlquery_str); /* DEBUG output of the SQL string */

  /* initialize the statement handle */
  sth1 = SQLO_STH_INIT;

  /* opens a cursor for the query statement */
  if ( 0 > (sqlo_open2(&sth1, dbh, sqlquery_str, 0, NULL)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* get the output column names */
  //if (SQLO_SUCCESS != sqlo_ocol_names2(sth1, &colcount, &colnames))
  //  cgi_error("Error getting the DB columns with sqlo_ocol_names2()");
  //RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
  /* initialize the connection */
  dbh = mysql_init(NULL);
  if(dbh == NULL) cgi_error("Error:  Failed to init MySQL DB.");

  /* login to the database */
  if (mysql_real_connect(dbh, MYSQLIP, EDACSADMIN, ADMIN_PASS, DB_NAME, DB_PORT, NULL, 0) == 0)
    cgi_error("Error: Cannot connect to database.");

  /* Get the database version */
  server_version = mysql_get_server_version(dbh);

  /* create the SQL query string */
  snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s FROM edacs_remote WHERE username='******' ORDER BY ip_or_phone",
           "ip_or_phone",                                                /* 00 */
           "DATE_FORMAT(first_connect, '%d-%m-%Y')",                     /* 01 */
           "DATE_FORMAT(first_connect, '%H:%i:%s')",                     /* 02 */
           "DATE_FORMAT(first_connect+INTERVAL '1' MINUTE, '%d-%m-%Y')", /* 03 */
           "DATE_FORMAT(first_connect+INTERVAL '1' MINUTE, '%H:%i')",    /* 04 */
           "DATE_FORMAT(last_connect, '%d-%m-%Y')",                      /* 05 */
           "DATE_FORMAT(last_connect, '%H:%i:%s')",                      /* 06 */
           "DATE_FORMAT(last_connect+INTERVAL '1' MINUTE, '%d-%m-%Y')",  /* 07 */
           "DATE_FORMAT(last_connect+INTERVAL '1' MINUTE, '%H:%i')",     /* 08 */
           username);
           // cgi_error(sqlquery_str); /* DEBUG output of the SQL string */

  /* Prepare and execute the SQL statement */
  if(mysql_query(dbh, sqlquery_str) != 0) {
    if(DEBUG == 0) cgi_error(mysql_error(dbh));
    else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
             mysql_error(dbh), sqlquery_str);
    cgi_error(err_str);
  }
 /* get query results set */
  result = mysql_store_result(dbh);
  if (result == NULL) {
    snprintf(err_str, sizeof(err_str), "No results for query: %s\n", sqlquery_str);
    cgi_error( err_str);
  }

  allrows = mysql_num_rows(result);
  colcount = mysql_num_fields(result);
#endif

/* -------------------------------------------------------------------------- *
 * start the html output                                                      *
 * ---------------------------------------------------------------------------*/

  /* define the CGI title */
  snprintf(title, sizeof(title), "User Information for '%s'", username);
  pagehead(title);
  fprintf(cgiOut, "<div id=\"content\">\n");

  fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th class=\"inner\">#</th>\n");
  fprintf(cgiOut, "<th class=\"inner\">Remote IP / Phone</th>\n");
  fprintf(cgiOut, "<th class=\"inner\">Active Since</th>\n");
  fprintf(cgiOut, "<th class=\"inner\">Last Update</th>\n");
  fprintf(cgiOut, "</tr>\n");

  /* fetch the data */
#ifdef ORACLE_DB
  while ( SQLO_SUCCESS == (stat = (sqlo_fetch(sth1, 1)))) {
    /* get one record */
    values = sqlo_values(sth1, NULL, 1);
#endif
#ifdef MYSQL_DB
   while((values = mysql_fetch_row(result)) != NULL) {
#endif
    rowcount++;

     /* check for even/odd rows */
     oddline_calc = div(rowcount, 2);
     if(oddline_calc.rem) fprintf(cgiOut, "<tr class=\"odd\">\n");
     else fprintf(cgiOut, "<tr class=\"even\">\n");

    /* calculate start and end times for link to session query */
    strncpy(first_start_date, values[1], sizeof(first_start_date)-1);
    first_start_date[2] = '.';
    first_start_date[5] = '.';
    first_start_date[10] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(first_start_time, values[2], sizeof(first_start_time)-1);
    first_start_time[5] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(first_end_date, values[3], sizeof(first_end_date)-1);
    first_end_date[2] = '.';
    first_end_date[5] = '.';
    first_end_date[10] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(first_end_time, values[4], sizeof(first_end_time)-1);
    first_end_time[5] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(last_start_date, values[5], sizeof(last_start_date)-1);
    last_start_date[2] = '.';
    last_start_date[5] = '.';
    last_start_date[10] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(last_start_time, values[6], sizeof(last_start_time)-1);
    last_start_time[5] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(last_end_date, values[7], sizeof(last_end_date)-1);
    last_end_date[2] = '.';
    last_end_date[5] = '.';
    last_end_date[10] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(last_end_time, values[8], sizeof(last_end_time)-1);
    last_end_time[5] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    fprintf(cgiOut, "<td>%d</td>\n", rowcount);
    fprintf(cgiOut, "<td>%s</td>", values[0]);
    fprintf(cgiOut, "<td>");
    fprintf(cgiOut, "<a href=user-acttime.cgi?start_date=%s&start_time=%s&end_date=%s&end_time=%s&sort_order=asc&username=%s&order_by=start_date>", first_start_date, first_start_time, first_end_date, first_end_time, username);
    fprintf(cgiOut, "%s %s</a></td>", values[1], values[2]);

    fprintf(cgiOut, "<td>");
    fprintf(cgiOut, "<a href=user-acttime.cgi?start_date=%s&start_time=%s&end_date=%s&end_time=%s&sort_order=asc&username=%s&order_by=start_date&select_by=stop_date>", last_start_date, last_start_time, last_end_date, last_end_time, username);
    fprintf(cgiOut, "%s %s</a></td>", values[5], values[6]);
    fprintf(cgiOut, "</tr>\n");
  }
#ifdef ORACLE_DB
  if (SQLO_SUCCESS != sqlo_close(sth1))
    cgi_error("Error Closing the SQL statment handle.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
   mysql_close(dbh);
#endif
  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th class=\"inner\" colspan=4>");
  fprintf(cgiOut, "&nbsp;");
  fprintf(cgiOut, "</th>\n");
  fprintf(cgiOut, "</tr>\n");
  fprintf(cgiOut, "</table>\n");

  fprintf(cgiOut, "<h3>Additional Information</h3>\n");
  fprintf(cgiOut, "<hr>\n");
  fprintf(cgiOut, "<p>");
  fprintf(cgiOut, "This list represents all remote IP addresses or telephone numbers this user connected from.");
  fprintf(cgiOut, "<ul>");
  fprintf(cgiOut, "<li>The \"Remote IP / Phone\" is the remote ISP IP address of a user in case of a VPN connection, or his telephone number reported when connecting via dial-up. If the value is unknown, the connection came from a line that has caller-ID supression or is a plain old analog modem line.");
  fprintf(cgiOut, "<li>The \"Active Since\" is the first time session information was received. The time links to the first recorded session for this user, coming from this particular remote IP or phone.");
  fprintf(cgiOut, "<li>The \"Last Update\" time shows when the latest session record was received. The link tries to find the latest session. Sometimes the session is still in progress and incomplete or no data is returned.");
  fprintf(cgiOut, "</ul>");
  fprintf(cgiOut, "</p>\n");

  pageside();
  pagefoot();
  return(0);
}
Beispiel #10
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)
    {
      static bool showed_ver_info = false;
      if (!showed_ver_info)
      {
        CLog::Log(LOGINFO, "MYSQL: Connected to version %s", mysql_get_server_info(conn));
        showed_ver_info = true;
      }

      // 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));
      }

      configure_connection();

      // 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;
}
/* {{{ flt_admin_mysql_init */
int flt_admin_mysql_init(cf_hash_t *cgi,cf_configuration_t *cfg) {
  MYSQL *ret;
  MYSQL_RES *result;
  MYSQL_ROW row;

  cf_string_t query;
  u_char *buff,*uname = cf_hash_get(GlobalValues,"UserName",8);
  unsigned int len;

  cf_cfg_config_value_t *host = cf_cfg_get_value(cfg,"MySqlAdmin:Host"),
    *user = cf_cfg_get_value(cfg,"MySqlAdmin:User"),
    *pass = cf_cfg_get_value(cfg,"MySqlAdmin:Password"),
    *db = cf_cfg_get_value(cfg,"MySqlAdmin:Database"),
    *port = cf_cfg_get_value(cfg,"MySqlAdmin:Port"),
    *socket = cf_cfg_get_value(cfg,"MySqlAdmin:Socket");

  if(!uname) return FLT_DECLINE;

  /* {{{ create connection */
  if((flt_amsql_dbh = mysql_init(NULL)) == NULL) return FLT_EXIT;
  mysql_options(flt_amsql_dbh,MYSQL_READ_DEFAULT_GROUP,"cforum");

  if((ret = mysql_real_connect(flt_amsql_dbh,host?host->sval:NULL,user?user->sval:NULL,pass?pass->sval:NULL,db?db->sval:NULL,port?port->ival:0,socket?socket->sval:NULL,0)) == NULL) return FLT_EXIT;
  /* }}} */

  /* {{{ create query */
  cf_str_init_growth(&query,128);
  cf_str_char_set(&query,"SELECT ",7);
  cf_str_chars_append(&query,flt_amsql_field,strlen(flt_amsql_field));
  cf_str_chars_append(&query," FROM ",6);
  cf_str_chars_append(&query,flt_amsql_table,strlen(flt_amsql_table));
  cf_str_chars_append(&query," WHERE ",7);
  cf_str_chars_append(&query,flt_amsql_wfield,strlen(flt_amsql_wfield));
  cf_str_chars_append(&query," = '",4);

  len  = strlen(uname);
  buff = cf_alloc(NULL,1,len * 2 + 1,CF_ALLOC_MALLOC);
  len  = mysql_real_escape_string(flt_amsql_dbh,buff,uname,len);

  cf_str_chars_append(&query,buff,len);
  free(buff);

  cf_str_char_append(&query,'\'');
  /* }}} */

  if(mysql_real_query(flt_amsql_dbh,query.content,query.len) != 0) {
    cf_str_cleanup(&query);
    return FLT_DECLINE;
  }

  cf_str_cleanup(&query);

  if((result = mysql_store_result(flt_amsql_dbh)) == NULL) return FLT_DECLINE;

  if((row = mysql_fetch_row(result)) == NULL) {
    mysql_free_result(result);
    return FLT_DECLINE;
  }

  if(row[0] == NULL) {
    mysql_free_result(result);
    return FLT_DECLINE;
  }

  if(atoi(row[0]) != 0 || cf_strcmp(row[0],"admin") == 0) cf_hash_set(GlobalValues,"is_admin",8,"1",1);
  mysql_free_result(result);

  return FLT_OK;
}
int main(int argc, char** argv)
{
  if (argc != 3)
  {
    std::cout << "Arguments are <socket mysqld> <connect_string cluster>.\n";
    exit(-1);
  }
  char * mysqld_sock  = argv[1];
  const char *connectstring = argv[2];
  ndb_init();

  Ndb_cluster_connection *cluster_connection=
    new Ndb_cluster_connection(connectstring); // Object representing the cluster

  int r= cluster_connection->connect(5 /* retries               */,
				     3 /* delay between retries */,
				     1 /* verbose               */);
  if (r > 0)
  {
    std::cout
      << "Cluster connect failed, possibly resolved with more retries.\n";
    exit(-1);
  }
  else if (r < 0)
  {
    std::cout
      << "Cluster connect failed.\n";
    exit(-1);
  }

  if (cluster_connection->wait_until_ready(30,0) < 0)
  {
    std::cout << "Cluster was not ready within 30 secs." << std::endl;
    exit(-1);
  }
					   
  // connect to mysql server
  MYSQL mysql;
  if ( !mysql_init(&mysql) ) {
    std::cout << "mysql_init failed\n";
    exit(-1);
  }
  if ( !mysql_real_connect(&mysql, "localhost", "root", "", "",
			   0, mysqld_sock, 0) )
    MYSQLERROR(mysql);
  
  /********************************************
   * Connect to database via mysql-c          *
   ********************************************/
  mysql_query(&mysql, "CREATE DATABASE TEST_DB_1");
  if (mysql_query(&mysql, "USE TEST_DB_1") != 0) MYSQLERROR(mysql);
  create_table(mysql);

  Ndb* myNdb = new Ndb( cluster_connection,
			"TEST_DB_1" );  // Object representing the database

  NdbTransaction*  myNdbTransaction[2];   // For transactions
  NdbOperation*   myNdbOperation;       // For operations
  
  if (myNdb->init(2) == -1) {          // Want two parallel insert transactions
    APIERROR(myNdb->getNdbError());
    exit(-1);
  }

  /******************************************************
   * Insert (we do two insert transactions in parallel) *
   ******************************************************/
  const NdbDictionary::Dictionary* myDict= myNdb->getDictionary();
  const NdbDictionary::Table *myTable= myDict->getTable("MYTABLENAME");
  if (myTable == NULL)
    APIERROR(myDict->getNdbError());
  for (int i = 0; i < 2; i++) {
    myNdbTransaction[i] = myNdb->startTransaction();
    if (myNdbTransaction[i] == NULL) APIERROR(myNdb->getNdbError());
    
    myNdbOperation = myNdbTransaction[i]->getNdbOperation(myTable);
    if (myNdbOperation == NULL) APIERROR(myNdbTransaction[i]->getNdbError());
    
    myNdbOperation->insertTuple();
    myNdbOperation->equal("ATTR1", 20 + i);
    myNdbOperation->setValue("ATTR2", 20 + i);
    
    // Prepare transaction (the transaction is NOT yet sent to NDB)
    myNdbTransaction[i]->executeAsynchPrepare(NdbTransaction::Commit,
					      &callback, NULL);
  }

  // Send all transactions to NDB 
  myNdb->sendPreparedTransactions(0);
  
  // Poll all transactions
  myNdb->pollNdb(3000, 2);
  
  // Close all transactions
  for (int i = 0; i < 2; i++) 
    myNdb->closeTransaction(myNdbTransaction[i]);

  delete myNdb;
  delete cluster_connection;

  drop_table(mysql);

  ndb_end(0);
  return 0;
}
Beispiel #13
0
int main (int argc, char *argv[])
{
        if (argc < 2){
                printf("a.out sql\n");
        }


        MYSQL conn;
        mysql_init(&conn);

        if (! mysql_real_connect(&conn, "192.168.49.189", "admin","admin","obtest", 2880, NULL, 0))
        {
                printf("Connection failed\n");
                return -1;
        }

        char error_info[1024] = {0};
        MYSQL_RES* result = 0;

        struct timeval t0,t1,t2;
        gettimeofday(&t0, 0);

        if (mysql_query(&conn, argv[1])){
                strncpy(error_info,mysql_error(&conn),1024);
                printf(error_info);
                mysql_close(&conn);
                return-1;
        }

        result = mysql_store_result(&conn);
        if (result == 0){
                strncpy(error_info,mysql_error(&conn),1024);
                printf(error_info);
                mysql_close(&conn);
                return -1;
        }

        int num_fields = mysql_num_fields(result);
        MYSQL_ROW row;
        gettimeofday(&t1, 0);

        while((row = mysql_fetch_row(result))) 
        {
                unsigned long *lengths = NULL;
                int i;
                for(i = 0; i < num_fields; i++)
                {
                        printf("%s\t",row[i]?row[i]:"NULL");
                }
                printf("\n");
        }
        gettimeofday(&t2, 0);

        mysql_free_result(result);
        mysql_close(&conn);

        long long diff = t1.tv_sec - t0.tv_sec;
        diff = diff * 1000000 + (t1.tv_usec - t0.tv_usec);
        printf("query takes time %llu\n", diff);
        diff = t2.tv_sec - t0.tv_sec;
        diff = diff * 1000000 + (t2.tv_usec - t0.tv_usec);

        printf("query and output take time %llu\n", diff);
        return 0;
}
Beispiel #14
0
/*
 * connection,err = DBD.MySQl.New(dbname, user, password, host, port)
 */
static int connection_new(lua_State *L) {
    int n = lua_gettop(L);

    connection_t *conn = NULL;

    const char *host = NULL;
    const char *user = NULL;
    const char *password = NULL;
    const char *db = NULL;
    const char *charset = NULL;
    int port = 0;

    const char *unix_socket = NULL; /* TODO always NULL */
    int client_flag = 0; /* TODO always 0, set flags from options table */

    /* db, user, password, host, port */
    switch (n) {
    case 6:
    if (lua_isnil(L, 6) == 0) 
        charset = luaL_checkstring(L, 6);
    case 5:
	if (lua_isnil(L, 5) == 0) 
	    port = luaL_checkint(L, 5);
    case 4: 
	if (lua_isnil(L, 4) == 0) 
	    host = luaL_checkstring(L, 4);
    case 3:
	if (lua_isnil(L, 3) == 0) 
	    password = luaL_checkstring(L, 3);
    case 2:
	if (lua_isnil(L, 2) == 0) 
	    user = luaL_checkstring(L, 2);
    case 1:
	/*
	 * db is the only mandatory parameter
	 */
	db = luaL_checkstring(L, 1);
    }

    conn = (connection_t *)lua_newuserdata(L, sizeof(connection_t));

    conn->mysql = mysql_init(NULL);

    /*
     * Indicate connection charset, must befor mysql_real_connect calling.
     */
    mysql_options(conn->mysql, MYSQL_SET_CHARSET_NAME, charset);

    if (!mysql_real_connect(conn->mysql, host, user, password, db, port, unix_socket, client_flag)) {
	lua_pushnil(L);
	lua_pushfstring(L, DBI_ERR_CONNECTION_FAILED, mysql_error(conn->mysql));
	return 2;
    }

    /*
     * by default turn off autocommit
     */
    mysql_autocommit(conn->mysql, 0);

    luaL_getmetatable(L, DBD_MYSQL_CONNECTION);
    lua_setmetatable(L, -2);

    return 1;
}
Beispiel #15
0
/** \brief Personendaten anhand der SID und E-mail abrufen
 *
 * \param pers person*  Person mit E-mail und SID in der die restlichen Daten gespeichert werden
 * \return bool         true: Person gefunden; false: Person nicht gefunden
 *
 */
bool get_person_by_sid(person * pers){
	char * query=NULL;
	MYSQL * my=NULL;
	bool found=false;

	if(asprintf(&query, "SELECT * FROM Benutzer WHERE sid='%d' AND email='%s'", pers->sid, pers->email) == -1){
		print_exit_failure("Es konnte kein Speicher angefordert werden (get_person_by_sid)");
	}

	my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure!");
	}

	if(mysql_real_connect(my, "localhost", SQL_USER, SQL_PASS, SQL_BASE, 0, NULL, 0) == NULL){
		print_exit_failure("MYSQL-connection error!");
	}

	if(mysql_query(my, query)){
		print_exit_failure("mysql_query failed (get_person_by_sid)");
		#ifdef DEBUG
		fprintf(stderr, "sql_query:\n%s\nfailed\n", query);
		#endif // DEBUG
	}else{
		MYSQL_RES * result=NULL;
		result = mysql_store_result(my);

		if(mysql_num_rows(result) > 0){
			#ifdef DEBUG
			fprintf(stderr, "uid gefunden\n");
			#endif // DEBUG

			MYSQL_ROW row;
			row=mysql_fetch_row(result);

			//Name holen
			pers->name=calloc(strlen(row[COL_NAME])+1, sizeof(char));
			strcpy(pers->name, row[COL_NAME]);
			pers->first_name=calloc(strlen(row[COL_VORNAME])+1, sizeof(char));
			strcpy(pers->first_name, row[COL_VORNAME]);

			//Kürzel (falls vorhanden) holen
			if(row[COL_ACR] != NULL){
				//Die Person hat ein Küzel --> Lehrer
				pers->acronym=calloc(strlen(row[COL_ACR])+1, sizeof(char));
				strcpy(pers->acronym, row[COL_ACR]);
				pers->isTeacher=true;
			}else{
				pers->isTeacher=false;
			}

			//Kurse (falls vorhanden)
			if(row[COL_COURSE] != NULL){
				pers->courses=calloc(strlen(row[COL_COURSE])+1, sizeof(char));
				strcpy(pers->courses, row[COL_COURSE]);
			}

			//ID holen
			if(row[COL_ID] != NULL){
				pers->id=atoi(row[COL_ID]);
			}

			found=true;
		}
		mysql_free_result(result);
	}

    mysql_close(my);
    free(query);
    return found;
}
Beispiel #16
0
int main(int argc, char**argv)
{
  if (argc != 3)
  {
    std::cout << "Arguments are <socket mysqld> <connect_string cluster>.\n";
    exit(-1);
  }
  char *mysqld_sock  = argv[1];
  const char *connectstring = argv[2];
  ndb_init();
  MYSQL mysql;

  /* Connect to mysql server and create table. */
  {
    if ( !mysql_init(&mysql) ) {
      std::cout << "mysql_init failed.\n";
      exit(-1);
    }
    if ( !mysql_real_connect(&mysql, "localhost", "root", "", "",
                             0, mysqld_sock, 0) )
      MYSQLERROR(mysql);

    mysql_query(&mysql, "CREATE DATABASE ndb_examples");
    if (mysql_query(&mysql, "USE ndb_examples") != 0)
      MYSQLERROR(mysql);

    create_table(mysql);
  }

  /* Connect to ndb cluster. */

  Ndb_cluster_connection cluster_connection(connectstring);
  if (cluster_connection.connect(4, 5, 1))
  {
    std::cout << "Unable to connect to cluster within 30 secs." << std::endl;
    exit(-1);
  }
  /* Optionally connect and wait for the storage nodes (ndbd's). */
  if (cluster_connection.wait_until_ready(30,0) < 0)
  {
    std::cout << "Cluster was not ready within 30 secs.\n";
    exit(-1);
  }

  Ndb myNdb(&cluster_connection,"ndb_examples");
  if (myNdb.init(1024) == -1) {      // Set max 1024 parallel transactions
    APIERROR(myNdb.getNdbError());
    exit(-1);
  }

  setup_records(&myNdb);

  if(populate(&myNdb) > 0)
    std::cout << "populate: Success!" << std::endl;

  if(update_key(&myNdb) > 0)
    std::cout << "update_key: Success!" << std::endl;

  if(update_scan(&myNdb) > 0)
    std::cout << "update_scan: Success!" << std::endl;

  if(fetch_key(&myNdb) > 0)
    std::cout << "fetch_key: Success!" << std::endl;

  if(update2_key(&myNdb) > 0)
    std::cout << "update2_key: Success!" << std::endl;

  if(delete_key(&myNdb) > 0)
    std::cout << "delete_key: Success!" << std::endl;

  return 0;
}
Beispiel #17
0
MySQLDao::MySQLDao()
{
    mysql_init(&(this->conn));//初始化数据库连接
}
Beispiel #18
0
int get_help( struct helps * h, int mode, int start, int num ){

	MYSQL s;
	MYSQL_RES *res;
	MYSQL_ROW row;
	int i;
	char sql[600];
	char tmp[200];

	mysql_init(&s);

	if( !my_connect_mysql(&s) ){
		clear();
		prints("%s\n", mysql_error(&s));
		pressanykey();
		return -1;
	}

	sprintf(sql,"SELECT * FROM help WHERE modeid=%d",mode);

	if( help_search[0] ){
		char newsearch[50];
		mysql_escape_string( newsearch, help_search, strlen(help_search) );
		snprintf(tmp, 199, " And ( content LIKE \"%%%s%%\" OR func LIKE \"%%%s%%\") ", newsearch, newsearch);
		strcat(sql, tmp);
	}

	snprintf(tmp, 99, " ORDER BY prekey LIMIT %d,%d", start, num);
	strcat(sql, tmp);

	if( mysql_real_query(&s, sql, strlen(sql)) ){
		clear();
		prints("%s\n", mysql_error(&s));
		pressanykey();
		mysql_close(&s);
		return -1;
	}
	res = mysql_store_result(&s);
	row = mysql_fetch_row(res);

	i=0;
	while( row != NULL ){
		i++;
		if( i>num)
			break;
		h[i-1].id = atoi(row[0]);
		h[i-1].modeid = mode;
		strncpy(h[i-1].index, row[2], 10);
		h[i-1].index[10]=0;
		strncpy(h[i-1].desc, row[3], 40);
		h[i-1].desc[40]=0;
		if( row[4] && strlen(row[4]) > 0){
			h[i-1].content=(char *)malloc(strlen(row[4])+1);
			if( h[i-1].content)
				strcpy(h[i-1].content, row[4] );
		}
		row=mysql_fetch_row(res);
	}
	mysql_free_result(res);
	mysql_close(&s);

	return i;
}
//-------------------------------------------------------------------------------------
bool DBInterfaceMysql::attach(const char* databaseName)
{
	if(!_g_installedWatcher)
	{
		initializeWatcher();
	}

	if(db_port_ == 0)
		db_port_ = 3306;
	
	if(databaseName != NULL)
		kbe_snprintf(db_name_, MAX_BUF, "%s", databaseName);

	hasLostConnection_ = false;

	try
	{
		pMysql_ = mysql_init(0);
		if(pMysql_ == NULL)
		{
			ERROR_MSG("DBInterfaceMysql::attach: mysql_init is error!\n");
			return false;
		}
		
		DEBUG_MSG(fmt::format("DBInterfaceMysql::attach: connect: {}:{} starting...\n", db_ip_, db_port_));

		int ntry = 0;

__RECONNECT:
		if(mysql_real_connect(mysql(), db_ip_, db_username_, 
    		db_password_, db_name_, db_port_, NULL, 0)) // CLIENT_MULTI_STATEMENTS  
		{
			if(mysql_select_db(mysql(), db_name_) != 0)
			{
				ERROR_MSG(fmt::format("DBInterfaceMysql::attach: Could not set active db[{}]\n",
					db_name_));

				detach();
				return false;
			}
		}
		else
		{
			if (mysql_errno(pMysql_) == 1049 && ntry++ == 0)
			{
				if (mysql())
				{
					::mysql_close(mysql());
					pMysql_ = NULL;
				}

				pMysql_ = mysql_init(0);
				if (pMysql_ == NULL)
				{
					ERROR_MSG("DBInterfaceMysql::attach: mysql_init is error!\n");
					return false;
				}

				if (mysql_real_connect(mysql(), db_ip_, db_username_,
					db_password_, NULL, db_port_, NULL, 0)) // CLIENT_MULTI_STATEMENTS  
				{
					this->createDatabaseIfNotExist();
					if (mysql_select_db(mysql(), db_name_) != 0)
					{
						goto __RECONNECT;
					}
				}
				else
				{
					goto __RECONNECT;
				}
			}
			else
			{
				ERROR_MSG(fmt::format("DBInterfaceMysql::attach: mysql_errno={}, mysql_error={}\n",
					mysql_errno(pMysql_), mysql_error(pMysql_)));

				detach();
				return false;
			}
		}

		if (mysql_set_character_set(mysql(), "utf8") != 0)
		{
			ERROR_MSG("DBInterfaceMysql::attach: Could not set client connection character set to UTF-8\n" );
			return false;
		}

		// 不需要关闭自动提交,底层会START TRANSACTION之后再COMMIT
		// mysql_autocommit(mysql(), 0);

		char characterset_sql[MAX_BUF];
		kbe_snprintf(characterset_sql, MAX_BUF, "ALTER DATABASE CHARACTER SET %s COLLATE %s", 
			characterSet_.c_str(), collation_.c_str());

		query(&characterset_sql[0], strlen(characterset_sql), false);
	}
	catch (std::exception& e)
	{
		ERROR_MSG(fmt::format("DBInterfaceMysql::attach: {}\n", e.what()));
		hasLostConnection_ = true;
		detach();
		return false;
	}

	bool ret = mysql() != NULL && ping();

	if(ret)
	{
		DEBUG_MSG(fmt::format("DBInterfaceMysql::attach: successfully! addr: {}:{}\n", db_ip_, db_port_));
	}

    return ret;
}
Beispiel #20
0
int main(int argc, char* argv[])
{
    if(argc < 4)
    {
        printf("Usage:%s etc_fn server_id log_fn\n", argv[0]);
        return -1;
    }

    //命令行参数,依次为: 配置文件路径,server_id,日志文件路径名
    const char* pszEtcFn = argv[1];
    uint16_t nServerId = SERVER_LOG;
    const char* pszLogPath = argv[3];

    signal(SIGPIPE, SIG_IGN);
	//curl_global_init(CURL_GLOBAL_ALL);
    CDebug::Init();
    InitLib();

    //printf("%d\n", mysql_thread_safe() );
    {
        MYSQL* dummy = mysql_init(NULL);
        mysql_close(dummy);
    }

    g_logger_mutex = new pthread_mutex_t;

    if(!g_pluto_recvlist.InitMutex() || !g_pluto_sendlist.InitMutex() || !g_worldOther.InitMutex()
        || pthread_mutex_init(g_logger_mutex, NULL) != 0 )
    {
        printf("pthead_mutext_t init error:%d,%s\n", errno, strerror(errno));
        return -1;
    }

    g_logger.SetLogPath(pszLogPath);
    CWorldOther& world = g_worldOther;
    int nRet = world.init(pszEtcFn);
    if(nRet != 0)
    {
        printf("CWorldLog init error:%d\n", nRet);
        return nRet;
    }

    COtherServer s;
    s.SetMailboxId(nServerId);
    s.SetWorld(&world);
    world.SetServer(&s);

    vector<pthread_t> pid_list;

	int ret = create_threads(pid_list);
	if ( 0 != ret)
	{
		return ret;
	}
	
    signal(SIGALRM, SigHandler);

    uint16_t unPort = world.GetServerPort(nServerId);
	////初始化线程池以及相关的多线程的检查
	//InitThreadPool();
    
	s.Service("", unPort);

	//处理完了所有的包后再关闭线程池
	//DestroyThreadPool();

	for(size_t i = 0; i < pid_list.size(); ++i)
    {
        if(pthread_join(pid_list[i], NULL) != 0)
        {           
            return -3;
        }
    }

}
Beispiel #21
0
int insert_data(const struct config *config, queue_t *data)
{
    MYSQL *sql_object, *sql_conn;
    queue_t *ptr;
    station_data_t *station;
    rbfsum_t rs;
    int ret, i, station_id;
    const int timeout = 3;
    char *cmd, *timestamp, *breaks;

    sql_object = mysql_init(NULL);
    if (sql_object == NULL)
        return 255;

    ret = mysql_options(sql_object, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);
    if (ret) {
        mysql_close(sql_object);
        return 3;
    }

    sql_conn = mysql_real_connect(sql_object, config->host, config->username,
                                  config->password, config->database, 
                                  config->port, 0, 0);
    if (sql_conn == NULL) {
        mysql_close(sql_object);
        return 3;
    }

    ptr = data;
    while (ptr) {
        station = ptr->data;
        station_id = get_station_id(station->name);
        if (station_id <= 0 
            || station_info[station_id].state == 0
            || station->ndata != 24) {
            ptr = ptr->next;
            continue;
        }
        for (i = 0; i < 24; i++) {
            rs = station->rs[i];
            timestamp = generate_timestamp(rs.start);
            breaks = rs.breaks ? g_strdup_printf("%i", rs.breaks) : g_strdup("-");
            cmd = g_strdup_printf("INSERT INTO tbldatarbf VALUES(NULL, %i, "
                                  "'%s', '%g', '%g', '%g', '%s')", station_id,
                                  timestamp, rs.data, rs.retx, rs.gap, breaks);
            ret = mysql_query(sql_object, cmd);
            g_free(breaks);
            g_free(cmd);
            g_free(timestamp);
            if (ret) {
                mysql_close(sql_object);
                return 6;
            }
        }

        switch (rbfsum_get_status(station->rs, station->ndata)) {
            case RBFSUM_STATUS_EQUAL:
                ret = 3;
                break;
            case RBFSUM_STATUS_GREATER:
                ret = 2;
                break;
            case RBFSUM_STATUS_LESS:
                ret = 4;
                break;
            case RBFSUM_STATUS_OFF:
                ret = 5;
                break;
            default:
                ret = 1;
        }
        rs = station->rs[0];
        timestamp = generate_timestamp(rs.start);
        cmd = g_strdup_printf("INSERT INTO tblstatus VALUES(NULL, %i, "
                              "'%s', %i)", station_id, timestamp, ret);
        ret = mysql_query(sql_object, cmd);
        g_free(cmd);
        g_free(timestamp);
        if (ret) {
            mysql_close(sql_object);
            return 6;
        }

        ptr = ptr->next;
    }

    mysql_close(sql_object);
    return 0;
}
Beispiel #22
0
/** \brief Überprüfen ob das Passwort einer angemeldeten Person stimmt
 *
 * \param pers person*  Person, mit E-Mail-Adresse und SessionID
 * \return bool         true: Passwort ist richtig; false: Passwort ist falsch
 *
 */
bool verify_user_password(person * pers){
	char * query=NULL;
	bool password_state=false;
	MYSQL * my=NULL;

	if(pers->password == NULL || pers->sid==0){
		print_exit_failure("Programm falsch (verify_user_password)");
	}

	if(asprintf(&query, "SELECT * FROM Benutzer WHERE sid='%d' AND email='%s'", pers->sid, pers->email) == -1){
		print_exit_failure("Es konnte kein Speicher angefordert werden (verify_user_password)");
	}

	my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure (verify_user_password)");
	}

	if(mysql_real_connect(my, "localhost", SQL_USER, SQL_PASS, SQL_BASE, 0, NULL, 0) == NULL){
		print_exit_failure("MYSQL-connection error!");
	}

	if(mysql_query(my, query)){
		print_exit_failure("mysql_query failed (verify_user_password)");
		#ifdef DEBUG
		fprintf(stderr, "sql_query:\n%s\nfailed\n", query);
		#endif // DEBUG
	}else{
		MYSQL_RES * result=NULL;
		result = mysql_store_result(my);

		if(mysql_num_rows(result) == 1){
			MYSQL_ROW * row=NULL;
			row=mysql_fetch_row(result);
			#ifdef DEBUG
			fprintf(stderr, "Benutzer gefunden (verify_user_password)\n");
			#endif // DEBUG
			char * password_encrypted=NULL;
			char * password_db=NULL;
			char * salt=NULL;
			password_db=row[COL_PASS];

			salt=salt_extract(password_db);

			char * arg=NULL;
			asprintf(&arg, "$6$%s$", salt);
			char * encr=crypt(pers->password, arg);
			//free(pers->password);
			asprintf(&password_encrypted, "%s%s", salt, encr+strlen(arg));

			free(salt);
			free(arg);
			free(encr);

			if(strcmp(password_db, password_encrypted) == 0){
				#ifdef DEBUG
				fprintf(stderr, "Passwort war richtig! (Benutzer: %s)", pers->email);
				#endif // DEBUG
				password_state=true;
			}else{
				password_state=false;
			}


		}else{
			pers->auth=false;
		}
		mysql_free_result(result);
	}

    mysql_close(my);
    free(query);

    return password_state;

}
Beispiel #23
0
void *openspy_mod_run(modLoadOptions *options)
{
  int sda,sd;
  socklen_t psz;
  fd_set  rset;
  struct sockaddr_in peer;
  struct sockaddr_in user;
  memset(&peer,0,sizeof(peer));
  int on=1;
  memcpy(&servoptions,options,sizeof(modLoadOptions));
  conn = mysql_init(NULL);
  mysql_options(conn,MYSQL_OPT_RECONNECT, (char *)&on);
  /* Connect to database */
  if (!mysql_real_connect(conn, servoptions.mysql_server,
      servoptions.mysql_user, servoptions.mysql_password, servoptions.mysql_database, 0, NULL, CLIENT_MULTI_RESULTS)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      return NULL;
  }
  peer.sin_port        = htons(LEGACYMSPORT);
  peer.sin_family      = AF_INET;
  peer.sin_addr.s_addr = servoptions.bindIP;
	
  sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))
      < 0) return NULL;
    if(bind(sd, (struct sockaddr *)&peer, sizeof(struct sockaddr_in))
      < 0) return NULL;
    if(listen(sd, SOMAXCONN)
      < 0) return NULL;
    struct timeval timeout;
    memset(&timeout,0,sizeof(struct timeval));
    for(;;) {
	int hsock;
	FD_ZERO(&rset);
	FD_SET(sd, &rset);
	hsock = getnfds(&rset);
	if(hsock < sd) hsock = sd;
	timeout.tv_sec = SB_TIMEOUT_TIME;
	if(select(hsock+1, &rset, NULL, NULL, &timeout)
          < 0) continue;
        if(FD_ISSET(sd, &rset)) {
	} else {
		processClients(&rset);
		continue;
	}
	psz = sizeof(struct sockaddr_in);
        sda = accept(sd, (struct sockaddr *)&user, &psz);
        if(sda <= 0) continue;
	if(!do_db_check()) {
		close(sda);
		continue; //TODO: send database error message
	}
	boost::shared_ptr<Client> c = boost::make_shared<Client>(sda,(struct sockaddr_in *)&user);
	boost::container::stable_vector< boost::shared_ptr<Client> >::iterator iterator=server.client_list.begin();
	boost::container::stable_vector< boost::shared_ptr<Client> >::iterator end=server.client_list.end();
	for(;;) {
		if(iterator == end) { server.client_list.push_back(c); break; }
		else if(!*iterator) { *iterator = c; break; }
		else ++iterator;
	}
    }
}
Beispiel #24
0
/** \brief Nutzer mit Name, (ggf. Kürzel) und Passwort in die DB einfügen
 *
 * \param pers person*  Personen-Struktur
 * \return void
 * Eine Person in die DB einfügen, falls diese noch nicht existiert.
 * Das Passwort wird mithilfe von crypt() verschlüsselt
 */
void insert_user(person * pers){
	MYSQL *my=NULL;
	char * query=NULL;

	if(pers == NULL){
		print_exit_failure("Programm falsch.\n Wörk!");
	}

	if(email_exists(pers->email)){
		print_exit_failure("Benutzer Existiert schon!");
	}

	my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure\n Wörk!");
	}

	if(mysql_real_connect(my, "localhost", SQL_ALTERNATE_USER, SQL_ALTERNATE_PASS, SQL_BASE, 0, NULL, 0) == NULL){
		print_exit_failure("MYSQL-connection error!");
	}

	char * salt=NULL;
	salt_generate(&salt);

    //Verhindern, dass ein bereits vorhandenes Salt zweimal verwendet wird (falls zwei Nutzer identische Passwörter wählen)
	while(salt_exists(&salt)){
		salt_generate(&salt);
	}
	char * arg=NULL;
	asprintf(&arg, "$6$%s$", salt);

	char * encr=crypt(pers->password, arg);
	char * store_pw=NULL;
	asprintf(&store_pw, "%s%s", salt, encr+strlen(arg));
	free(arg);
	free(pers->password);

	//pers->password=encr+strlen(arg);

	clean_string(pers->first_name);
	clean_string(pers->email);
	clean_string(pers->name);


	//Ist es eine Lehrer oder ein Schüler?
	if(!pers->isTeacher){
		if(asprintf(&query, "INSERT INTO Benutzer (vorname, name, email, passwort, kurse) \
					VALUES('%s', '%s', '%s', '%s', 'n/a')",
					pers->first_name, pers->name, pers->email, store_pw) == -1)
		{
			print_exit_failure("Es konnte kein Speicher angefordert werden (insert_user)");
		}
	}else{
		clean_string(pers->acronym);
		if(asprintf(&query, "INSERT INTO Benutzer (vorname, name, email, passwort, kurse, kuerzel) \
					VALUES('%s', '%s', '%s', '%s', 'n/a', '%s')",
					pers->first_name, pers->name, pers->email, store_pw, pers->acronym) == -1)
		{
			print_exit_failure("Es konnte kein Speicher angefordert werden (insert_user)");
		}
	}
	#ifdef DEBUG
	fprintf(stderr, "\nInsert dat:\n%s\n", query);
	#endif // DEBUG
	if(mysql_query(my, query)){
		#ifdef DEBUG
		fprintf(stderr, "sql_query:\n%s\nfailed\n", query);
		#endif // DEBUG
		print_exit_failure("mysql_query failed (insert)");
	}
	free(query);
	mysql_close(my);
}
Beispiel #25
0
int cgiMain() {
#ifdef MYSQL_DB
  static MYSQL *dbh;              /* database connect handle */
  static MYSQL_RES *result;       /* database query results  */
  static MYSQL_ROW values;        /* query data returned     */
  unsigned int colcount    =0;    /* number of returned columns */
  int server_version;             /* returned server version */
#endif
#ifdef ORACLE_DB
  sqlo_db_handle_t dbh;           /* database handle */
  sqlo_stmt_handle_t sth1;        /* statement handle 1 */
  char server_version[1024]="";   /* string for returned server version */
  int stat                 =0;    /* status of sqlo calls */
  int handle               =0;    /* handle of the interrupt handler */
  //const char ** colnames;         /* column names */
  const char ** values;           /* values */
#endif
  char sqlquery_str[1024]  ="";   /* SQL query string */
  int allrows              =0;    /* number of returned rows */
  int rowcount             =0;    /* row iteration counter */
  div_t oddline_calc;             /* calculates even/odd row color */
  int top_count            =0;    /* how many top IP to display */
  char start_date[11]      ="";   /* selected start date */
  char start_time[6]       ="";   /* selected start time */
  char end_date[11]        ="";   /* selected end date */
  char end_time[6]         ="";   /* selected end time */
  char order_by[13]        ="";   /* sort list by column */
  char sort_order[5]       ="";   /* ascending or descending */
  char **form_data;               /* string array for query data */
  char title[256]          = "";  /* cgi title string */
  struct tm *tm_ptr;              /* containing time structure */
  time_t now, old;                /* containing timestamp */
  char err_str[2048]       = "";  /* use for combined error string */
  char dataunit[255] = "0 Bytes"; /* holds the calculated KB/MB */

  _abort_flag     = 0;
#ifdef ORACLE_DB
  /* ------------------------------------------------------------------- * 
   * ORACLE_HOME is needed for OCI8 to find tnsnames.ora                 *
   * ------------------------------------------------------------------- */
  putenv(WEB_ORACLE_ENV);

  /* initialize the connection */
  if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100))
    cgi_error("Error: Failed to init libsqlora8.");

  /* register the interrupt handler */
  sqlo_register_int_handler(&handle, sigint_handler);

  /* login to the database */
  if (SQLO_SUCCESS != sqlo_connect(&dbh, WEB_TNS_STRING))
    cgi_error("Error: Cannot connect to database.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  if (SQLO_SUCCESS != sqlo_server_version(dbh, server_version,
                                        sizeof(server_version)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* enable autocommit, each statement is commited as a single transaction */
  stat = sqlo_set_autocommit(dbh, 1);
#endif
#ifdef MYSQL_DB
  /* initialize the connection */
  dbh = mysql_init(NULL);
  if(dbh == NULL) cgi_error("Error:  Failed to init MySQL DB.");

  /* login to the database */
  if (mysql_real_connect(dbh, MYSQLIP, EDACSADMIN, ADMIN_PASS, DB_NAME, DB_PORT, NULL, 0) == 0)
    cgi_error("Error: Cannot connect to database.");

  /* Get the database version */
  server_version = mysql_get_server_version(dbh);
#endif

  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    cgi_error("Error: Could not retrieve form data.");

  if(form_data[0] == NULL) {
    /* ------------------------------------------------------------------- * 
     * The calculate query start and end time from given period in hours   *
     * ------------------------------------------------------------------- */
    now = time(NULL);
    tm_ptr = localtime(&now);
    strftime(end_date, sizeof(end_date), "%d.%m.%Y", (tm_ptr));
    strftime(end_time, sizeof(end_time), "%H:%M", tm_ptr);
    old = time(NULL) - 7200;
    tm_ptr = localtime(&old);
    strftime(start_date, sizeof(start_date), "%d.%m.%Y", tm_ptr);
    strftime(start_time, sizeof(start_time), "%H:%M", tm_ptr);
  
    /* ------------------------------------------------------------------- * 
     * Start the HTML output to display the query selection                *
     * ------------------------------------------------------------------- */
    /* define the CGI title */
    snprintf(title, sizeof(title), "Top IP Address Session Activity");
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");

    fprintf(cgiOut, "<form action=\"ip-toptime.cgi\" method=\"get\">\n");
    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    /* 1st row, display headers */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">Number of IP</th>");
    fprintf(cgiOut, "<th class=\"inner\">Time Frame</th>");
    fprintf(cgiOut, "<th class=\"inner\">Top by</th>");
    fprintf(cgiOut, "<th class=\"inner\">Sort Order</th>");
    fprintf(cgiOut, "</tr>\n");
    /* 2nd row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">From:</td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 3rd row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><input type=text size=10 name=start_date value=\"%s\">",start_date);
    fprintf(cgiOut, "<input type=text size=5 name=start_time value=\"%s\">",start_time);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"desc\" checked name=\"sort_order\">");
    fprintf(cgiOut, "Top</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 4th row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><select name=\"top_count\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"5\">Top 5 IP</option>");
    fprintf(cgiOut, "<option selected value=\"10\">Top 10 IP</option>");
    fprintf(cgiOut, "<option value=\"20\">Top 20 IP</option>");
    fprintf(cgiOut, "<option value=\"50\">Top 50 IP</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">To:</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><select name=\"order_by\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"elapsed_mins\">Elapsed Time</option>");
    fprintf(cgiOut, "<option value=\"bytes_in\">Bytes In</option>");
    fprintf(cgiOut, "<option selected value=\"bytes_out\">Bytes Out</option>");
    fprintf(cgiOut, "<option value=\"packets_in\">Packets In</option>");
    fprintf(cgiOut, "<option value=\"packets_out\">Packets Out</option>");
    fprintf(cgiOut, "<option value=\"sessions\">Session Count</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio name=\"sort_order\" value=\"asc\">Bottom</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 5th row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><input type=text size=10 name=\"end_date\" value=\"%s\">", end_date);
    fprintf(cgiOut, "<input type=text size=5 name=\"end_time\" value=\"%s\"><br>&nbsp;</td>", end_time);
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 6th and last row, close the frame */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=4><input type=submit value=\"Run Query\"></td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");

    fprintf(cgiOut, "<h3>Additional Information</h3>\n");
    fprintf(cgiOut, "<hr>\n");
    fprintf(cgiOut, "<p>\n");
    fprintf(cgiOut, "This query returns a list of top IP addresses for the selected time period in the \"Order By\" selection.");
    fprintf(cgiOut, " It will give you a quick view who is possibly missusing the service, i.e. transferring large amounts of data in or out.");
    fprintf(cgiOut, "<ul>");
    fprintf(cgiOut, "<li>Select the number of top IP to display (5, 10, 20, 50) from the drop down list.");
    fprintf(cgiOut, "<li>The time frame can be adjusted by typing into it, using the format DD.MM.YYYY HH:MM.");
    fprintf(cgiOut, "<li>The results list is grouped by the \"Order By\" list, and sorted \"Top\" down or \"Bottom\" up.");
    fprintf(cgiOut, "</ul>");
    fprintf(cgiOut, "</p>\n");
  } /* end if for displaying the query request */
  else {
  /* ------------------------------------------------------------------- *
   * check if we got all information to make the SQL query               *
   * --------------------------------------------------------------------*/
    if ( cgiFormIntegerBounded("top_count", &top_count, 1, 50, 10) 
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving IP address top count.");
  
    if ( cgiFormString("start_date", start_date, sizeof(start_date))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving start_date information.");

    if ( cgiFormString("start_time", start_time, sizeof(start_time))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving start_time information.");

    if ( cgiFormString("end_date", end_date, sizeof(end_date))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving end_date information.");

    if ( cgiFormString("end_time", end_time, sizeof(end_time))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving end_time information.");

    if ( cgiFormString("order_by", order_by, sizeof(order_by))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving order_by information.");
  
    if ( cgiFormString("sort_order", sort_order, sizeof(sort_order))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving sort_order information.");
  
    /* ------------------------------------------------------------------- *
     * check we got all parts and can start doing the SQL query below      *
     * --------------------------------------------------------------------*/
#ifdef ORACLE_DB
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT IP_ADDR, TO_CHAR(SUM(BYTES_IN), '999,999,999,999') BYTES_IN, TO_CHAR(SUM(BYTES_OUT), '999,999,999,999') BYTES_OUT, TO_CHAR(SUM(PACKETS_IN), '999,999,999,999') PACKETS_IN, TO_CHAR(SUM(PACKETS_OUT), '999,999,999,999') PACKETS_OUT, TO_CHAR(SUM(ELAPSED_MINS), '99,999.99') ELAPSED_MINS, COUNT (IP_ADDR) AS SESSIONS FROM %s.V_EDACS WHERE BYTES_IN IS NOT NULL AND START_DATE BETWEEN TO_DATE('%s %s', 'dd.mm.yyyy hh24:mi') and TO_DATE ('%s %s', 'dd.mm.yyyy hh24:mi') GROUP BY IP_ADDR ORDER BY %s %s",
           EDACSADMIN, start_date, start_time, end_date,
           end_time, order_by, sort_order);

    /* initialize the statement handle */
    sth1 = SQLO_STH_INIT;
  
    /* opens a cursor for the query statement */
    if ( 0 > (sqlo_open2(&sth1, dbh, sqlquery_str, 0, NULL))) {
      if(DEBUG == 0) cgi_error(sqlo_geterror(dbh));
      else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
               sqlo_geterror(dbh), sqlquery_str);
      cgi_error(err_str);
    }
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
  
    /* get the output column names */
    if (SQLO_SUCCESS != sqlo_ocol_names2(sth1, &colcount, &colnames))
      cgi_error("Error getting the DB columns with sqlo_ocol_names2()");
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT ip_addr, SUM(bytes_in) bytes_in, SUM(bytes_out) bytes_out, TRUNCATE((bytes_in+bytes_out)/SUM(TIME_TO_SEC(elapsed_mins)),2) throughput, FORMAT(SUM(packets_in), 0) packets_in, FORMAT(SUM(packets_out), 0) packets_out, SEC_TO_TIME(SUM(TIME_TO_SEC(elapsed_mins))) elapsed_mins, COUNT(ip_addr) AS SESSIONS FROM v_edacs WHERE bytes_in IS NOT NULL AND start_date BETWEEN STR_TO_DATE('%s %s', '%s') and STR_TO_DATE('%s %s', '%s') GROUP BY ip_addr ORDER BY %s %s",
           start_date, start_time, "%d.%m.%Y %H:%i",
           end_date, end_time, "%d.%m.%Y %H:%i",
           order_by, sort_order);

  /* Prepare and execute the SQL statement */
  if(mysql_query(dbh, sqlquery_str) != 0) {
    if(DEBUG == 0) cgi_error(mysql_error(dbh));
    else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
             mysql_error(dbh), sqlquery_str);
    cgi_error(err_str);
  }
 /* get query results set */
  result = mysql_store_result(dbh);
  if (result == NULL) {
    snprintf(err_str, sizeof(err_str), "No results for query: %s\n", sqlquery_str);
    cgi_error( err_str);
  }


  allrows = mysql_num_rows(result);
  colcount = mysql_num_fields(result);
#endif

  /* ------------------------------------------------------------------------ *
   * start the html output                                                    *
   * -------------------------------------------------------------------------*/
    snprintf(title, sizeof(title), "Top %d IP Activity for %s", top_count, order_by);
  
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");
    fprintf(cgiOut, "<p>\n");
    fprintf(cgiOut, "<b>Top:</b> %d <b>Selection:</b> %s <b>Timeperiod:</b> %s %s - %s %s <b>Data Records:</b> %d",
               top_count, order_by, start_date, start_time, end_date, end_time, allrows);
    fprintf(cgiOut, "</p>\n");
  
    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">#</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">IP Address</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Data In</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Data Out</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Throughput</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Packets In</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Packets Out</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Elapsed Time</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Sessions</th>\n");
    fprintf(cgiOut, "</tr>\n");
  
    /* fetch the data */
#ifdef ORACLE_DB
    while ( SQLO_SUCCESS == (stat = (sqlo_fetch(sth1, 1)))) {
       /* get one record */
       values = sqlo_values(sth1, NULL, 1);
#endif
#ifdef MYSQL_DB
    while((values = mysql_fetch_row(result)) != NULL) {
#endif
     rowcount++;

     /* check for even/odd rows */
     oddline_calc = div(rowcount, 2);
     if(oddline_calc.rem) fprintf(cgiOut, "<tr class=\"odd\">\n");
     else fprintf(cgiOut, "<tr class=\"even\">\n");

     fprintf(cgiOut, "<td>%d</td>\n", rowcount);
     fprintf(cgiOut, "<td>");
     fprintf(cgiOut, "<a href=ip-acttime.cgi?start_date=%s&start_time=%s&end_date=%s&end_time=%s&sort_order=%s&ipaddr=%s&order_by=start_date>",
                     start_date, start_time, end_date, end_time, sort_order, values[0]);
     fprintf(cgiOut, "%s</a></td>", values[0]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", calc_units(values[1], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s</td>", calc_units(values[2], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s/s</td>", calc_units(values[3], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[4]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[5]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[6]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[7]);
     fprintf(cgiOut, "</tr>\n");

     if ( rowcount == top_count) break;
   } /* end while row */
#ifdef ORACLE_DB
    if (SQLO_SUCCESS != sqlo_close(sth1))
      cgi_error("Error Closing the SQL statment handle.");
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
 #endif
#ifdef MYSQL_DB
   mysql_close(dbh);
#endif

   /* ----------------------------------------------------------------- *
    * IF there was no data for the selection, display a notification    *
    * ----------------------------------------------------------------- */
    if(rowcount == 0) {
      fprintf(cgiOut, "<tr>\n");
      fprintf(cgiOut, "<td colspan=9>");
      fprintf(cgiOut, "No data found for top %d IP by %s between %s %s and %s %s.",
              top_count, order_by, start_date, start_time, end_date, end_time);
      fprintf(cgiOut, "</td>\n");
      fprintf(cgiOut, "</tr>\n");
    } /* end if rowcount is zero */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=9>");
    fprintf(cgiOut, "&nbsp;");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
  } /* end else we were called with form data */

  pageside();
  pagefoot();
  return(0);
}
Beispiel #26
0
int get_messages(message ** mes, int offset, char * select_course){

	char * query=NULL;
	int num=0;
	MYSQL * my=NULL;

	if(select_course){
		if(asprintf(&query, "SELECT * FROM Meldungen WHERE kurse REGEXP '(^|, )%s($|, )'  ORDER BY erstellt DESC LIMIT %d OFFSET %d", select_course, GET_MESSAGE_COUNT,(offset*GET_MESSAGE_COUNT)) == -1){
			print_exit_failure("Es konnte kein Speicher angefordert werden (get_all_messages)");
		}
	}else{
		if(asprintf(&query, "SELECT * FROM Meldungen WHERE kurse='all' ORDER BY erstellt DESC LIMIT %d OFFSET %d", GET_MESSAGE_COUNT,(offset*GET_MESSAGE_COUNT)) == -1){
			print_exit_failure("Es konnte kein Speicher angefordert werden (get_all_messages)");
		}
	}

	my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure!");
	}

	if(mysql_real_connect(my, "localhost", SQL_USER, SQL_PASS, SQL_BASE, 0, NULL, 0) == NULL){
		print_exit_failure("MYSQL-connection error!");
	}

	if(mysql_query(my, query)){
		print_exit_failure("mysql_query failed (get_messages)");
		#ifdef DEBUG
		fprintf(stderr, "sql_query:\n%s\nfailed\n", query);
		#endif // DEBUG
	}else{
		MYSQL_RES * result=NULL;
		result = mysql_store_result(my);
		num=mysql_num_rows(result);
		if(mysql_num_rows(result) > 0){
			*mes = calloc(mysql_num_rows(result), sizeof(message));
			MYSQL_ROW message_row;
			for(my_ulonglong i=0; i<mysql_num_rows(result) && (message_row=mysql_fetch_row(result)); i++){
				(*mes+i)->id=atoi(message_row[COL_MESSAGE_ID]);

				//(*mes+i)->title=calloc(strlen(message_row[COL_MESSAGE_TITEL])+1, sizeof(char));
				//strcpy((*mes+i)->title, message_row[COL_MESSAGE_TITEL]);
				asprintf(&(*mes+i)->title, "%s", message_row[COL_MESSAGE_TITEL]);

				//TODO: nur den ersten Satz / die ersten n Zeichen ausgeben oder bis zum ersten <br> ???
				//(*mes+i)->message=calloc(strlen(message_row[COL_MESSAGE_MES])+1, sizeof(char));
				//strcpy((*mes+i)->message, message_row[COL_MESSAGE_MES]);
				asprintf(&(*mes+i)->message, "%s", message_row[COL_MESSAGE_MES]);

				//(*mes+i)->courses=calloc(strlen(message_row[COL_MESSAGE_COURSES])+1, sizeof(char));
				//strcpy((*mes+i)->courses, message_row[COL_MESSAGE_COURSES]);
				asprintf(&(*mes+i)->courses, "%s", message_row[COL_MESSAGE_COURSES]);

				(*mes+i)->creator_id=atoi(message_row[COL_MESSAGE_CREATORID] ? message_row[COL_MESSAGE_CREATORID] : "-1");

				//(*mes+i)->s_created=calloc(strlen(message_row[COL_MESSAGE_TIME_CREATED])+1, sizeof(char));
				//strcpy((*mes+i)->s_created, message_row[COL_MESSAGE_TIME_CREATED]);
				asprintf(&(*mes+i)->s_created, "%s", message_row[COL_MESSAGE_TIME_CREATED]);

            }
		}
		mysql_free_result(result);
	}
	mysql_close(my);

	free(query);
	return num;
}
int main() {
/// 例子1
    puts("测试1...(链接)");
    //MYSQL句柄   (任何一个mysql操作都是基于MYSQL这个句柄来操作的)
    MYSQL* link_ = mysql_init(NULL);             //初始化MYSQL句柄
	//设置超时时间(链接超时时间,查询超时时间,写数据库超时时间)
    int  timeout =  3;                      //超时时间设置为3秒
    if(link_ != NULL) {
        mysql_options(link_,MYSQL_OPT_CONNECT_TIMEOUT,(const char *)&timeout);
        //设置链接超时时间.
        mysql_options(link_,MYSQL_OPT_READ_TIMEOUT,(const char *)&timeout);
        //设置查询数据库(select)超时时间
        mysql_options(link_,MYSQL_OPT_WRITE_TIMEOUT,(const char *)&timeout);
        //设置写数据库(update,delect,insert,replace等)的超时时间。
    }
	//真正建立mysql链接
    char  host_name[1024] = "localhost";		//mysql服务器的IP
    char  user_name[1024] = "root";				//用户名
    char  user_password[1024] = "123456";		///密码		需要改为自己的密码
    char  server_name[1024] = "test";			///数据库名	需要改为自己的数据库名
    unsigned short host_port = 3306;			//服务器端口

    if(!mysql_real_connect(link_,host_name,user_name,user_password,server_name,host_port,NULL,0)) {
        //失败处理
        int error_code  =  mysql_errno(link_);            //获取错误码
        //针对不同的错误码error_code,还应该做不同的处理
        mysql_close(link_);                           //释放句柄
    	printf("链接建立失败! :%s\n",mysql_error(link_));
    }else {
    	puts("链接建立成功");
        //链接建立成功,可以进行具体的操作(select   insert    delete   update  replace等)
    }
/// 下面是第二个例子,可以和上面一个例子分开运行
    puts("\n测试2...(链接并查询)");
    char SqlText[256] = "";
    MYSQL mysql;
    MYSQL_RES *res = NULL;
    MYSQL_FIELD * fd = NULL;
    MYSQL_ROW row;
    int i = 0;

    mysql_init( &mysql );

    if ( !mysql_real_connect( &mysql, "localhost", "root",
                              "123456", "test", 3306, NULL, 0) ) {
        puts("数据库连接失败");
        printf( "Error connecting to database: %s\n",mysql_error(&mysql));
        mysql_close( &mysql );
        return FALSE;
    } else {
        puts("数据库连接成功");
        mysql_query(&mysql,"set names 'GBK'");//设置字符集,防止中文无法正常显示
        sprintf( SqlText, "insert into animals(name, kg) values ('chicken',6), ('dog', 4)");
        if ( !mysql_query(&mysql, SqlText ) ) {        //insert失败
            printf("Can't insert data to table: ");
            printf("%s\n", mysql_error(&mysql));
            mysql_close( &mysql );
            return FALSE;
        }
        sprintf( SqlText, "select * from %s","stu");	///stu需要改为自己的数据库中对应的表名
        //进行数据检索
        if ( !mysql_query(&mysql, SqlText )) {
            res = mysql_store_result( &mysql );
            i = (int)mysql_num_rows( res );
            printf("Query: %s\n%d records found:\n", SqlText, i );
            //输出各字段名
            for (; fd = mysql_fetch_field(res);)
                printf("%-*s\t",50/mysql_num_fields(res), fd->name );
            puts("");

            //打印获取的数据
            MYSQL_ROW row; //一个行数据的类型安全(type-safe)的表示
            while (row = mysql_fetch_row(res)) {    //获取下一行
                for(int i=0; i<mysql_num_fields(res); i++)
                    printf("%-*s",80/mysql_num_fields(res),row[i]);
                puts("");
            }
            mysql_free_result( res );
        } else {
        	printf("查询失败: %s\n",mysql_error(&mysql));
        	puts("请更改66行表名");
            mysql_close( &mysql );
            return FALSE;
        }
    }
    mysql_close(&mysql);
    getchar();
    return TRUE;
}
Beispiel #28
0
/** \brief Überprüfen, ob eine Person in der Datenbank ist und ob das Passwort stimmt
 *
 * \param pers person*  Person, die angemeldet werden soll
 * \return int          1: Benutzer ist schon angemeldet; 0: Benutzer war noch nicht angemeldet (PW richtig); -1: PW falsch
 *  Die Funktion testet, ob der Name oder das Kürzel (je nachdem was eingegeben wurde)
 *  (Erkennung an der Länge des Strings: =3 --> Kürzel, >3 --> Name)
 *  in der DB vorhanden ist. Wenn der Name existiert wird geprüft ob das Passwort richtig ist.
 *  Wenn das Passwort stimmt wird der bool-Wert "auth" in "person" auf true gesetzt.
 *  --> die Person ist authentifiziert.
 */
int verify_user(person * pers){
	bool isAcronym;
	UserState user_state=PW_INCORRECT;

	if(pers->email==NULL || pers->password==NULL){
		print_exit_failure("Programm falsch!");
	}

	isAcronym=detect_convert_acronym(pers);

	MYSQL *my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure");
	}

	if(mysql_real_connect(my, "localhost", SQL_USER, SQL_PASS, SQL_BASE, 0, NULL, 0) == NULL){

		print_exit_failure("MYSQL-connection error!");
	}else{
		//fprintf(stderr, "Connection extablished!\n");
	}

	MYSQL_RES * result=NULL;
	bool found=false;

	if(isAcronym){
		//Es ist sicher eine Lehrer (jemand hat das Kürzel eingegeben)
		//TODO: sql-injection verhindern

		char * sql_query=NULL;
		if(asprintf(&sql_query, "SELECT  * FROM Benutzer WHERE kuerzel='%s'", pers->acronym) == -1){
			print_exit_failure("Es konnte kein Speicher angefordert werden (verify_user)");
		}
		#ifdef DEBUG
		fprintf(stderr, "Lehrer.\nsql_query: %s\n", sql_query);
		#endif // DEBUG

		if(mysql_query(my, sql_query)){  //Liefert 0 bei Erfolg
			print_exit_failure("mysql_query failed (Lehrer)");
		}

		result = mysql_store_result(my);

		if(mysql_num_rows(result) == 1){
			found=true;
			isAcronym=true; //Da wir jetzt eine Person mit Kürzel gefunden haben
			pers->isTeacher=true;
		}
		free(sql_query);
    }else{
		//Es könnte ein Lehrer oder ein Schüler sein

		char * sql_query=NULL;
		if(asprintf(&sql_query, "SELECT * FROM Benutzer WHERE email='%s'", pers->email) == -1){
			print_exit_failure("Es konnte kein Speicher angefordert werden (verify_user)");
		}
		#ifdef DEBUG
		fprintf(stderr, "Schueler o. Lehrer.\nsql_query: %s\n", sql_query);
		#endif // DEBUG

		if(mysql_query(my, sql_query)){  // Liefert 0 bei Erfolg
			print_exit_failure("mysql_query failed (Schueler - Lehrer)");
		}

		result = mysql_store_result(my);

		if(mysql_num_rows(result) == 1){
			found=true;
			isAcronym=false; //Da wir jetzt eine Person mit Kürzel gefunden haben
		}else{
			//Person nicht vorhanden, oder Fehler
			//print_exit_failure("mysql: Person nicht vorhanden, oder Passwort falsch."); //Was auch immer
			found=false;
			isAcronym=false;
		}
		free(sql_query);
    }

	//Ab hier wurde die SQL-Query für Lehrer oder Schüler ausgeführt.
	if(found == true){
		MYSQL_ROW row;
		row=mysql_fetch_row(result);
		#ifdef DEBUG
		fprintf(stderr, "\nEin Ergebnis!\n Name: %s, Pass: %s, SID: '%s'\n", row[COL_NAME], row[COL_PASS], row[COL_SID]);
		#endif // DEBUG

		//Auslesen des Salt
		char * salt=calloc(SALT_LENGTH+1, sizeof(char));
		//strncat(salt, row[COL_PASS], 1);
		//strncat(salt, row[COL_PASS]+1, 1);
		for(int i=0; i<SALT_LENGTH; i++){
			strncat(salt, row[COL_PASS]+i, 1);
		}
		char * arg=NULL;
		asprintf(&arg, "$6$%s$", salt);
		char * encr=crypt(pers->password, arg);
		free(pers->password);
		char * load_pw=NULL;
		asprintf(&load_pw, "%s%s", salt, encr+strlen(arg));
		//pers->password=encr+strlen(arg);

		if(strcmp(load_pw, row[COL_PASS]) == 0){
			pers->auth=true;

			//Name holen
			//pers->name=calloc(strlen(row[COL_NAME])+1, sizeof(char));
			//strcpy(pers->name, row[COL_NAME]);
			asprintf(&pers->name, "%s", row[COL_NAME]);
			//pers->first_name=calloc(strlen(row[COL_VORNAME])+1, sizeof(char));
			//strcpy(pers->first_name, row[COL_VORNAME]);
			asprintf(&pers->first_name, "%s", row[COL_VORNAME]);

			if(isAcronym){
				//Person hat Kürzel angegeben --> es ist eine Leherer --> email holen holen
				pers->email=calloc(strlen(row[COL_EMAIL])+1, sizeof(char));
				strcpy(pers->email, row[COL_EMAIL]);
			}else{
				//Person hat ihre Email-Adresse statt dem Kürzel angegeben --> (Falls es ein Lehrer ist, dessen Kürzel holen)
				pers->acronym=NULL;
				if(row[COL_ACR] != NULL){
					//Die Person hat ein Küzel --> Lehrer
					pers->acronym=calloc(strlen(row[COL_ACR])+1, sizeof(char));
					strcpy(pers->acronym, row[COL_ACR]);
					pers->isTeacher=true;
				}else{
					pers->isTeacher=false;
				}
			}

			//Kurse (falls vorhanden)
			if(row[COL_COURSE] != NULL){
				pers->courses=calloc(strlen(row[COL_COURSE])+1, sizeof(char));
				strcpy(pers->courses, row[COL_COURSE]);
			}

			//ID holen
			if(row[COL_ID] != NULL){
				pers->id=atoi(row[COL_ID]);
			}

			if(row[COL_SID] != NULL){
				//Benutzer ist schon angemeldet
				user_state=PW_CORRECT_ALREADY_LOGGED_IN;
				pers->auth=true;
				pers->sid=atoi(row[COL_SID]);
			}else{
				user_state=PW_CORRECT;
				create_session(pers);
			}
		}else{
			user_state=PW_INCORRECT;
			pers->auth=false;
			pers->sid=0;
		}
	}

	mysql_free_result(result);
	mysql_close(my);

	return user_state;
}
Beispiel #29
0
int main(int argc, char** argv) {
  int ret = 0;
  gchar domain[80];
  gchar *result = NULL;
  gchar* ret_char = NULL;
  gchar buf[64];

  gchar *username = NULL;
  gchar *password = NULL;
  gchar xmpp_server[80];
  gchar *xmpp_ssl_fingerprint = "blah";
  gchar pubsub_server[80];
  int xmpp_server_port = 5223;
  char *db_username = NULL;
  char *db_password = NULL;
  char *db_name = NULL;
  char *db_server = NULL;
  int db_server_port = 3306;
  int unsubscribe;
  GSList *node_list = NULL;
  gchar* event_node_file_str = NULL;
  FILE* event_node_file = NULL;

  int current_arg_num = 1;
  gchar *current_arg_name = NULL;
  gchar *current_arg_val = NULL;
  GMainLoop *main_loop = NULL;

  unsubscribe=FALSE;

  if (argc < 2) {
    print_usage (argv[0]);
    return -1;
  }

  if (strcmp (argv[1], "-help") == 0) {
    print_usage (argv[0]);
    return -1;
  }

  strcpy (xmpp_server, "none");
  strcpy (pubsub_server, "none");

  while (current_arg_num < argc) {
    current_arg_name = argv[current_arg_num++];

    if (strcmp (current_arg_name, "-help") == 0) {
      print_usage (argv[0]);
      return -1;
    }

    if (strcmp (current_arg_name, "-verbose") == 0) {
      verbose = TRUE;
      continue;
    }

    if(strcmp(current_arg_name,"-unsubscribe")==0) {
      unsubscribe = TRUE;
      continue;
    }
 
    if (current_arg_num == argc) {
      print_usage (argv[0]);
      return -1;
    }

    current_arg_val = argv[current_arg_num++];

     if(strcmp(current_arg_name,"-f")==0) {
      event_node_file_str = current_arg_val;
      printf( "Loading File: %s\n",event_node_file_str );
    } 
   else if (strcmp (current_arg_name, "-u") == 0) {
      username = current_arg_val;
      if (strcmp (xmpp_server, "none") == 0) {
        strcpy (domain, username);
        result = strtok (domain, "@");
        result = strtok (NULL, "@");
        strcpy (xmpp_server, result);
        strcpy (pubsub_server, "pubsub.");
        strcat (pubsub_server, xmpp_server);
      }
    }
    else if (strcmp (current_arg_name, "-p") == 0) {
      password = current_arg_val;
    }
    else if (strcmp (current_arg_name, "-host") == 0) {
      strcpy (xmpp_server, current_arg_val);
      if (strcmp (pubsub_server, "none") == 0) {
        strcpy (pubsub_server, "pubsub.");
        strcat (pubsub_server, xmpp_server);
      }
    }
    else if (strcmp (current_arg_name, "-port") == 0) {
      xmpp_server_port = atoi (current_arg_val);
    }
    else if (strcmp (current_arg_name, "-pubsub") == 0) {
      strcpy (pubsub_server, current_arg_val);
    }
    else if (strcmp (current_arg_name, "-ssl") == 0) {
      xmpp_ssl_fingerprint = current_arg_val;
    }
    else if (strcmp (current_arg_name, "-du") == 0) {
      db_username = current_arg_val;
    }
    else if (strcmp (current_arg_name, "-dp") == 0) {
      db_password = current_arg_val;
    }
    else if (strcmp (current_arg_name, "-dhost") == 0) {
      db_server = current_arg_val;
    }
    else if (strcmp (current_arg_name, "-dname") == 0) {
      db_name = current_arg_val;
    }
    else if (strcmp (current_arg_name, "-dport") == 0) {
      db_server_port = atoi(current_arg_val);
    }
    else {
      g_printerr ("Unknown argument: %s\n", current_arg_name);
      print_usage (argv[0]);
      return -1;
    }
  }

  if (username == NULL) {
    g_printerr ("Username missing\n");
    print_usage (argv[0]);
    return -1;
  }
  else if (password == NULL) {
    g_printerr ("Password missing\n");
    print_usage (argv[0]);
    return -1;
  }
  else if (db_username == NULL) {
    g_printerr ("Database username missing\n");
    print_usage (argv[0]);
    return -1;
  }
  else if (db_password == NULL) {
    g_printerr ("Database password missing\n");
    print_usage (argv[0]);
    return -1;
  }
  else if (db_server == NULL) {
    g_printerr ("Database server name missing\n");
    print_usage (argv[0]);
    return -1;
  }
  else if (db_name == NULL) {
    g_printerr ("Database name missing\n");
    print_usage (argv[0]);
    return -1;
  }

  if (verbose) {
    g_print ("XMPP Server: %s\n", xmpp_server);
    g_print ("XMPP Server Port: %d\n", xmpp_server_port);
    g_print ("XMPP PubSub Server: %s\n", pubsub_server);
    g_print ("XMPP Server SSL Fingerprint: %s\n", xmpp_ssl_fingerprint);
    g_print ("username: %s\n", username);
    g_print ("DB username: %s\n",db_username);
    g_print ("DB server: %s\n",db_server);
    g_print ("DB server port: %u\n",db_server_port);
    g_print ("DB name: %s\n",db_name);
    g_print ("Verbose: YES\n");
    g_print ("\n");
  }

  main_loop = g_main_loop_new (NULL, FALSE);

  if(verbose)
    printf("initialized xmpp client\n");  

  //Create connection to database
  mysql_init(&connection);
  sock = mysql_real_connect(&connection,
			    db_server,
			    db_username,
			    db_password,
			    db_name,
			    db_server_port,
			    NULL,
			    0);
  if(!sock) {
    fprintf(stderr,"Couldnt connect to database\n%s\n",mysql_error(&connection));
    perror("");
    return -1;
  }
  
  connection.reconnect = 1;

  xmpp_connection = start_xmpp_client(username,
				      password,
				      xmpp_server,
				      xmpp_server_port,
				      xmpp_ssl_fingerprint,
				      pubsub_server,
				      handle_event);
  
  if(xmpp_connection == NULL) {
    printf("Could not start client\n");
    return -1;
  }

  if(verbose)
    printf("Connected to database\n");

    //Unsubscribe from all nodes on service
  if(unsubscribe) {
    node_list = get_all_current_subscriptions(xmpp_connection);
    if(node_list == NULL)
      g_print("No subscriptions found\n");
    else {
      g_slist_foreach(node_list,do_unsubscribe,xmpp_connection);
      g_slist_free(node_list);
      node_list = NULL;
    }
  }
  
  //Subscribe to DeviceCreation event node to get notifications of new devices
  ret = subscribe_to_node(xmpp_connection,"DeviceCreation");
  if(ret != XMPP_NO_ERROR) {
    printf("Coult not subscribe to root creation\n");
    return -1;
  }

  if(verbose)
    printf("Subscribed to DeviceCreation\n");


 //Read event nodes from file if specified by user
  if(event_node_file_str != NULL) {
    event_node_file = fopen(event_node_file_str,"r");
    if(event_node_file == NULL) {
      g_printerr("ERROR: could not open file %s\n",event_node_file_str);
      return -1;
    }
    while((ret_char=readline(buf,event_node_file))!=NULL) {
      NodeDesc *node = g_new0 (NodeDesc, 1);
      strcpy(node->name,ret_char);
      node_list = g_slist_prepend (node_list, node);
    }
    fclose(event_node_file);
  }

  //Subscribe to all nodes in list
  if(node_list == NULL)
    g_print("No Nodes to subscribe to\n");
  else {
    g_slist_foreach(node_list,do_subscribe,xmpp_connection);
    g_slist_free(node_list);

    main_loop = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (main_loop);
  }





//  g_main_loop_run (main_loop);

  mysql_close(sock);

  return 0;
}
bool _database::connection(MYSQL *conn, char *host, char *user, char *pass, char *name)
{
	mysql_init(conn);
	return !mysql_real_connect(conn, host, user, pass, name, 0, 0, 0) ? false : true;
}