Ejemplo n.º 1
0
void poll_host(int host_id) {
    char query1[BUFSIZE];
    char query2[BUFSIZE];
    char *query3;
    char query4[BUFSIZE];
    char errstr[512];
    int num_rows;
    int host_status;
    int assert_fail = 0;
    char *poll_result = NULL;
    char logmessage[LOGSIZE];
    char update_sql[BUFSIZE];

    reindex_t *reindex;
    target_t *entry;
    host_t *host;
    ping_t *ping;

    MYSQL mysql;
    MYSQL_RES *result;
    MYSQL_ROW row;

    /* allocate host and ping structures with appropriate values */
    host = (host_t *) malloc(sizeof(host_t));
    ping = (ping_t *) malloc(sizeof(ping_t));

#ifndef OLD_MYSQL
    mysql_thread_init();
#endif

    snprintf(query1, sizeof(query1), "select action,hostname,snmp_community,snmp_version,snmp_username,snmp_password,rrd_name,rrd_path,arg1,arg2,arg3,local_data_id,rrd_num,snmp_port,snmp_timeout from poller_item where host_id=%i order by rrd_path,rrd_name", host_id);
    snprintf(query2, sizeof(query2), "select id, hostname,snmp_community,snmp_version,snmp_port,snmp_timeout,status,status_event_count,status_fail_date,status_rec_date,status_last_error,min_time,max_time,cur_time,avg_time,total_polls,failed_polls,availability from host where id=%i", host_id);
    snprintf(query4, sizeof(query4), "select data_query_id,action,op,assert_value,arg1 from poller_reindex where host_id=%i", host_id);

    db_connect(set.dbdb, &mysql);

    /* get data about this host */
    result = db_query(&mysql, query2);
    num_rows = (int)mysql_num_rows(result);

    if (num_rows != 1) {
        snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: Unknown Host ID", host_id);
        cacti_log(logmessage);
        return;
    }

    row = mysql_fetch_row(result);

    /* populate host structure */
    host->id = atoi(row[0]);
    if (row[1] != NULL) snprintf(host->hostname, sizeof(host->hostname), "%s", row[1]);
    if (row[2] != NULL) snprintf(host->snmp_community, sizeof(host->snmp_community), "%s", row[2]);
    host->snmp_version = atoi(row[3]);
    host->snmp_port = atoi(row[4]);
    host->snmp_timeout = atoi(row[5]);
    if (row[6] != NULL) host->status = atoi(row[6]);
    host->status_event_count = atoi(row[7]);
    snprintf(host->status_fail_date, sizeof(host->status_fail_date), "%s", row[8]);
    snprintf(host->status_rec_date, sizeof(host->status_rec_date), "%s", row[9]);
    snprintf(host->status_last_error, sizeof(host->status_last_error), "%s", row[10]);
    host->min_time = atof(row[11]);
    host->max_time = atof(row[12]);
    host->cur_time = atof(row[13]);
    host->avg_time = atof(row[14]);
    host->total_polls = atoi(row[15]);
    host->failed_polls = atoi(row[16]);
    host->availability = atof(row[17]);

    host->ignore_host = 0;

    /* initialize SNMP */
    snmp_host_init(host);

    /* perform a check to see if the host is alive by polling it's SysDesc
     * if the host down from an snmp perspective, don't poll it.
     * function sets the ignore_host bit */
    if ((set.availability_method == AVAIL_SNMP) && (host->snmp_community == "")) {
        update_host_status(HOST_UP, host, ping, set.availability_method);

        if (set.verbose >= POLLER_VERBOSITY_MEDIUM) {
            snprintf(logmessage, LOGSIZE, "Host[%s] No host availability check possible for '%s'\n", host->id, host->hostname);
            cacti_log(logmessage);
        }
    } else {
        if (ping_host(host, ping) == HOST_UP) {
            update_host_status(HOST_UP, host, ping, set.availability_method);
        } else {
            host->ignore_host = 1;
            update_host_status(HOST_DOWN, host, ping, set.availability_method);
        }
    }

    /* update host table */
    snprintf(update_sql, sizeof(update_sql), "update host set status='%i',status_event_count='%i', status_fail_date='%s',status_rec_date='%s',status_last_error='%s',min_time='%f',max_time='%f',cur_time='%f',avg_time='%f',total_polls='%i',failed_polls='%i',availability='%.4f' where id='%i'\n",
             host->status,
             host->status_event_count,
             host->status_fail_date,
             host->status_rec_date,
             host->status_last_error,
             host->min_time,
             host->max_time,
             host->cur_time,
             host->avg_time,
             host->total_polls,
             host->failed_polls,
             host->availability,
             host->id);

    db_insert(&mysql, update_sql);

    /* do the reindex check for this host */
    if (!host->ignore_host) {
        reindex = (reindex_t *) malloc(sizeof(reindex_t));

        result = db_query(&mysql, query4);
        num_rows = (int)mysql_num_rows(result);

        if (num_rows > 0) {
            if (set.verbose == POLLER_VERBOSITY_DEBUG) {
                snprintf(logmessage, LOGSIZE, "Host[%i] RECACHE: Processing %i items in the auto reindex cache for '%s'\n", host->id, num_rows, host->hostname);
                cacti_log(logmessage);
            }

            while ((row = mysql_fetch_row(result))) {
                assert_fail = 0;

                reindex->data_query_id = atoi(row[0]);
                reindex->action = atoi(row[1]);
                if (row[2] != NULL) snprintf(reindex->op, sizeof(reindex->op), "%s", row[2]);
                if (row[3] != NULL) snprintf(reindex->assert_value, sizeof(reindex->assert_value), "%s", row[3]);
                if (row[4] != NULL) snprintf(reindex->arg1, sizeof(reindex->arg1), "%s", row[4]);

                switch(reindex->action) {
                case POLLER_ACTION_SNMP: /* snmp */
                    poll_result = snmp_get(host, reindex->arg1);
                    break;
                case POLLER_ACTION_SCRIPT: /* script (popen) */
                    poll_result = exec_poll(host, reindex->arg1);
                    break;
                }

                /* assume ok if host is up and result wasn't obtained */
                if (!strcmp(poll_result,"U")) {
                    assert_fail = 0;
                } else if ((!strcmp(reindex->op, "=")) && (strcmp(reindex->assert_value,poll_result) != 0)) {
                    snprintf(logmessage, LOGSIZE, "ASSERT: '%s=%s' failed. Recaching host '%s', data query #%i\n", reindex->assert_value, poll_result, host->hostname, reindex->data_query_id);
                    cacti_log(logmessage);

                    query3 = (char *)malloc(128);
                    snprintf(query3, 128, "insert into poller_command (poller_id,time,action,command) values (0,NOW(),%i,'%i:%i')", POLLER_COMMAND_REINDEX, host_id, reindex->data_query_id);
                    db_insert(&mysql, query3);
                    free(query3);

                    assert_fail = 1;
                } else if ((!strcmp(reindex->op, ">")) && (strtoll(reindex->assert_value, (char **)NULL, 10) <= strtoll(poll_result, (char **)NULL, 10))) {
                    snprintf(logmessage, LOGSIZE, "ASSERT: '%s>%s' failed. Recaching host '%s', data query #%i\n", reindex->assert_value, poll_result, host->hostname, reindex->data_query_id);
                    cacti_log(logmessage);

                    query3 = (char *)malloc(128);
                    snprintf(query3, 128, "insert into poller_command (poller_id,time,action,command) values (0,NOW(),%i,'%i:%i')", POLLER_COMMAND_REINDEX, host_id, reindex->data_query_id);
                    db_insert(&mysql, query3);
                    free(query3);

                    assert_fail = 1;
                } else if ((!strcmp(reindex->op, "<")) && (strtoll(reindex->assert_value, (char **)NULL, 10) >= strtoll(poll_result, (char **)NULL, 10))) {
                    snprintf(logmessage, LOGSIZE, "ASSERT: '%s<%s' failed. Recaching host '%s', data query #%i\n", reindex->assert_value, poll_result, host->hostname, reindex->data_query_id);
                    cacti_log(logmessage);

                    query3 = (char *)malloc(128);
                    snprintf(query3, 128, "insert into poller_command (poller_id,time,action,command) values (0,NOW(),%i,'%i:%i')", POLLER_COMMAND_REINDEX, host_id, reindex->data_query_id);
                    db_insert(&mysql, query3);
                    free(query3);

                    assert_fail = 1;
                }

                /* update 'poller_reindex' with the correct information if:
                 * 1) the assert fails
                 * 2) the OP code is > or < meaning the current value could have changed without causing
                 *     the assert to fail */
                if ((assert_fail == 1) || (!strcmp(reindex->op, ">")) || (!strcmp(reindex->op, ">"))) {
                    query3 = (char *)malloc(255);
                    snprintf(query3, 255, "update poller_reindex set assert_value='%s' where host_id='%i' and data_query_id='%i' and arg1='%s'", poll_result, host_id, reindex->data_query_id, reindex->arg1);
                    db_insert(&mysql, query3);
                    free(query3);
                }

                free(poll_result);
            }
        }
    }

    /* retreive each hosts polling items from poller cache */
    entry = (target_t *) malloc(sizeof(target_t));

    result = db_query(&mysql, query1);
    num_rows = (int)mysql_num_rows(result);

    while ((row = mysql_fetch_row(result)) && (!host->ignore_host)) {
        /* initialize monitored object */
        entry->target_id = 0;
        entry->action = atoi(row[0]);
        if (row[1] != NULL) snprintf(entry->hostname, sizeof(entry->hostname), "%s", row[1]);
        if (row[2] != NULL) {
            snprintf(entry->snmp_community, sizeof(entry->snmp_community), "%s", row[2]);
        } else {
            snprintf(entry->snmp_community, sizeof(entry->snmp_community), "%s", "");
        }
        entry->snmp_version = atoi(row[3]);
        if (row[4] != NULL) snprintf(entry->snmp_username, sizeof(entry->snmp_username), "%s", row[4]);
        if (row[5] != NULL) snprintf(entry->snmp_password, sizeof(entry->snmp_password), "%s", row[5]);
        if (row[6] != NULL) snprintf(entry->rrd_name, sizeof(entry->rrd_name), "%s", row[6]);
        if (row[7] != NULL) snprintf(entry->rrd_path, sizeof(entry->rrd_path), "%s", row[7]);
        if (row[8] != NULL) snprintf(entry->arg1, sizeof(entry->arg1), "%s", row[8]);
        if (row[9] != NULL) snprintf(entry->arg2, sizeof(entry->arg2), "%s", row[9]);
        if (row[10] != NULL) snprintf(entry->arg3, sizeof(entry->arg3), "%s", row[10]);
        entry->local_data_id = atoi(row[11]);
        entry->rrd_num = atoi(row[12]);
        entry->snmp_port = atoi(row[13]);
        entry->snmp_timeout = atoi(row[14]);
        snprintf(entry->result, sizeof(entry->result), "%s", "U");

        if (!host->ignore_host) {
            switch(entry->action) {
            case POLLER_ACTION_SNMP: /* raw SNMP poll */
                poll_result = snmp_get(host, entry->arg1);
                snprintf(entry->result, sizeof(entry->result), "%s", poll_result);
                free(poll_result);

                if (host->ignore_host) {
                    snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: SNMP timeout detected [%i milliseconds], ignoring host '%s'\n", host_id, host->snmp_timeout, host->hostname);
                    cacti_log(logmessage);
                    snprintf(entry->result, sizeof(entry->result), "%s", "U");
                } else {
                    /* remove double or single quotes from string */
                    strncpy(entry->result, strip_quotes(entry->result), sizeof(entry->result));

                    /* detect erroneous non-numeric result */
                    if (!is_numeric(entry->result)) {
                        strncpy(errstr, entry->result,sizeof(errstr));
                        snprintf(logmessage, LOGSIZE, "Host[%i] WARNING: Result from SNMP not valid. Partial Result: %.20s...\n", host_id, errstr);
                        cacti_log(logmessage);
                        strncpy(entry->result, "U", sizeof(entry->result));
                    }
                }

                if (set.verbose >= POLLER_VERBOSITY_MEDIUM) {
                    snprintf(logmessage, LOGSIZE, "Host[%i] SNMP: v%i: %s, dsname: %s, oid: %s, value: %s\n", host_id, host->snmp_version, host->hostname, entry->rrd_name, entry->arg1, entry->result);
                    cacti_log(logmessage);
                }

                break;
            case POLLER_ACTION_SCRIPT: /* execute script file */
                poll_result = exec_poll(host, entry->arg1);
                snprintf(entry->result, sizeof(entry->result), "%s", poll_result);
                free(poll_result);

                /* remove double or single quotes from string */
                strncpy(entry->result, strip_quotes(entry->result), sizeof(entry->result));

                /* detect erroneous result. can be non-numeric */
                if (!validate_result(entry->result)) {
                    strncpy(errstr, (char *) strip_string_crlf(entry->result),sizeof(errstr));
                    snprintf(logmessage, LOGSIZE, "Host[%i] WARNING: Result from SCRIPT not valid. Partial Result: %.20s...\n", host_id, errstr);
                    cacti_log(logmessage);
                    strncpy(entry->result, "U", sizeof(entry->result));
                }

                if (set.verbose >= POLLER_VERBOSITY_MEDIUM) {
                    snprintf(logmessage, LOGSIZE, "Host[%i] SCRIPT: %s, output: %s\n", host_id, entry->arg1, entry->result);
                    cacti_log(logmessage);
                }

                break;
            case POLLER_ACTION_PHP_SCRIPT_SERVER: /* execute script server */
                poll_result = php_cmd(entry->arg1);
                snprintf(entry->result, sizeof(entry->result), "%s", poll_result);
                free(poll_result);

                /* remove double or single quotes from string */
                strncpy(entry->result, strip_quotes(entry->result), sizeof(entry->result));

                /* detect erroneous result. can be non-numeric */
                if (!validate_result(entry->result)) {
                    strncpy(errstr, entry->result, sizeof(errstr));
                    snprintf(logmessage, LOGSIZE, "Host[%i] WARNING: Result from SERVER not valid.  Partial Result: %.20s...\n", host_id, errstr);
                    cacti_log(logmessage);
                    strncpy(entry->result, "U", sizeof(entry->result));
                }

                if (set.verbose >= POLLER_VERBOSITY_MEDIUM) {
                    snprintf(logmessage, LOGSIZE, "Host[%i] SERVER: %s, output: %s\n", host_id, entry->arg1, entry->result);
                    cacti_log(logmessage);
                }

                break;
            default: /* unknown action, generate error */
                snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: Unknown Poller Action: %s\n", host_id, entry->arg1);
                cacti_log(logmessage);

                break;
            }
        }

        if (entry->result != NULL) {
            /* format database insert string */
            query3 = (char *)malloc(sizeof(entry->result) + sizeof(entry->local_data_id) + 128);
            snprintf(query3, (sizeof(entry->result) + sizeof(entry->local_data_id) + 128), "insert into poller_output (local_data_id,rrd_name,time,output) values (%i,'%s','%s','%s')", entry->local_data_id, entry->rrd_name, start_datetime, entry->result);
            db_insert(&mysql, query3);
            free(query3);
        }
    }

    /* cleanup memory and prepare for function exit */
    snmp_host_cleanup(host);

    free(entry);
    free(host);
    free(ping);

    mysql_free_result(result);

#ifndef OLD_MYSQL
    mysql_thread_end();
#endif

    mysql_close(&mysql);

    if (set.verbose == POLLER_VERBOSITY_DEBUG) {
        snprintf(logmessage, LOGSIZE, "Host[%i] DEBUG: HOST COMPLETE: About to Exit Host Polling Thread Function\n", host_id);
        cacti_log(logmessage);
    }
}
Ejemplo n.º 2
0
SqlConnection::~SqlConnection()
{
	mysql_close(&handle_);
}
Ejemplo n.º 3
0
MySQLConn::~MySQLConn()
{
	if (mysql)
		mysql_close(mysql);
}
Ejemplo n.º 4
0
bool DatabaseMysql::Initialize(const char *infoString)
{

    if (!Database::Initialize(infoString))
        return false;

    tranThread = NULL;
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        sLog.outError("Could not initialize Mysql connection");
        return false;
    }

    InitDelayThread();

    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.outDetail("Connected to MySQL database at %s", host.c_str());
        sLog.outString("MySQL client library: %s", mysql_get_client_info());
        sLog.outString("MySQL server ver: %s ", mysql_get_server_info( mMysql));

        if (!mysql_autocommit(mMysql, 1))
            sLog.outDetail("AUTOCOMMIT SUCCESSFULLY SET TO 1");
        else
            sLog.outDetail("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
        PExecute("SET NAMES `utf8`");
        PExecute("SET CHARACTER SET `utf8`");

    #if MYSQL_VERSION_ID >= 50003
        my_bool my_true = (my_bool)1;
        if (mysql_options(mMysql, MYSQL_OPT_RECONNECT, &my_true))
            sLog.outDetail("Failed to turn on MYSQL_OPT_RECONNECT.");
        else
           sLog.outDetail("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;
    }
}
Ejemplo n.º 5
0
static int check_session(const char *assertion, char *email)
{
    printf("MySQL client version: %s\n", mysql_get_client_info());
    MYSQL *conn;
    int query_rs;
    int num_rs;
    MYSQL_RES *rs;
    MYSQL_ROW row;

    char assertion_esc[300];
    char *select_email =
        "SELECT email FROM browserid_session WHERE digest = MD5('%s')";
    char select_email_esc[1024];

    char *update_session = "UPDATE browserid_session SET created = NOW() WHERE digest = MD5('%s')";
    char update_session_esc[1024];

    int rv = 0;

    conn = mysql_init(NULL);
    if (conn == NULL) {
        error(1, 1, "Unable to mysql_init");
    }
    conn = mysql_real_connect(conn, "localhost", "root", "", "mozillians", NULL, NULL, (void *) 0);
    if (conn == NULL) {
        printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
        error(1, 1, "Unable to connect to mysql server");
    }
    mysql_real_escape_string(conn, assertion_esc, assertion, strlen(assertion));
    sprintf(select_email_esc, select_email, assertion_esc);
    printf(select_email_esc);
    printf("\n");
    if (mysql_query(conn, select_email_esc) == 0) {
        rs = mysql_store_result(conn);
        while((row = mysql_fetch_row(rs))) {
            printf("Email: %s\n", row[0]);
	    printf("\n");
            strcpy(email, row[0]);
            rv = 1;
	    
	    /* Touch session */
	    sprintf(update_session_esc, update_session, assertion_esc);
	    printf(update_session_esc);
	    printf("\n");
	    mysql_query(conn, update_session_esc);
            break;
        }
        if (rs != 0) {
            mysql_free_result(rs);
        }
    } else if (query_rs == CR_UNKNOWN_ERROR) {
        error(1, 1, "Unkown Error");
    } else if (query_rs == CR_SERVER_GONE_ERROR ||\
               query_rs == CR_SERVER_LOST) {
        error(1, 1, "Executed query, SOL");
    } else {
        printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
        error(1, 1, mysql_error(conn));
    }
    mysql_close(conn);
    return rv;
}
Ejemplo n.º 6
0
/***********
  根据type得到十大列表,已经经过排序等一系列检查,可以直接输出
  type!=4的时候还得到分区十大
  *******/
int get_top(int type)
{

    MYSQL s;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char sqlbuf[500];
    char cmptime[200];
    int start=0;
    int i,secid;
    int threadid;
    char title[81];
    char userid[IDLEN+1];
    int m,n;
#ifdef BLESS_BOARD
    const struct boardheader *bh;
#endif

    topnum = 0;

    if (type < 0 || type > 4)
        return 0;

    mysql_init(&s);

    if (! my_connect_mysql(&s)) {
        return 0;;
    }

    if (type==0 || type==4) {
        //sprintf(cmptime,"YEAR(time)=YEAR(CURDATE()) AND MONTH(time)=MONTH(CURDATE()) AND DAYOFMONTH(time)=DAYOFMONTH(CURDATE())");
        sprintf(cmptime,"time>curdate()");
    } else if (type==1) {
        sprintf(cmptime,"YEAR(date)=YEAR(CURDATE()) AND WEEK(date)=WEEK(CURDATE())");
    } else if (type==2) {
        sprintf(cmptime,"YEAR(date)=YEAR(CURDATE()) AND MONTH(date)=MONTH(CURDATE())");
    } else if (type==3) {
        sprintf(cmptime,"YEAR(date)=YEAR(CURDATE())");
    }

    bzero(top, TOPCOUNT * sizeof(struct postrec));
    bzero(sectop, SECNUM * SECTOPCOUNT * sizeof(struct postrec));

    for (i=0;i<SECNUM;i++) sectopnum[i]=0;
    sectopnumtotal=0;

    while (1) {
        if (type==4) {
            if (topnum>=mytop[type])
                break;
        } else if (type==0) {
            if (topnum>=mytop[type] && sectopnumtotal>=SECNUM*SECTOPCOUNT)
                break;
        } else {
            if (topnum >= mytop[type])
                break;
        }

        if (start > MAXCMP)
            break;

        if (type==0 || type==4)
            sprintf(sqlbuf,"SELECT bname,threadid,MAX(UNIX_TIMESTAMP(time)) AS maxtime,count(DISTINCT userid) AS count FROM postlog WHERE %s GROUP BY bname,threadid ORDER BY count desc LIMIT %d,%d;", cmptime, start, INTERVAL);
        else
            sprintf(sqlbuf,"SELECT bname,threadid,UNIX_TIMESTAMP(time),count,title,userid FROM toplog WHERE %s ORDER BY count desc LIMIT %d,%d",cmptime,start, INTERVAL);

        if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) {
            printf("%s\n", mysql_error(&s));
            mysql_close(&s);

            return topnum;
        }

        res = mysql_store_result(&s);

        while (1) {
            row = mysql_fetch_row(res);
            if (row==NULL)
                break;

            /***检查是否该计算十大***/
            bh = getbcache(row[0]);
            if (bh==NULL || bh->flag & BOARD_POSTSTAT) {
                continue;
            }
            if (!normal_board(bh->filename))
                continue;
#ifdef BLESS_BOARD
            if (type==0) {
                if (! strcasecmp(row[0], BLESS_BOARD)) {
                    continue;
                }
            } else if (type==4) {
                if (strcasecmp(row[0], BLESS_BOARD)) {
                    continue;
                }
            }
#endif

            secid= get_seccode_index(bh->title[0]);

            if (topnum >= mytop[type] && (secid==-1 || sectopnum[secid] >= SECTOPCOUNT))
                continue;

            threadid = atoi(row[1]);
            if (type==0 || type==4) {
                if (get_file_title(row[0], threadid, title, userid) == NULL) {
                    continue;
                }
            } else {
                strncpy(title, row[4], 80);
                title[80]=0;
                strncpy(userid, row[5], IDLEN);
                userid[IDLEN]=0;
            }
            /**一个版面最多3个十大**/
            if (type==0) {
                m = 0;
                for (n = 0; n < topnum; n++) {
                    if (!strcmp(row[0], top[n].board))
                        m++;
                }
                if (m>0)
                    continue;

                /***分区十大里一个版面也最多3个***/
                if (secid!=-1) {
                    m = 0;
                    for (n = 0; n < sectopnum[secid]; n++) {
                        if (!strcmp(row[0], sectop[secid][n].board))
                            m++;
                    }
                    if (m>0)
                        continue;
                }
            }


            /***先记录正常十大的值***/
            if (topnum < mytop[type]) {

                strncpy(top[topnum].board, row[0], BOARDNAMELEN);
                top[topnum].board[BOARDNAMELEN-1]='\0';
                top[topnum].groupid = threadid;
                strncpy(top[topnum].title, title, 80);
                top[topnum].title[80]='\0';
                strncpy(top[topnum].userid, userid, IDLEN);
                top[topnum].userid[IDLEN]='\0';
                top[topnum].date = atol(row[2]);
                top[topnum].number = atoi(row[3]);

                topnum++;

            }

            /***计算分区十大***/
            if (type==0) {

                i=secid;
                if (i!=-1) {
                    if (sectopnum[i] < SECTOPCOUNT) {

                        strncpy(sectop[i][sectopnum[i]].board, row[0], BOARDNAMELEN);
                        sectop[i][sectopnum[i]].board[BOARDNAMELEN-1]='\0';
                        sectop[i][sectopnum[i]].groupid = threadid;
                        strncpy(sectop[i][sectopnum[i]].title, title, 80);
                        sectop[i][sectopnum[i]].title[80]='\0';
                        strncpy(sectop[i][sectopnum[i]].userid, userid, IDLEN);
                        sectop[i][sectopnum[i]].userid[IDLEN]='\0';
                        sectop[i][sectopnum[i]].date = atol(row[2]);
                        sectop[i][sectopnum[i]].number = atoi(row[3]);

                        sectopnum[i]++;
                        sectopnumtotal++;
                    }
                }

            }//type==0

            if (type==4) {
                if (topnum>=mytop[type])
                    break;
            } else if (type==0) {
                if (topnum >= mytop[type] && sectopnumtotal >= SECNUM*SECTOPCOUNT)
                    break;
            } else {
                if (topnum >= mytop[type])
                    break;
            }

        }

        mysql_free_result(res);

        start += INTERVAL;

    }

    mysql_close(&s);

    return topnum;

}
Ejemplo n.º 7
0
int main(int argc, char *argv[], char *envp[])
{
  int res,status;
  char databas[25]="olfix";
  const char *userp = getenv("USER");	// vem är inloggad?
  char usr[15];				// userid

  char temp1a[]="REPLACE INTO OFFERTRADREG (OFFERTNR,ORDERNR,ORDERRAD,KUNDNR,ARTIKELNR,BENEMNING,LEVERANSVECKA,BESTELLT,APRIS,SUMMA,MOMSKR,LEVERERAT,RESTNOTERAT,RADRABATT,KALKYLPRIS,LEVDATUM,ENHET,FAKTURERAT,RADORDERTYP) VALUES (";
  char temp2[]="\"";
  char temp3[]=",";
  char temp4[]=")";
  char temp5[1500]="";
  char offertraddata[2000]="";

  char *pos1;
  char *pos2;
  int tmp,lenght,ant,i,j,k,n;

  /* ================================================================================ */
/* 		Val av databas, START						    */
/* ================================================================================ */

  status = which_database(envp);

  if (status != 0)
	exit(status);

  strncpy(usr,userp,15);			/* Den inloggades userid	*/
/*  fprintf(stderr,"status=%d ANTARG=%d len(database)=%d\n",status,ANTARG,strlen(database));	*/
  if (argc < ANTARG+1){
    	if (strlen(database)!= 0){
		strncpy(databas,database,15);
	}else{
  		strncpy(databas,"olfixtst",15);	/* olfixtst = testföretag	*/
	}
  }else{
	if (strlen(argv[ANTARG]) != 0){
  		if (strncmp(argv[ANTARG],"99",2)==0){
			strncpy(databas,"olfixtst",15);
		}else{
  			strncpy(databas,argv[ANTARG],15);
  		}
  	}
  }
/*  fprintf(stderr,"ANTARG=%d,argv[ANTARG]=%s\n",ANTARG,argv[ANTARG]);	*/
/* Om usr (userid) börjar på 'test' eller 'prov' använd databas 'olfixtst' */
  if (strncmp(usr,"test",4)==0 || strncmp(usr,"prov",4)==0 ) {
  	strncpy(databas,"olfixtst",15);
  } /* fprintf(stderr,"Databas=%s\n",databas);	*/

/* ================================================================================ */
/* 		Val av databas, END!						    */
/* ================================================================================ */

  if (argv[1] != NULL){
  	strncpy(offertraddata,argv[1],sizeof(offertraddata));	/* 2005-02-23	*/
  }
  else{
  	fprintf(stderr,"Error: OFFRCHG: Ange offertnummer!\n");
	exit(-1);
  }


  lenght=strlen(offertraddata);
/*  fprintf(stderr,"lenght=%d\n",lenght);	*/
  strncpy(temp5,temp1a,strlen(temp1a));
/*  fprintf(stderr,"offertraddata=%s\n",offertraddata);	*/
  pos1=strstr(offertraddata,"_:_")+3;
  k=3;
  n=0;
  ant=ANTFELT;		/* antal fält	*/
  for (i=0;i<ant;i++){
  	for (j=k;j<lenght;j++){
/*		fprintf(stderr,"j=%d\n",j);	*/
  		if (offertraddata[j]== 95 && offertraddata[j+1]== 58 && offertraddata[j+2]== 95){
			j=lenght;
		}
		n=n+1;
  	}
	k=k+(n-1)+3;

	pos2=pos1+3+(n-1);

	tmp=pos2-pos1-3;
  	strncat(temp5,temp2,strlen(temp2));
  	strncat(temp5,pos1,tmp);
  	strncat(temp5,temp2,strlen(temp2));
	if (i<(ant-1)){
  		strncat(temp5,temp3,strlen(temp3));
	}
	pos1=pos2;
/*	fprintf(stderr,"i=%d, k=%d, n=%d, tmp=%d\n",i,k,n,tmp);	*/
	n=0;
/*	fprintf(stderr,"temp5 = %s\n",temp5);	*/
  }
  strncat(temp5,temp4,strlen(temp4));

 fprintf(stderr,"\nORDRCHG: temp5 = %s\n\n",temp5);	
// exit(0);	


  mysql_init(&my_connection);
  if (mysql_real_connect(&my_connection, "localhost",  "olfix", "olfix", databas, 0, NULL, 0)){
/*  	fprintf(stderr,"OFFRCHG:Connection success\n");	*/

  res = mysql_query(&my_connection,temp5);

  if (!res){
 	fprintf(stdout,"OK: OFFRCHG Inserted %lu rows\n",
		(unsigned long)mysql_affected_rows(&my_connection));
        }else{
	fprintf(stderr,"Error: OFFRCHG INSERT error: %d  %s\n", mysql_errno(&my_connection),
					mysql_error(&my_connection));
	}
	mysql_close(&my_connection);
 }else {
	fprintf(stderr,"Error: OFFRCHG Connection failed\n");
 	if (mysql_errno(&my_connection))   {
 		fprintf(stderr,"Error: OFFRCHG Connection error %d:  %s\n",
			mysql_errno(&my_connection), mysql_error(&my_connection));
	}
  }
 	fprintf(stdout,"\n");
  return EXIT_SUCCESS;
}
Ejemplo n.º 8
0
DataBaseConnector::~DataBaseConnector() {
    
  mysql_close(conn);
}
bool MySQLConnection::_HandleMySQLErrno(uint32 errNo, uint8 attempts /*= 5*/)
{
    switch (errNo)
    {
        case CR_SERVER_GONE_ERROR:
        case CR_SERVER_LOST:
        case CR_SERVER_LOST_EXTENDED:
        {
            if (m_Mysql)
            {
                TC_LOG_ERROR("sql.sql", "Lost the connection to the MySQL server!");

                mysql_close(GetHandle());
                m_Mysql = nullptr;
            }
        }
        /* fallthrough */
        case CR_CONN_HOST_ERROR:
        {
            TC_LOG_INFO("sql.sql", "Attempting to reconnect to the MySQL server...");

            m_reconnecting = true;

            uint32 const lErrno = Open();
            if (!lErrno)
            {
                // Don't remove 'this' pointer unless you want to skip loading all prepared statements...
                if (!this->PrepareStatements())
                {
                    TC_LOG_FATAL("sql.sql", "Could not re-prepare statements!");
                    std::this_thread::sleep_for(std::chrono::seconds(10));
                    std::abort();
                }

                TC_LOG_INFO("sql.sql", "Successfully reconnected to %s @%s:%s (%s).",
                    m_connectionInfo.database.c_str(), m_connectionInfo.host.c_str(), m_connectionInfo.port_or_socket.c_str(),
                        (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous");

                m_reconnecting = false;
                return true;
            }

            if ((--attempts) == 0)
            {
                // Shut down the server when the mysql server isn't
                // reachable for some time
                TC_LOG_FATAL("sql.sql", "Failed to reconnect to the MySQL server, "
                             "terminating the server to prevent data corruption!");

                // We could also initiate a shutdown through using std::raise(SIGTERM)
                std::this_thread::sleep_for(std::chrono::seconds(10));
                std::abort();
            }
            else
            {
                // It's possible this attempted reconnect throws 2006 at us.
                // To prevent crazy recursive calls, sleep here.
                std::this_thread::sleep_for(std::chrono::seconds(3)); // Sleep 3 seconds
                return _HandleMySQLErrno(lErrno, attempts); // Call self (recursive)
            }
        }

        case ER_LOCK_DEADLOCK:
            return false;    // Implemented in TransactionTask::Execute and DatabaseWorkerPool<T>::DirectCommitTransaction
        // Query related errors - skip query
        case ER_WRONG_VALUE_COUNT:
        case ER_DUP_ENTRY:
            return false;

        // Outdated table or database structure - terminate core
        case ER_BAD_FIELD_ERROR:
        case ER_NO_SUCH_TABLE:
            TC_LOG_ERROR("sql.sql", "Your database structure is not up to date. Please make sure you've executed all queries in the sql/updates folders.");
            std::this_thread::sleep_for(std::chrono::seconds(10));
            std::abort();
            return false;
        case ER_PARSE_ERROR:
            TC_LOG_ERROR("sql.sql", "Error while parsing SQL. Core fix required.");
            std::this_thread::sleep_for(std::chrono::seconds(10));
            std::abort();
            return false;
        default:
            TC_LOG_ERROR("sql.sql", "Unhandled MySQL errno %u. Unexpected behaviour possible.", errNo);
            return false;
    }
}
Ejemplo n.º 10
0
MySQLConnection::~MySQLConnection()
{
    FreePreparedStatements();
    mysql_close(mMysql);
}
Ejemplo n.º 11
0
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`");

#if MYSQL_VERSION_ID >= 50003
        my_bool my_true = (my_bool)1;
        if (mysql_options(mMysql, MYSQL_OPT_RECONNECT, &my_true))
        {
            sLog.outDetail("Failed to turn on MYSQL_OPT_RECONNECT.");
        }
        else
        {
            sLog.outDetail("Successfully turned on MYSQL_OPT_RECONNECT.");
        }
#else
        sLog.outDetail("Your mySQL client lib version does not support reconnecting after a timeout.");
        sLog.outDetail("If this causes you any trouble we advice you to upgrade");
        sLog.outDetail("your mySQL client libs to at least mySQL 5.0.13 to resolve this problem.");
#endif

    return true;
}
Ejemplo n.º 12
0
int main( int argc, char *argv[])
{
 time_t now;
   MYSQL *conn;
   MYSQL_RES *res;
   MYSQL_ROW row;
   struct contact list[5];
   char *server = "127.0.0.1";
   char *user = "******";
   char *password = "******"; /* set me first */
   char *database = "FD";
FILE *output;
int i = 0;
int count = 0;
int lines ;
char c;
char buff[512] ; // output to the sign
char bufftmp[100]; // local concat
int numberOfRows;

		 
output = fopen("/home/kd5lct/hamradio/hamoutput.htm" , "w");
fprintf(output,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" ");
fprintf(output,"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
fprintf(output,"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
fprintf(output,"<head>\n");
fprintf(output,"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n");
fprintf(output,"<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"65\">");
fprintf(output,"<META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\">");
fprintf(output,"<title>K5SLD Field Day Stats TESTING DATA NOT REAL!!!!</title>");
fprintf(output, "<link href=\"css/oneColFixCtrHdr.css\" rel=\"stylesheet\" type=\"text/css\" />\n");
fprintf(output,"</head>\n");

fprintf(output,"<body>\n"
"<div class=\"container\">\n"
"<div class=\"header\"><a href=\"http://www.k5sld.com\"><img src=\"images/header.jpg\" alt=\"Radio\" name=\"Radio\" width=\"180\" height=\"90\" id=\"Radio\" style=\"background: #C6D580; display:block; background-color: #00FFFF;\" />\n"
  "</a> <a href=\"/hamoutput.htm\">Stats</a> <BR />\n"
  "<!-- end .header --></div>\n"
  "<div class=\"content\">\n");
fprintf(output,"<h1>Welcome to K5SLD Field day statsi<br> TEST DATA NOT REAL!!!!!,</h1>\n"
    "<p>This page will display the last five stations worked for each station and auto refresh every 65 seconds.</p>\n"
    "<p>cw</p>\n"
      "<p>");

   conn = mysql_init(NULL);
   if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

i =0;//					0	1	2	3		4		   5	6 	7
   if (mysql_query(conn, "select fldPrimaryKey,fldCall,fldClass, fldState, fldDateStr, fldTransmitterID, fldBand, FldMode  from tblContacts where FldBand>=10 AND FldMode ='CW' order by fldPrimaryKey DESC LIMIT 0,5")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   res = mysql_use_result(conn);

while ((row = mysql_fetch_row(res)) != NULL)
      	{


        strcpy(list[i].id, " "); //number NOT USED
        strcpy(list[i].call, row[1]); // Call Sign
        strcpy(list[i].type, row[2]); // Type of station (3A)
        strcpy(list[i].location, row[3]); // Section Section
        strcpy(list[i].date, row[4]); //Date string
        strcpy(list[i].time, row[5]); //Time string
        strcpy(list[i].band, row[6]); // Band
        strcpy(list[i].mode, row[7]); // Mode
        strcpy(list[i].op, " ");

	i++;
	}
	count =i;
   mysql_free_result(res);    
	fprintf(output,"<table width=\"400\" border=\"1\">");
        fprintf(output, "<tr><td>");
        fprintf(output, "Call");
        fprintf(output,"</td><td>");
        fprintf(output,"Class");
       fprintf(output, "</td><td>");
        fprintf(output, "Section");
	    fprintf(output,"</td><td>");
        fprintf(output, "Date");
		fprintf(output,"</td><td>");
        fprintf(output, "Time");

        fprintf(output,"</td><td>");
        fprintf(output, "Band");
        fprintf(output, "</td><td>");
        fprintf(output,"Mode");
		fprintf(output,"</td></tr>\n");
for(i =0 ; i < count ; i++)
{
        // Print out the contents of each row into a table
        fprintf(output,"<tr><td>");
        fprintf(output,"%s ",list[i].call);
        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].type);
        fprintf(output,"</td><td>");
fprintf(output,"%s",list[i].location);        
        fprintf(output,"</td><td>");

        fprintf(output, "%s ",list[i].date);
        fprintf(output,"</td><td>");
        fprintf(output,"%sUTC",list[i].time);
        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].band);

        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].mode);
		fprintf(output,"</td></tr>\n");
		}
                fprintf(output," </table> </p>");


i =0;
   if (mysql_query(conn, "select fldPrimaryKey,fldCall,fldClass, fldState, fldDateStr, fldTransmitterID, fldBand, FldMode  from tblContacts where FldBand>=10 AND FldMode ='DIG' order by fldPrimaryKey DESC LIMIT 0,5")) {

      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   res = mysql_use_result(conn);

while ((row = mysql_fetch_row(res)) != NULL)
      	{


    strcpy(list[i].id, " "); //number NOT USED
    strcpy(list[i].call, row[1]); // Call Sign
    strcpy(list[i].type, row[2]); // Type of station (3A)
    strcpy(list[i].location, row[3]); // Section Section
    strcpy(list[i].date, row[4]); //Date string
    strcpy(list[i].time, row[5]); //Time string
    strcpy(list[i].band, row[6]); // Band
    strcpy(list[i].mode, row[7]); // Mode
    strcpy(list[i].op, " ");


	i++;
	}
count = i;
   mysql_free_result(res);
   fprintf(output,"<p>digi</p>\n"
      "<p>\n");
        fprintf(output,"<table width=\"400\" border=\"1\">");
        fprintf(output, "<tr><td>");;
        fprintf(output, "Call");
        fprintf(output,"</td><td>");
        fprintf(output,"Class");
       fprintf(output, "</td><td>");
        fprintf(output, "Section");
	    fprintf(output,"</td><td>");
        fprintf(output, "Date");
		fprintf(output,"</td><td>");
        fprintf(output, "Time");

        fprintf(output,"</td><td>");
        fprintf(output, "Band");
        fprintf(output, "</td><td>");
        fprintf(output,"Mode");
		fprintf(output,"</td></tr>\n");
for(i =0 ; i < count ; i++)
{
        // Print out the contents of each row into a table
        fprintf(output,"<tr><td>");
       fprintf(output,"%s ",list[i].call);
        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].type);
        fprintf(output,"</td><td>");
fprintf(output,"%s",list[i].location);        
        fprintf(output,"</td><td>");

        fprintf(output, "%s ",list[i].date);
        fprintf(output,"</td><td>");
        fprintf(output,"%sUTC",list[i].time);
        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].band);

        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].mode);
		fprintf(output,"</td></tr>\n");
		}
fprintf(output,"</table>  </p>");

i =0;
   if (mysql_query(conn, "select fldPrimaryKey,fldCall,fldClass, fldState, fldDateStr, fldTransmitterID, fldBand, FldMode  from tblContacts where FldBand>=10 AND FldMode ='PH' order by fldPrimaryKey DESC LIMIT 0,5")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   res = mysql_use_result(conn);

while ((row = mysql_fetch_row(res)) != NULL)
      	{

    strcpy(list[i].id, " "); //number NOT USED
    strcpy(list[i].call, row[1]); // Call Sign
    strcpy(list[i].type, row[2]); // Type of station (3A)
    strcpy(list[i].location, row[3]); // Section Section
    strcpy(list[i].date, row[4]); //Date string
    strcpy(list[i].time, row[5]); //Time string
    strcpy(list[i].band, row[6]); // Band
    strcpy(list[i].mode, row[7]); // Mode
    strcpy(list[i].op, " ");


	i++;
	}
count = i;
   mysql_free_result(res);
   fprintf(output,"<p>phone</p>\n"
      "<p>\n");
        fprintf(output,"<table width=\"400\" border=\"1\">");
        fprintf(output, "<tr><td>");
        fprintf(output, "Call");
        fprintf(output,"</td><td>");
        fprintf(output,"Class");
       fprintf(output, "</td><td>");
        fprintf(output, "Section");
	    fprintf(output,"</td><td>");
        fprintf(output, "Date");
		fprintf(output,"</td><td>");
        fprintf(output, "Time");

        fprintf(output,"</td><td>");
        fprintf(output, "Band");
        fprintf(output, "</td><td>");
        fprintf(output,"Mode");
		fprintf(output,"</td></tr>\n");
for(i =0 ; i < count ; i++)
{
        // Print out the contents of each row into a table
        fprintf(output,"<tr><td>");
       fprintf(output,"%s ",list[i].call);
        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].type);
        fprintf(output,"</td><td>");
fprintf(output,"%s",list[i].location);        
        fprintf(output,"</td><td>");

        fprintf(output, "%s ",list[i].date);
        fprintf(output,"</td><td>");
        fprintf(output,"%sUTC",list[i].time);
        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].band);

        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].mode);
		fprintf(output,"</td></tr>\n");
		}
                fprintf(output, "</table>  </p>");
                i =0;
   if (mysql_query(conn, "select fldPrimaryKey,fldCall,fldClass, fldState, fldDateStr, fldTransmitterID, fldBand, FldMode  from tblContacts where FldBand<10 order by fldPrimaryKey DESC LIMIT 0,5")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   res = mysql_use_result(conn);

while ((row = mysql_fetch_row(res)) != NULL)
      	{



    strcpy(list[i].id, " "); //number NOT USED
    strcpy(list[i].call, row[1]); // Call Sign
    strcpy(list[i].type, row[2]); // Type of station (3A)
    strcpy(list[i].location, row[3]); // Section Section
    strcpy(list[i].date, row[4]); //Date string
    strcpy(list[i].time, row[5]); //Time string
    strcpy(list[i].band, row[6]); // Band
    strcpy(list[i].mode, row[7]); // Mode
    strcpy(list[i].op, " ");
	i++;
	}
count = i;
   mysql_free_result(res);
   fprintf(output,"<p>VHF</p>\n"
      "<p>\n");
        fprintf(output,"<table width=\"400\" border=\"1\">");
        fprintf(output, "<tr><td>");
        fprintf(output, "Call");
        fprintf(output,"</td><td>");
        fprintf(output,"Class");
       fprintf(output, "</td><td>");
        fprintf(output, "Section");
	    fprintf(output,"</td><td>");
        fprintf(output, "Date");
		fprintf(output,"</td><td>");
        fprintf(output, "Time");

        fprintf(output,"</td><td>");
        fprintf(output, "Band");
        fprintf(output, "</td><td>");
        fprintf(output,"Mode");
		fprintf(output,"</td></tr>\n");
for(i =0 ; i < count ; i++)
{
        // Print out the contents of each row into a table
        fprintf(output,"<tr><td>");
       fprintf(output,"%s ",list[i].call);
        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].type);
        fprintf(output,"</td><td>");
fprintf(output,"%s",list[i].location);        
        fprintf(output,"</td><td>");

        fprintf(output, "%s ",list[i].date);
        fprintf(output,"</td><td>");
        fprintf(output,"%sUTC",list[i].time);
        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].band);

        fprintf(output,"</td><td>");
        fprintf(output,"%s ",list[i].mode);
		fprintf(output,"</td></tr>\n");
		}
                fprintf(output,"</table>  </p>");
                i =0;

time(&now);
	fprintf(output,"<br>time generated, %s <br>",ctime(&now));
	fprintf(output,"<p>View of the Field Day</p>"
"<p><img src=\"out.jpg\" width=\"640\" height=\"480\" alt=\"A webcam\" longdesc=\"A webcam at Field day site\" /><br>"
"</p>");
fprintf(output," </div>\n"
  "<div class=\"footer\">\n"
    "<p>^.^</p>\n"
   " <!-- end .footer --></div>"
 " <!-- end .container --></div>"
"\n</body>\n"
"</html>");
   mysql_close(conn);
fclose(output);
return 0;
}
Ejemplo n.º 13
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;
        }
    }

}
Ejemplo n.º 14
0
Archivo: main.cpp Proyecto: xlin/pbs
int main(int argc, char **argv){
    if (getuid()!=0){
	std::cout << "run only root" << std::endl;
	return 1;
    }
    MYSQL_RES *result;
    MYSQL_ROW row;
    MYSQL *connection, mysql;    
    
    // Защита от двойного запуска
    int fd = -1;
    if ((fd = open(PATHLOCK, O_RDWR| O_CREAT, S_IRUSR| S_IWUSR)) == -1) {
        int myerr = errno;
        printf("ERROR: open errno(%d): %s\n", errno,strerror(myerr));
        return EXIT_FAILURE;
    }
    if (LockFile(fd)==EXIT_FAILURE){
	std::cout << "ERROR: is already running" << std::endl;
	return 1;
    }
    
    
    // Читаем в map параметры командной строки
    map<string,string> cmdParam = loadArgv(argc,argv);
    
    if (cmdParam["--daemon"]=="true") run_as_daemon();
    

    map<string,string> conf = loadConfig();
    //string pathAum=conf["paths/pathAum"];
    string pathUserHome=conf["paths/pathUserHome"];
    //string pathPbs=conf["paths/pathPbs"];
    string pathTemp=conf["paths/pathTemp"];

    string cmdLine="";
    string sqlQuery="";
    int buildError=0;		// Состояние ошибки
    
    mysql_init(&mysql);
    connection = mysql_real_connect(&mysql,conf["mysql/hostname"].c_str(), conf["mysql/username"].c_str(), conf["mysql/password"].c_str(), conf["mysql/database"].c_str(), 0, NULL,0);
    if( connection == NULL ) {
	printf("%s\n",mysql_error(&mysql));
        return 1;
    }
    
    srand (time(NULL));

    // Тут будет основной цикл
    while(1){
	
	int state = mysql_query(connection, 
	    "SELECT t1.id,t1.file_id, t2.filename, t3.user, t4.os, t4.arch "
	    "FROM jobs as t1, tsrc t2, users as t3, platforms as t4 "
	    "WHERE t1.status=0 and t2.id=t1.file_id and t3.id=t2.user_id and t4.id=t1.platform_id ");
	    
	if( state != 0 ) {
	    printf("%s\n",mysql_error(connection));
	    break;
	}

        result = mysql_store_result(connection);    
	while( ( row = mysql_fetch_row(result)) != NULL ) {
    	    printf("%s, %s\n",  row[0],row[1]);
    	
    	    // 
    	    sqlQuery="UPDATE jobs SET status='1' WHERE id='"+string(row[0])+"'";
    	    mysql_query(connection,sqlQuery.c_str());
    	
    	    string dbNSrcFile=string(row[1]);
    	    string dbOsName=string(row[4]);
    	    string dbOsArch=string(row[5]);
	    string username=string(row[3]);
	    string jobFilename=string(row[2]);
	    
	    string aumOsKey=dbOsName+"_"+dbOsArch;
	    string aumLogFile=pathUserHome+"/"+username+"/logs/"+dbNSrcFile+"/"+aumOsKey+".txt";
	    string aumUploadDir=pathTemp+"/files/"+dbNSrcFile;
	    string aumFileName=pathUserHome+"/"+username+"/srpms/"+dbNSrcFile+"/"+jobFilename;

	    std::cout << " " << dbNSrcFile << " " << dbOsName << " " << dbOsArch << " " << username << " " << jobFilename << " " << aumOsKey << std::endl;
	    
	    string aumChroot=conf[aumOsKey+"/chroot"];
	    string aumDistrib=conf[aumOsKey+"/distrib"];
	    
	    string aumPathTemp=pathTemp+"/pbs-chroot-"+dbNSrcFile+"-"+aumOsKey;
	    
	    //Создание временной папки
	    pbsMkdir(aumUploadDir);
	    pbsMkdir(aumPathTemp);

	    map<string,string> options;
	
	    // Формирование строки
	    //cmdLine=pathAum+" ";
	    options["chroot"]=aumChroot;
	    options["distrib"]=aumDistrib;
	    options["log-file"]=aumLogFile;
	    options["upload-dir"]=aumUploadDir;
	    options["tmp-dir"]=aumPathTemp;
	    
	    if (boost::filesystem::exists(pathUserHome+"/"+username+"/.rpmmacros")==true){
		options["rpmmacros"]=pathUserHome+"/"+username+"/.rpmmacros";
	    }
	    options["srpm"]=aumFileName;

	    

	    // Запуск сборки
	    //buildError=system(cmdLine.c_str());
	    cBuild bb;
	    buildError=bb.build(options);
	    if (buildError!=0){
    	        string sqlQuery="UPDATE jobs SET status='11' WHERE id='"+string(row[0])+"'";
    		mysql_query(connection,sqlQuery.c_str());
		continue;
	    }
	    

	    string targetOs = pathUserHome+"/"+username+"/repo/"+dbOsName;
	    int countFile=copyRpmToRepo(aumUploadDir,targetOs);
	    if (countFile==0){
    	        string sqlQuery="UPDATE jobs SET status='11' WHERE id='"+string(row[0])+"'";
    		mysql_query(connection,sqlQuery.c_str());
		continue;
	    }
	    
	    // Удаление временной папки
	    boost::filesystem::remove_all(aumUploadDir);

	    
	    // Пересоздание репозитория
	    exec_cmd("pbs-hdlistgen "+username+ " "+dbOsName);
	    
	    
    	    sqlQuery="UPDATE jobs SET status='10' WHERE id='"+string(row[0])+"'";
	    mysql_query(connection,sqlQuery.c_str());
	    
	    std::cout << "Build end" << std::endl;
	    
	}
	mysql_free_result(result);

	sleep(1);
    }
    
    
    mysql_close(connection);

    return 0;
}
Ejemplo n.º 15
0
int main(int argc, char *argv[], char *envp[])
{
  int res;
/*  int i;	*/
  int num_rows;
  int status;
  const char *userp = getenv("USER");	/* vem är inloggad?	*/
  char databas[25]="olfix";
  char usr[21];				/* userid 20070212 utökat från 15 till 21 tecken */

/* ================================================================================ */
/* 		Val av databas, START						    */
/* ================================================================================ */

  status = which_database(envp);

  if (status != 0)
	exit(status);

  strncpy(usr,userp,15);			/* Den inloggades userid	*/
/*  fprintf(stderr,"status=%d ANTARG=%d len(database)=%d\n",status,ANTARG,strlen(database));	*/
  if (argc < ANTARG+1){
    	if (strlen(database)!= 0){
		strncpy(databas,database,15);
	}else{
  		strncpy(databas,"olfixtst",15);	/* olfixtst = testföretag	*/
	}
  }else{
	if (strlen(argv[ANTARG]) != 0){
  		if (strncmp(argv[ANTARG],"99",2)==0){
			strncpy(databas,"olfixtst",15);
		}else{
  			strncpy(databas,argv[ANTARG],15);
  		}
  	}
  }
/*  fprintf(stderr,"ANTARG=%d,argv[ANTARG]=%s\n",ANTARG,argv[ANTARG]);	*/
/* Om usr (userid) börjar på 'test' eller 'prov' använd databas 'olfixtst' */
  if (strncmp(usr,"test",4)==0 || strncmp(usr,"prov",4)==0 ) {
  	strncpy(databas,"olfixtst",15);
  }
/* fprintf(stderr,"Databas=%s\n",databas);	*/
/* ================================================================================ */
/* 		Val av databas, END!						    */
/* ================================================================================ */


  if (argc <2){
  	fprintf(stderr,"Error: Artikelnr saknas.\n");
	exit(-1);
  }
/*
  for (i=0;i<argc;i++){
  	fprintf(stderr,"argc=%d argv[%d]=%s\n",argc,i,argv[i]);
  }
*/
  char temp1[]="SELECT * FROM ARTIKELREG WHERE (ARTIKELNR = \"";
  char temp2[]="\"";
  char temp4[]=")";
  char temp5[200]="";
  char artikelnr[31]="";

  strncpy(artikelnr,argv[1],sizeof(artikelnr));		/*2005-02-23	*/
  fprintf(stderr,"ARDSP artikelnr = %s\n",artikelnr);
  strncpy(temp5,temp1,strlen(temp1));
/* SELECT * FROM ARTIKELREG WHERE (artikelnr = "	*/
  strncat(temp5,artikelnr,strlen(artikelnr));/* 12334 */
/* SELECT * FROM ARTIKELREG WHERE (artikelnr = "12334	*/
  strncat(temp5,temp2,strlen(temp2)); /*  "     */
/* SELECT * FROM ARTIKELREG WHERE (artikelnr = "12334"	*/
  strncat(temp5,temp4,strlen(temp4)); /*  )     */
/* SELECT * FROM ARTIKELREG WHERE (artikelnr = "12334")	*/
/*  fprintf(stderr,"ARDSP temp5 = %s\n",temp5);		*/

  mysql_init(&my_connection);
  if (mysql_real_connect(&my_connection, "localhost",  "olfix", "olfix", databas, 0, NULL, 0)){
/*  	fprintf(stdout,"ARDSP_Connection success\n");	*/
  	res = mysql_query(&my_connection,temp5);
  	if (res){
/*  		fprintf(stderr,"ARDSP ERROR\n");	*/
		fprintf(stderr,"Error: ARDSP SELECT errno: %d\n",mysql_errno(&my_connection));
        }
	else{
		res_ptr=mysql_store_result(&my_connection);
		num_rows = mysql_affected_rows(&my_connection);
/*		fprintf(stderr,"num_rows=%d\n",num_rows);	*/
/*		if (res_ptr){	*/
		if(num_rows != 0){
			sqlrow=mysql_fetch_row(res_ptr);
			fprintf(stdout,"OK: ");
			fprintf(stdout,"01:%s  ",sqlrow[0]);
			fprintf(stdout,"02:%s  ",sqlrow[1]);
			fprintf(stdout,"03:%s  ",sqlrow[2]);
			fprintf(stdout,"04:%s  ",sqlrow[3]);
			fprintf(stdout,"05:%s  ",sqlrow[4]);
			fprintf(stdout,"06:%s  ",sqlrow[5]);
			fprintf(stdout,"07:%s  ",sqlrow[6]);
			fprintf(stdout,"08:%s  ",sqlrow[7]);
			fprintf(stdout,"09:%s  ",sqlrow[8]);
			fprintf(stdout,"10:%s  ",sqlrow[9]);
			fprintf(stdout,"11:%s  ",sqlrow[10]);
			fprintf(stdout,"12:%s  ",sqlrow[11]);
			fprintf(stdout,"13:%s  ",sqlrow[12]);
			fprintf(stdout,"14:%s  ",sqlrow[13]);
			fprintf(stdout,"15:%s  ",sqlrow[14]);
			fprintf(stdout,"16:%s  ",sqlrow[15]);
			fprintf(stdout,"17:%s  ",sqlrow[16]);
			fprintf(stdout,"18:%s  ",sqlrow[17]);
			fprintf(stdout,"19:%s  ",sqlrow[18]);
			fprintf(stdout,"20:%s  ",sqlrow[19]);
			fprintf(stdout,"END:");
/*
			fprintf(stdout,"21:%s  ",sqlrow[20]);
			fprintf(stdout,"22:%s  ",sqlrow[21]);
			fprintf(stdout,"23:%s  ",sqlrow[22]);
			fprintf(stdout,"24:%s  ",sqlrow[23]);
			fprintf(stdout,"25:%s  ",sqlrow[24]);
			fprintf(stdout,"26:%s  ",sqlrow[25]);
			fprintf(stdout,"27:%s  ",sqlrow[26]);
			fprintf(stdout,"28:%s  ",sqlrow[27]);
			fprintf(stdout,"29:%s  ",sqlrow[28]);
			fprintf(stdout,"30:%s  ",sqlrow[29]);
			fprintf(stdout,"31:%s  ",sqlrow[30]);
			fprintf(stdout,"32:%s  ",sqlrow[31]);
			fprintf(stdout,"33:%s  ",sqlrow[32]);
			fprintf(stdout,"34:%s  ",sqlrow[33]);
			fprintf(stdout,"35:%s  ",sqlrow[34]);
			fprintf(stdout,"36:%s  ",sqlrow[35]);
			fprintf(stdout,"37:%s  ",sqlrow[36]);
			fprintf(stdout,"38:%s  ",sqlrow[37]);
			fprintf(stdout,"39:%s  ",sqlrow[38]);
			fprintf(stdout,"40:%s  ",sqlrow[39]);
			fprintf(stdout,"41:%s  ",sqlrow[40]);
*/
			fprintf(stdout,"\n");
		}
		else{
			fprintf(stderr,"Error: ARDSP Data saknas:  %s\n", mysql_error(&my_connection));
		}
		if (mysql_errno(&my_connection))  {
		fprintf(stderr,"Error: ARDSP Retriev error:  %s\n", mysql_error(&my_connection));
		}
	}
	mysql_free_result(res_ptr);
    	mysql_close(&my_connection);
  }
  else {
    	fprintf(stderr,"Error: ARDSP Connection failed\n");
    	if (mysql_errno(&my_connection))   {
    		fprintf(stderr,"Error: ARDSP Connection error %d:  %s\n",
			mysql_errno(&my_connection), mysql_error(&my_connection));
	}
    }
  return EXIT_SUCCESS;
}
Ejemplo n.º 16
0
fuh::~fuh() {
	mysql_close(conn);
}
Ejemplo n.º 17
0
void ObPSTest::TearDown()
{
    mysql_close(&my_);
}
Ejemplo n.º 18
0
void DBConn::Close_mysql() {
    mysql_close(&mysql);
}
Ejemplo n.º 19
0
bool MySQLConnection::Open()
{
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit)
    {
        TC_LOG_ERROR(LOG_FILTER_SQL, "Could not initialize Mysql connection to database `%s`", m_connectionInfo.database.c_str());
        return false;
    }

    int port;
    char const* unix_socket;
    //unsigned int timeout = 10;

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

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

    if (m_Mysql)
    {
        if (!m_reconnecting)
        {
            TC_LOG_INFO(LOG_FILTER_SQL, "MySQL client library: %s", mysql_get_client_info());
            TC_LOG_INFO(LOG_FILTER_SQL, "MySQL server ver: %s ", mysql_get_server_info(m_Mysql));
            // MySQL version above 5.1 IS required in both client and server and there is no known issue with different versions above 5.1
            // if (mysql_get_server_version(m_Mysql) != mysql_get_client_version())
            //     TC_LOG_INFO(LOG_FILTER_SQL, "[WARNING] MySQL client/server version mismatch; may conflict with behaviour of prepared statements.");
        }

        TC_LOG_INFO(LOG_FILTER_SQL, "Connected to MySQL database at %s", m_connectionInfo.host.c_str());
        mysql_autocommit(m_Mysql, 1);

        // set connection properties to UTF8 to properly handle locales for different
        // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
        mysql_set_character_set(m_Mysql, "utf8");
        return PrepareStatements();
    }
    else
    {
        TC_LOG_ERROR(LOG_FILTER_SQL, "Could not connect to MySQL database at %s: %s\n", m_connectionInfo.host.c_str(), mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    int rc, i;
    struct statvfs vfs;

    if (getuid() != 0) {
        fprintf(stderr, "Error: You need to run %s as root!\n", argv[0]);
        return EXIT_FAILURE;
    }

    flags = parseArgs(argc, argv);

    if (!mServer || !mUser || !mPass || !mMntPoint)
        usage(argv[0]);

    if (strcmp(mPwdType, "b64") == 0)
        mPass = strdup(unbase64(mPass));

    dumpArgs();

    if (flagIsSet(FLAG_UNMOUNT) || (flagIsSet(FLAG_FORCE))) {
        rc = unmount( replace(argv[0], "./", ""), mMntPoint, flagIsSet(FLAG_FORCE) );

        if (flagIsSet(FLAG_UNMOUNT))
            return rc;

        if ((rc != 0) && (flagIsSet(FLAG_UNMOUNT)))
            fprintf(stderr, "Warning: Error unmounting mountpoint %s\n", mMntPoint);
    }

    if (statvfs(mMntPoint, &vfs) == 0) {
        if (vfs.f_fsid == 0) { /* Observed when mounted (FUSE mount) */
            fprintf(stderr, "Path %s seems to be already mounted. Cannot "
                    "continue. Quiting...\n", mMntPoint);
            return EXIT_FAILURE;
        }
    }

    if (mysql_init(&sql) == NULL)
        return EXIT_FAILURE;

    if (!mysql_real_connect(&sql, mServer, mUser, mPass, NULL, 0, NULL, 0)) {
        fprintf(stderr, "MySQL connection error: %s (%d)\n", mysql_error(&sql),
                mysql_errno(&sql));
        mysql_close(&sql);
        return EXIT_FAILURE;
    }

    /* Unset all the arguments for fuse_main */
    for (i = 1; i > argc; i++)
        free(argv[i]);
    argc = 2;
    /* Set only the mountpoint argument */
    argv[1] = mMntPoint;

    printf("Process %s started successfully\n", argv[0]);

    rc = fuse_main(argc, argv, &fmysql_oper, NULL);
    mysql_close(&sql);

    return rc;
}
void finish_with_error(MYSQL *con)
{
	sprintf(dbError, "%s\n", mysql_error(con));
	mysql_close(con);
	        
}
Ejemplo n.º 22
0
/**
Connect to the server with options given by arguments to this application,
stored in global variables opt_host, opt_user, opt_password, opt_db, 
opt_port and opt_unix_socket.

@param flag[in]           client_flag passed on to mysql_real_connect
@param protocol[in]       MYSQL_PROTOCOL_* to use for this connection
@param auto_reconnect[in] set to 1 for auto reconnect
   
@return pointer to initialized and connected MYSQL object
*/
static MYSQL* client_connect(ulong flag, uint protocol, my_bool auto_reconnect)
{
 MYSQL* mysql;
 int  rc;
 static char query[MAX_TEST_QUERY_LENGTH];
 myheader_r("client_connect");

 if (!opt_silent)
 fprintf(stdout, "\n Establishing a connection to '%s' ...",
 opt_host ? opt_host : "");

 if (!(mysql= mysql_client_init(NULL)))
 {
   opt_silent= 0;
   myerror("mysql_client_init() failed");
   exit(1);
 }
 /* enable local infile, in non-binary builds often disabled by default */
 mysql_options(mysql, MYSQL_OPT_LOCAL_INFILE, 0);
 mysql_options(mysql, MYSQL_OPT_PROTOCOL, &protocol);
 if (opt_plugin_dir && *opt_plugin_dir)
 mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);

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

 if (!opt_secure_auth)
 mysql_options(mysql, MYSQL_SECURE_AUTH, (char*)&opt_secure_auth);

 if (!(mysql_real_connect(mysql, opt_host, opt_user,
 opt_password, opt_db ? opt_db:"test", opt_port,
 opt_unix_socket, flag)))
 {
   opt_silent= 0;
   myerror("connection failed");
   mysql_close(mysql);
   fprintf(stdout, "\n Check the connection options using --help or -?\n");
   exit(1);
 }
 mysql->reconnect= auto_reconnect;

 if (!opt_silent)
 fprintf(stdout, "OK");

 /* set AUTOCOMMIT to ON*/
 mysql_autocommit(mysql, TRUE);

 if (!opt_silent)
 {
   fprintf(stdout, "\nConnected to MySQL server version: %s (%lu)\n",
   mysql_get_server_info(mysql),
   (ulong) mysql_get_server_version(mysql));
   fprintf(stdout, "\n Creating a test database '%s' ...", current_db);
 }
 strxmov(query, "CREATE DATABASE IF NOT EXISTS ", current_db, NullS);

 rc= mysql_query(mysql, query);
 myquery(rc);

 strxmov(query, "USE ", current_db, NullS);
 rc= mysql_query(mysql, query);
 myquery(rc);
 have_innodb= check_have_innodb(mysql);

 if (!opt_silent)
 fprintf(stdout, "OK");

 return mysql;
}
Ejemplo n.º 23
0
// disconnect from mysql
void CDatabase::Disconnect( )
{
     Log(MSG_INFO,"Closing mysql");
    mysql_close( Mysql );
}
Ejemplo n.º 24
0
/*	free Mysql class object		*/
static void free_mysql(struct mysql* my)
{
    if (my->connection == Qtrue)
	mysql_close(&my->handler);
    xfree(my);
}
CppMysqlConn::~CppMysqlConn()
{
		mysql_close(&this->mObj);
}
Ejemplo n.º 26
0
/*
create table `toplog` (
 `id` int unsigned NOT NULL auto_increment,
 `userid` char(15) NOT NULL default '',
 `bname` char(31) NOT NULL default '',
 `title` char(81) NOT NULL default '',
 `time` timestamp NOT NULL,
 `date` date NOT NULL,
 `topth` int NOT NULL default '1',
 `count` int NOT NULL default '0',
 `threadid` int unsigned NOT NULL default '0',
 PRIMARY KEY (`id`),
 KEY userid (`userid`),
 KEY bname(`bname`, `threadid`),
 KEY date(`date`),
 UNIQUE top (`date`,`topth`)
) TYPE=MyISAM COMMENT='toplog';

create table `toplog_all` (
 `id` int unsigned NOT NULL auto_increment,
 `userid` char(15) NOT NULL default '',
 `bname` char(31) NOT NULL default '',
 `title` char(81) NOT NULL default '',
 `time` timestamp NOT NULL,
 `date` date NOT NULL,
 `topth` int NOT NULL default '1',
 `count` int NOT NULL default '0',
 `threadid` int unsigned NOT NULL default '0',
 PRIMARY KEY (`id`),
 KEY userid (`userid`),
 KEY bname(`bname`, `threadid`),
 KEY date(`date`),
) TYPE=MyISAM COMMENT='toplog_all';
*/
int log_top()
{
    MYSQL s;
    char sqlbuf[500];
    char newtitle[161];
    int i;
    char newts[20];
    time_t now;
    struct tm ptime;

    mysql_init(&s);

    if (! my_connect_mysql(&s)) {
        return 0;;
    }

    for (i=0;i<topnum;i++) {

        mysql_escape_string(newtitle, top[i].title, strlen(top[i].title));

#ifdef NEWSMTH
        MYSQL_RES *res;
        MYSQL_ROW row;
        sprintf(sqlbuf, "SELECT id FROM toplog_all WHERE date=CURDATE() AND bname='%s' AND threadid=%d; ", top[i].board, top[i].groupid);
        if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) {
            printf("%s\n", mysql_error(&s));
        } else {
            res = mysql_store_result(&s);
            row = mysql_fetch_row(res);
            if (row==NULL) {
                char title[STRLEN],file[STRLEN];
                // auto post top10 to ShiDa
                sprintf(title, "[%s] %s", top[i].board,top[i].title);
                sprintf(file, "boards/%s/%s", top[i].board,top[i].filename);
                post_file(NULL, "", file , "ShiDa", title, 0, 1, getSession());
                // insert into toplog_all
                sprintf(sqlbuf, "INSERT INTO toplog_all VALUES (NULL,'%s','%s','%s','%s',CURDATE(),'%d','%d','%d');",top[i].userid, top[i].board, newtitle, tt2timestamp(top[i].date,newts), i+1, top[i].number, top[i].groupid);
                if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) {
                    printf("%s\n", mysql_error(&s));
                }
            } else {
                // update toplog_all
                sprintf(sqlbuf,"UPDATE toplog_all SET userid='%s',bname='%s',title='%s',count='%d',time='%s',threadid='%d' WHERE date=CURDATE() AND bname='%s' AND threadid=%d;;", top[i].userid, top[i].board, newtitle, top[i].number, tt2timestamp(top[i].date,newts), top[i].groupid, top[i].board, top[i].groupid);
                if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) {
                    printf("%s\n", mysql_error(&s));
                }
            }
        }
        time(&now);
        ptime = *localtime(&now);
        if (ptime.tm_hour == 23) {
            total_post_top10(top[i].groupid,top[i].board,top[i].title);
        }
#endif

        sprintf(sqlbuf,"UPDATE toplog SET userid='%s',bname='%s',title='%s',count='%d',time='%s',threadid='%d' WHERE date=CURDATE() AND topth='%d';", top[i].userid, top[i].board, newtitle, top[i].number, tt2timestamp(top[i].date,newts), top[i].groupid, i+1);

        if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) {
            printf("%s\n", mysql_error(&s));
            continue;
        }
        if ((int)mysql_affected_rows(&s) <= 0) {
            sprintf(sqlbuf, "INSERT INTO toplog VALUES (NULL,'%s','%s','%s','%s',CURDATE(),'%d','%d','%d');",top[i].userid, top[i].board, newtitle, tt2timestamp(top[i].date,newts), i+1, top[i].number, top[i].groupid);
            if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) {
                printf("%s\n", mysql_error(&s));
                continue;
            }
        }
    }

    mysql_close(&s);

    return 1;
}
Ejemplo n.º 27
0
Archivo: child.c Proyecto: xiu/child
int main(int argc, char **argv)
{
    startuptime = time(NULL);

    InitMem();

    int retval,mysql_lastconn,newfd,i,lastcheck,lastcheck2,nbfd;
    struct sockaddr_storage sa;
    socklen_t salen = sizeof(sa);
    Eclient *eclient;

    indata.nextline = indata.chunkbufentry = indata.chunkbuf;

    emerg = emerg_req = 0;

    eos = raws = verbose = vv = 0;
    int daemonize = 1;
    char op = 0;
    me.retry_attempts = me.nextretry = me.connected = 0;

    struct sigaction sig, old;
    memset(&sig,0,sizeof(sig));
    sig.sa_handler = sighandler;
    sigaction(SIGHUP,&sig,&old);
#ifdef USE_FILTER
    sigaction(SIGUSR1,&sig,&old);
#endif
    sigaction(SIGUSR2,&sig,&old);
    sigaction(SIGINT,&sig,&old);
    sigaction(SIGCHLD,&sig,&old);
    sigaction(SIGPIPE,&sig,&old);

    struct rlimit rlim;
    if ((getrlimit(RLIMIT_CORE, &rlim)) == -1) {
        perror("getrlimit");
        return -1;
    }
    rlim.rlim_cur = RLIM_INFINITY;
    if ((setrlimit(RLIMIT_CORE, &rlim)) == -1) {
        perror("setrlimit");
        return -1;
    }

    /* Setting default values */

    strcpy(me.nick,"C");
    strcpy(me.name,"services.geeknode.org");
    strcpy(me.ident,"cserve");
    strcpy(me.host,"geeknode.org");
    strcpy(me.linkpass,"f00p4ss");
    strcpy(me.mysql_host,"localhost");
    strcpy(me.mysql_db,"child");
    strcpy(me.mysql_login,"child");
    strcpy(me.mysql_passwd,"childp4ss");
    strcpy(me.logfile,"child.log");
    strcpy(me.guest_prefix,"Geek");
    strcpy(me.pl_logfile,"partyline.log");
    strcpy(me.sendmail,"/usr/sbin/sendmail -t");
    strcpy(me.sendfrom,"*****@*****.**");
    strcpy(me.usercloak,".users.geeknode.org");
    bzero(me.mysql_anope_host,32);
    bzero(me.mysql_anope_db,32);
    bzero(me.mysql_anope_login,32);
    bzero(me.mysql_anope_passwd,32);
    bzero(me.bindip,32);
    me.port = 4400;
    me.maxclones = 5;
    me.nick_expire = 45;
    me.chan_expire = 60;
    me.chanperuser = 10;
    me.level_oper = 100;
    me.level_admin = 500;
    me.level_root = 900;
    me.level_owner = 1000;
    me.limittime = 5;
    me.savedb_interval = 60;
    me.listen_port = 0;
#ifdef USE_GNUTLS
    me.ssl = 0;
#endif
    me.enable_exec = 0;
    me.anonymous_global = 0;
    me.maxmsgtime = 2;
    me.maxmsgnb = 5;
    me.ignoretime = 60;
    me.maxloginatt = 3;
    me.chlev_sadmin = 20;
    me.chlev_admin = 10;
    me.chlev_op = 5;
    me.chlev_halfop = 4;
    me.chlev_voice = 3;
    me.chlev_invite = 1;
    me.chlev_nostatus = -1;
    me.chlev_akick = -2;
    me.chlev_akb = -3;
    me.anopemd5 = 0;
#ifdef USE_FILTER
    me.filter = 0;
#endif
    me.emailreg = 0;

    /* -- */

    int ladb=0,cdb=0;

    while ((op = getopt(argc,argv,"acdhv")) != EOF) {
        switch(op) {
            case 'a':
                ladb = 1;
                break;
            case 'c':
                cdb = 1;
                break;
            case 'd':
                daemonize = 0;
                break;
            case 'v':
                if (verbose)
                    vv = 1;
                else
                    verbose = 1;
                break;
            case 'h':
            default:
                usage(argv[0]);
        }
    }

    loadconf(0);
#ifdef USE_FILTER
    if (me.filter)
        loadrulefile();
#endif

    if (ladb) {
        if (!connect_to_db()) {
            printf("Cannot connect to db\n");
            child_clean();
        }

        loadalldb();
        mysql_close(&mysql);

        if (!connect_to_anope_db()) {
            printf("Cannot connect to anope db\n");
            child_clean();
        }

        printf("Loading anope database... ");
        fflush(stdout);

        loadanopedb();
        mysql_close(&mysql2);
        printf("done.\n");
        printf("Saving databases... ");
        fflush(stdout);
        savealldb();
        printf("done.\n");
        printf("Anope database converted\n");
        child_clean();
    }

    if (cdb) {
        if (!connect_to_db()) {
            printf("Cannot connect to db\n");
            child_clean();
        }

        printf("Creating databases ... ");
        fflush(stdout);
        char tmp[512];
        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_chans` (chname varchar(50) not null, founder varchar(50) not null, entrymsg blob not null, options int not null, mlock varchar(32) not null, autolimit int not null, lastseen int not null, regtime int not null, topic blob not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_chan_access` (chname varchar(50) not null, username varchar(255) not null, level int not null, automode int not null default 1, suspended int not null, uflags int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_trusts` (hostname varchar(255) not null, clones int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_users` (username varchar(50) not null, authlevel int not null, seen int not null, vhost varchar(200) not null, md5_pass varchar(32) not null, options int not null, timeout int not null, email varchar(100) not null, regtime int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_links` (master varchar(50) not null, slave varchar(50) not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_botserv_bots` (name varchar(50) not null, ident varchar(50) not null, host varchar(50) not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_botserv_chans` (chan varchar(50) not null, bot varchar(50) not null)");
        mysql_query(&mysql,tmp);

        RunHooks(HOOK_CREATEDB,NULL,NULL,NULL,NULL);

        printf(" done.\n");
        mysql_close(&mysql);
        child_clean();
    }

    if (me.listen_port) {
        if (!Bind()) {
            fprintf(stderr,"Error while binding\n");
            child_clean();
        }
        pllog("Partyline created");
    }

    retval = ConnectToServer();
    switch(retval) {
        case -1:
            fprintf(stderr,"Failed to connect to %s:%d (connection timed out)\n",me.server,me.port);
            operlog("Failed to connect to %s:%d (connection timed out)",me.server,me.port);
            child_clean();
        case 0:
            fprintf(stderr,"Failed to connect to %s:%d",me.server,me.port);
            operlog("Failed to connect to %s:%d",me.server,me.port);
            child_clean();
    }

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

    if (!connect_to_db()) {
        fprintf(stderr,"Cannot connect to mysql\n");
        operlog("Cannot connect to mysql db");
        child_clean();
    }

    if (verbose) printf("Connected to mysql DB\n");
    loadalldb();
    mysql_close(&mysql);
    if (verbose) printf("Logging in to server\n");
    SendInitToServer();
    me.connected = 1;
    if (verbose) printf("Logged in to server\n");

    SendRaw("EOS");

    lastcheck = lastcheck2 = mysql_lastconn = time(NULL);
    if (daemonize) daemon(1,0);
    write_pid();

    nbfd = build_poll();
    struct pollfd pfdout;
    pfdout.fd = sock;
    pfdout.events = POLLOUT;
    pfdout.revents = 0;

    while(1) {
        if (outdata.writebytes > 0) {
            retval = poll(&pfdout,1,1000);
            if (retval > 0 && (pfdout.revents & POLLOUT))
                flush_sendq();
        }
        retval = poll(ufds,nbfd,1000);
        if (retval > 0) {
            for (i=0;i<nbfd;i++) {
                if (ufds[i].revents & (POLLIN | POLLPRI)) {
                    switch(i) {
                        case 0:
                            if (!ReadChunk()) {
                                if (!me.connected || !eos) break;
                                operlog("Connection reset by peer");
                                savealldb();
                                eos = me.retry_attempts = me.connected = 0;
                                me.nextretry = time(NULL)+1;
                                cleanup_reconnect();
                                close(sock);
                                break;
                            }
                            while (GetLineFromChunk())
                                ParseLine();
                            break;
                        case 1:
                            if (!me.listen_port) break;
                            newfd = accept(esock,(struct sockaddr *)&sa,&salen);
                            if (eclient_list.size+1 >= ECL_MAXSOCK) {
                                close(newfd);
                                break;
                            }
                            fcntl(newfd,F_SETFL,O_NONBLOCK);
                            eclient = AddEclient(newfd,sa,salen);
                            sendto_all_butone(eclient,"*** Connection from %s (%s)",eclient->host,eclient->addr);
                            nbfd = build_poll(); i++;
                            break;
                        default:
                            eclient = find_eclient(ufds[i].fd);
                            if (!eclient) break;
                            int oldnbfd = nbfd;
                            int old_eclient_size = eclient_list.size;
                            if (!ReadPChunk(eclient)) {
                                if (eclient->authed == 1)
                                    sendto_all_butone(eclient,"*** User %s (%s) logged out (Connection reset by peer)",eclient->nick,eclient->host);
                                else
                                    sendto_all_butone(eclient,"*** Lost connection from %s",eclient->host);
                                close(eclient->fd);
                                DeleteEclient(eclient);
                                nbfd = build_poll();
                                i--;
                                break;
                            }
                            int tmpfd = eclient->fd;
                            while (GetLineFromPChunk(tmpfd))
                                ParseEclient(eclient);
                            if (old_eclient_size > eclient_list.size)
                                nbfd = build_poll();
                            if (nbfd < oldnbfd) i -= (oldnbfd - nbfd);
                            break;
                    }
                }
            }
        }

        int timenow = time(NULL);

        if (!me.connected && timenow - me.nextretry >= 0) {
            retval = ConnectToServer();
            if (retval == -1 || retval == 0) {
                me.retry_attempts++;
                operlog("Reconnecting attempt #%d failed (%s)",me.retry_attempts,retval ? "timeout" : "error");
                if (me.retry_attempts >= MAX_RECO_ATTEMPTS) {
                    operlog("Maximum reconnection attempts reached, exiting");
                    savealldb();
                    unloadallmod();
                    CloseAllSock();
                    child_clean();
                }
                me.nextretry = timenow + RECONNECT_DELAY;
            } else {
                SendInitToServer();
                me.connected = 1;
                me.nextretry = 0;
                SendRaw("EOS");
                operlog("Reconnected");
            }
            if (me.connected) continue;
        }

        if (timenow - mysql_lastconn >= 60*me.savedb_interval) {
            savealldb();
            mysql_lastconn = timenow;
        }

        if (timenow - lastcheck >= 1) {
            CheckGuests();
            CheckLimits();
            CheckTB();
            lastcheck = timenow;
        }

        if (timenow - lastcheck2 >= 60) {
            checkexpired();
            lastcheck2 = timenow;
        }
    }

    operlog("Program shouldn't reach this piece of code, WTF ? Saving DBs and exiting.");
    savealldb();
    unloadallmod();
    CloseAllSock();
    child_clean();

    return 0;
}
Ejemplo n.º 28
0
/**
 * 功能:添加分享资源
 * 参数:resource_share - 分享资源结构体
 *	返回值:添加成功返回0,失败返回1,数据库内部错误返回-1
 */
int add_share_resource(const struct resource_share *res)
{
	
	MYSQL *mysql = NULL;
	char query_str[512];
	int affect_rows;
	if(mysql == NULL) {
		mysql = open();
	}
	
	/* insert into tbl_resoure */
	sprintf(query_str,"INSERT INTO tbl_resource(f_res_name,\
		f_res_size,f_res_md5,f_res_piececount) VALUES('%s',\
		'%s','%s','%d')", res->name,res->size,res->md5,res->piececount);
	if(mysql_query(mysql,query_str)) {
		fprintf(stderr,"Error: %s\n",mysql_error(mysql));
	}
	
	/* get sharetime */
	char *sharetime;
	sharetime = get_curr_time();

	/* insert into tbl_resource_owner */
	if(strlen(res->mac) <= 0) {

		mysql_close(mysql);
		return 0;
	}
	memset(query_str,'\0',sizeof(query_str));
	sprintf(query_str,"INSERT INTO tbl_resource_owner(f_res_md5,\
		f_res_owner,f_res_sharetime) VALUES('%s','%s','%s')",res->md5
		,res->mac,sharetime);
	if(mysql_query(mysql,query_str)) {
		fprintf(stderr,"Error: %s\n",mysql_error(mysql));
	}


	/* insert into tbl_resource_tags */
	if(strlen(res->tag) <= 0) {

		mysql_close(mysql);
		return 0;
	}
	const char *sp = TAG_SEPERATOR;
	char *tag = NULL;
	char key[512];

	int tag_failed = 0;
	strcpy(key,res->tag);
	tag = strtok(key,sp);
	while(tag) {
		memset(query_str,'\0',sizeof(query_str));
		sprintf(query_str,"INSERT INTO tbl_resource_tags(f_res_md5,\
			f_res_tags) VALUES('%s','%s')",res->md5,tag);
		if(mysql_query(mysql,query_str)) {
			fprintf(stderr,"Error: %s\n",mysql_error(mysql));

			mysql_close(mysql);
			return -1;
		}
		affect_rows = mysql_affected_rows(mysql);
		if(affect_rows < 0) {
			tag_failed = 1;
		}

		tag = strtok(NULL,sp);
	}

	mysql_close(mysql);

	return tag_failed == 1 ? -1:0;
}
Ejemplo n.º 29
0
int main() {
  MYSQL_ROW row;
  MYSQL_RES *result;
  int i;
  char query[1024];

  int hdr;
#define HDR ((struct header *)(buf+hdr))

  if (!(conn = mysql_init(NULL))) return -1;
  mysql_options(conn, MYSQL_SET_CHARSET_NAME, "utf8");
  if (!mysql_real_connect(conn, "localhost", DBUSER, DBPASS, "pismo", 0, MYSQL_SOCKET, 0)) {
    fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(conn));
    return -2;
  }

  buf_init();
  hdr = buf_alloc(sizeof(struct header));
  HDR->signature = SIGNATURE;

  mysql_query(conn, "select o.id, o.spis, coalesce(o.alias,''), max(coalesce(t._1,0)), min(coalesce(t.id,1000000))-1, max(coalesce(t.id,-1))-1 "
      "from doc_biblia_obsah o left outer join doc_biblia_text t on o.id=t._0 "
      "group by o.id, o.spis, coalesce(o.alias,'') "
      "order by o.id asc");
  result = mysql_store_result(conn);
  HDR->n_knihy = mysql_num_rows(result);
  ASGN(HDR->knihy, buf_alloc(HDR->n_knihy * sizeof(struct kniha)));
#define KNH ((struct kniha *)(buf+HDR->knihy))
  i=0;
  while ((row = mysql_fetch_row(result))) {
    int j;

    sscanf(row[0], "%d", &j);
    if (i!=j-1) { fprintf(stderr, "nesuvisle id\n"); exit(1); }

    ASGN(KNH[i].meno, buf_add(row[1], strlen(row[1])+1));
    ASGN(KNH[i].alias, buf_add(row[2], strlen(row[2])+1));
    sscanf(row[3], "%d", &KNH[i].n_hlav);
    sscanf(row[4], "%d", &KNH[i].min);
    sscanf(row[5], "%d", &KNH[i].max);
    ASGN(KNH[i].hlava, buf_alloc(sizeof(struct hlava)*KNH[i].n_hlav));

    for (j=0; j<KNH[i].n_hlav; j++) {
      MYSQL_ROW row2;
      MYSQL_RES *result2;
      int k;
#define HLV ((struct hlava *)(buf+KNH[i].hlava))

      sprintf(query, "select min(coalesce(t.id,1000000))-1, max(coalesce(t.id,-1))-1 "
          "from doc_biblia_text t "
          "where t._0=%d and t._1=%d", i+1, j+1);
      mysql_query(conn, query);
      result2 = mysql_store_result(conn);
      row2 = mysql_fetch_row(result2);
      sscanf(row2[0], "%d", &HLV[j].min);
      sscanf(row2[1], "%d", &HLV[j].max);
      // printf("kniha %d, hlava %d, min %d, max %d\n", i, j, HLV[j].min, HLV[j].max);
      mysql_free_result(result2);

      sprintf(query, "select t._2, min(t.id)-1, max(t.id)-1 "
          "from doc_biblia_text t "
          "where t._0=%d and t._1=%d and t._2 is not null group by t._2", i+1, j+1);
      mysql_query(conn, query);
      result2 = mysql_store_result(conn);
      HLV[j].n_versov = mysql_num_rows(result2);
      // if (!HLV[j].n_versov) printf("kniha = %s; hlava = %d; versov=%d\n", row[1], j, HLV[j].n_versov);
      ASGN(HLV[j].vers, buf_alloc(sizeof(struct vers)*HLV[j].n_versov));

      for (k=0; k < HLV[j].n_versov; k++) {
        int l;
#define VRS ((struct vers *)(buf+HLV[j].vers))
        row2 = mysql_fetch_row(result2);
        sscanf(row2[0], "%d", &l);
        if (l-1 != k) { fprintf(stderr, "nesuvisle id versa k=%d h=%d v=%d!=%d\n", i+1, j+1, l, k+1); exit(1); }
        sscanf(row2[1], "%d", &VRS[k].min);
        sscanf(row2[2], "%d", &VRS[k].max);
        // printf("k=%d min=%d=%s max=%d=%s\n", k, VRS[k].min, row2[1], VRS[k].max, row2[2]);
      }

      mysql_free_result(result2);
    }

    i++;
  }
  mysql_free_result(result);

  mysql_query(conn, "select max(coalesce(id,0)) from doc_biblia_text where _0 is not null order by id asc");
  result = mysql_store_result(conn);
  row = mysql_fetch_row(result);
  sscanf(row[0], "%d", &HDR->n_text);
  mysql_free_result(result);

  mysql_query(conn, "select id, _0-1, coalesce(_1, 0)-1, coalesce(_2, 0)-1, coalesce(html,'') from doc_biblia_text where _0 is not null order by id asc");
  result = mysql_store_result(conn);
  i=0;
  ASGN(HDR->text, buf_alloc(sizeof(struct text)*HDR->n_text));
#define TXT ((struct text *)(buf+HDR->text))
  while ((row = mysql_fetch_row(result))) {
    int j;

    sscanf(row[0], "%d", &j);
    while (i<j-1) {
      TXT[i].k = TXT[i].h = TXT[i].v = -1;
      ASGN(TXT[i].t, buf_add("", 1));
      i++;
    }
    sscanf(row[1], "%d", &TXT[i].k);
    sscanf(row[2], "%d", &TXT[i].h);
    sscanf(row[3], "%d", &TXT[i].v);
    ASGN(TXT[i].t, buf_add(row[4], strlen(row[4])+1));
    // printf("txt %d = %s\n", i, row[4]);
    i++;
  }
  mysql_free_result(result);

  mysql_query(conn, "select max(coalesce(id,0)) from doc_biblia_ppc order by id asc");
  result = mysql_store_result(conn);
  row = mysql_fetch_row(result);
  sscanf(row[0], "%d", &HDR->n_ppc);
  mysql_free_result(result);

  mysql_query(conn, "select id, coalesce(html,'') from doc_biblia_ppc order by id asc");
  result = mysql_store_result(conn);
  i=0;
  ASGN(HDR->ppc, buf_alloc(sizeof(int32_t)*HDR->n_ppc));
#define PPC ((int32_t *)(buf+HDR->ppc))
  while ((row = mysql_fetch_row(result))) {
    int j;

    sscanf(row[0], "%d", &j);
    while (i<j-1) {
      ASGN(PPC[i], buf_add("", 1));
      i++;
    }
    ASGN(PPC[i], buf_add(row[1], strlen(row[1])+1));
    i++;
  }
  mysql_free_result(result);

  mysql_query(conn, "select datum, zalm, citania from liturgicke_citania order by datum asc");
  result = mysql_store_result(conn);
  HDR->n_kalendar = mysql_num_rows(result);
  ASGN(HDR->kalendar, buf_alloc(sizeof(struct kalendar)*HDR->n_kalendar));
#define KAL ((struct kalendar *)(buf+HDR->kalendar))
  i = 0;
  while ((row = mysql_fetch_row(result))) {
    sscanf(row[0], "%d-%d-%d", &KAL[i].y, &KAL[i].m, &KAL[i].d);
    ASGN(KAL[i].zalm, buf_add(row[1], strlen(row[1])+1));
    ASGN(KAL[i].text, buf_add(row[2], strlen(row[2])+1));
    i++;
  }
  mysql_free_result(result);

  for (i=0; i<TABLES; i++) {
    int j;
    int min = (1<<i);
    int max = (i==TABLES-1) ? (1<<30) : (1<<(i+1))-1;
    sprintf(query, "(select 0, id-1, start-1 as start, end-1 from doc_biblia_text "
        "where end-start+1>=%d and end-start+1<=%d) union "
        "(select 1, id-1, start-1, end-1 from doc_biblia_ppc "
        "where end-start+1>=%d and end-start+1<=%d) order by start asc", min, max, min, max);
    mysql_query(conn, query);
    result = mysql_store_result(conn);

    HDR->n_item[i] = mysql_num_rows(result);
    ASGN(HDR->item[i], buf_alloc(sizeof(struct item)*HDR->n_item[i]));
#define ITM ((struct item *)(buf+HDR->item[i]))

    j = 0;
    while ((row = mysql_fetch_row(result))) {
      sscanf(row[0], "%d", &ITM[j].comment);
      sscanf(row[1], "%d", &ITM[j].id);
      sscanf(row[2], "%d", &ITM[j].b);
      sscanf(row[3], "%d", &ITM[j].e);
      j++;
    }
  }

  dump("pismo.bin");
  mysql_close(conn);
  return 0;
}
Ejemplo n.º 30
0
 void operator()(MYSQL* mysql)
 {
     if (mysql)
         mysql_close(mysql);
 }