Exemplo n.º 1
0
Arquivo: conn.c Projeto: llxp/llxp
int main (int argc, char* argv[])
{
    int i, c, option_index;
    char databases[15][30];


    char *pass = NULL;
    char *user = NULL;
    char *host = NULL;
    char *sock = NULL;
    unsigned int port = 0;

    // needs for operations required by load_defaults().
    my_init();
    // reads /etc/.my.cnf or ${HOME}/.my.cnf file
    load_defaults("my",groups,&argc,&argv);

    // allows assigning values for host, pass...
    while((c=getopt_long(argc,argv,"h:p:u:P:S:",long_options,
                    &option_index)) != EOF)
    {
        switch(c)
        {
            case 'h':
                host = optarg;
                break;
            case 'u':
                user = optarg;
                break;
            case 'p':
                pass = optarg;
                break;
            case 'P':
                port = (unsigned int) atoi(optarg);
                break;
            case 'S':
                sock = optarg;
                break;
        }
    }

    //=================================================
    if ( (conn = mysql_init(NULL)) == NULL)
    {
        print_error("mysql_init()");
        exit (EXIT_FAILURE);
    }
    if ( (mysql_real_connect(conn,host,user,pass,"",0,NULL,0))
                == NULL)
    {
        print_error("mysql_real_connect()");
        exit (EXIT_FAILURE);
    }
    mysql_query(conn,"show databases");
    res = mysql_store_result(conn);

    i=0;
    system("clear");
    printf("\nThere are %lu databases\n",how_rows());
    puts("=====================");

    while ( row = mysql_fetch_row(res) )
    {
        strcpy(databases[i],row[0]);
        puts(databases[i]);
        i++;
    }
    mysql_close(conn);
    return 0;

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

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

  int r= cluster_connection->connect(5 /* retries               */,
				     3 /* delay between retries */,
				     1 /* verbose               */);
  if (r > 0)
  {
    std::cout
      << "Cluster connect failed, possibly resolved with more retries.\n";
    exit(-1);
  }
  else if (r < 0)
  {
    std::cout
      << "Cluster connect failed.\n";
    exit(-1);
  }
					   
  if (cluster_connection->wait_until_ready(30,30))
  {
    std::cout << "Cluster was not ready within 30 secs." << std::endl;
    exit(-1);
  }
  // connect to mysql server
  MYSQL mysql;
  if ( !mysql_init(&mysql) ) {
    std::cout << "mysql_init failed\n";
    exit(-1);
  }
  if ( !mysql_real_connect(&mysql, "localhost", "root", "", "",
			   0, mysqld_sock, 0) )
    MYSQLERROR(mysql);
  
  /********************************************
   * Connect to database via mysql-c          *
   ********************************************/
  mysql_query(&mysql, "CREATE DATABASE ndb_examples");
  if (mysql_query(&mysql, "USE ndb_examples") != 0) MYSQLERROR(mysql);
  create_table(mysql);

  Ndb* myNdb= new Ndb( cluster_connection,
		       "ndb_examples" );  // Object representing the database
  
  if (myNdb->init() == -1) {
    APIERROR(myNdb->getNdbError());
    exit(-1);
  }

  const NdbDictionary::Dictionary* myDict= myNdb->getDictionary();
  const NdbDictionary::Table *myTable= myDict->getTable("api_retries");
  if (myTable == NULL)
  {
    APIERROR(myDict->getNdbError());
    return -1;
  }
  /************************************
   * Execute some insert transactions *
   ************************************/
   
  std::cout << "Ready to insert rows.  You will see notices for temporary "
    "errors, permenant errors, and retries. \n";
  for (int i = 10000; i < 20000; i++) {
    executeInsertTransaction(i, myNdb, myTable);
  }
  std::cout << "Done.\n";
  
  delete myNdb;
  delete cluster_connection;
    
  ndb_end(0);
  return 0;
}
Exemplo n.º 3
0
int open(struct libdb *dbp)
{
	if(NULL != dbp)
	{
		int dbType = dbp->db_type;
			int result = 0;
			switch(dbType)
			{
			case DB_ORACLE://oracle database connect
				{
					if(is_open(dbp))
					{
						result = 1;
						break;//The connection is built up, you do not need to repeat the connection
					}
					if(dbp->db_orap != NULL)
					{
						int ret, len;
						struct oracle *orap = dbp->db_orap;
						ret = sqlo_init(orap->ora_mode, orap->ora_num, orap->ora_cur);
						if(SQLO_SUCCESS != ret)
						{
							result = 0;
							set_error_d(dbp, "Failed to initialize the libsqlora8 Library:");
							break;
						}
						char *connp = NULL;
						analyse(dbp, connp);
						if((len=strlen(connp))<=0)
							break;
						connp[len-1]='\0';
						sqlo_db_handle_t *dbhp = &dbp->db_orap->ora_dbhp;
						ret = sqlo_connect(dbhp, connp);
						if(SQLO_SUCCESS != ret)
						{
							const char *error = sql_geterror();
							result = 0;
							dbp->db_errorp = "Failed to initialize the oracle Library:%s";
							int alen = len+strlen(error);
							dbp->db_errorp.resize(alen+1);
							snprintf(&dbp->db_errorp[0], alen, "Failed to initialize the oracle Library:%s", error);
							break;
						}
						sqlo_set_autocommit(dbp->db_orap->ora_dbhp, SQLO_OFF);
						result = 1;
					}
				}
				break;
			case DB_MYSQL://MySql database connect
				{
					if(is_open(dbp))
					{
						result = 1;
						break;//The connection is built up, you do not need to repeat the connection
					}
					if(dbp->db_sqlp != NULL)
					{
						MYSQL *retp = NULL ;
						retp = mysql_init(dbp->db_sqlp->mys_sqlp);
						if(NULL == retp)
						{
							result = 0;
							set_error_d(dbp, "mysql_init");
							break;
						}
						char *connp = NULL;
						analyse(dbp, connp);
						struct mysql *sqlp = dbp->db_sqlp;
						retp = mysql_real_connect(
								sqlp->mys_sqlp,              //pointer to MySql
								sqlp->mys_hostp,             //host name
								sqlp->mys_userp,             //user name
								sqlp->mys_pwdp,              //user password
								sqlp->mys_dbp,               //database name
								sqlp->mys_port,              //the port
								sqlp->mys_socketp,           //the socket
								sqlp->mys_flags              //the flags of client
							);
						if(NULL == retp)
						{
							result = 0;
							set_error_d(dbp, "mysql_real_connect");
							break;
						}
						int ret = -1;
						ret = mysql_autocommit(dbp->db_sqlp->mys_sqlp, 0);
						if(0 != ret)
						{
							result = 0;
							set_error_d(dbp, "mysql_autocommit");
							break;
						}
						result = 1;
					}
				}
				break;
			default:
				{
					result = 0;
					set_error_d(dbp, "The system is not support the database.");
				}
				break;
			}
			return result;
	}
	return 0;
}
Exemplo n.º 4
0
void *process_queue(struct thread_data *td) {
	struct configuration *conf= td->conf;
	g_mutex_lock(init_mutex);
	MYSQL *thrconn= mysql_init(NULL);
	g_mutex_unlock(init_mutex);

	configure_connection(thrconn,"myloader");

	if (!mysql_real_connect(thrconn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Failed to connect to MySQL server: %s", mysql_error(thrconn));
		exit(EXIT_FAILURE);
	}

	if (mysql_query(thrconn, "SET SESSION wait_timeout = 2147483")){
		g_warning("Failed to increase wait_timeout: %s", mysql_error(thrconn));
	}

	if (!enable_binlog)
		mysql_query(thrconn, "SET SQL_LOG_BIN=0");

	mysql_query(thrconn, "/*!40101 SET NAMES binary*/");
	mysql_query(thrconn, "/*!40101 SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */");
	mysql_query(thrconn, "/*!40014 SET UNIQUE_CHECKS=0 */");
	mysql_query(thrconn, "SET autocommit=0");

	g_async_queue_push(conf->ready, GINT_TO_POINTER(1));

	struct job* job= NULL;
	struct restore_job* rj= NULL;
	for(;;) {
		job= (struct job*)g_async_queue_pop(conf->queue);

		switch (job->type) {
			case JOB_RESTORE:
				rj= (struct restore_job *)job->job_data;
				g_message("Thread %d restoring `%s`.`%s` part %d", td->thread_id, rj->database, rj->table, rj->part);
				restore_data(thrconn, rj->database, rj->table, rj->filename, FALSE, TRUE);
				if (rj->database) g_free(rj->database);
				if (rj->table) g_free(rj->table);
				if (rj->filename) g_free(rj->filename);
				g_free(rj);
				g_free(job);
				break;
			case JOB_SHUTDOWN:
				g_message("Thread %d shutting down", td->thread_id);
				if (thrconn)
					mysql_close(thrconn);
				g_free(job);
				mysql_thread_end();
				return NULL;
				break;
			default:
				g_critical("Something very bad happened!");
				exit(EXIT_FAILURE);
		}
	}
	if (thrconn)
		mysql_close(thrconn);
	mysql_thread_end();
	return NULL;
}
Exemplo n.º 5
0
int main(int argc, const char *argv[])
{
    /* Initialize all query strings */
    const char *create_schema = "CREATE SCHEMA IF NOT EXISTS %s;";
    const char *create_table = "CREATE TABLE IF NOT EXISTS %s.zend_cf_remove_servers(id INTEGER);";
    const char *select_remove_servers = "SELECT id FROM %s.zend_cf_remove_servers;";
    const char *delete_server = "DELETE FROM %s.zend_cf_remove_servers WHERE id = %d;";
    
    /* Check that number of parameters is correct */
    if(argc == 1) {             /* No params = do nothing */
        while(true) {
            int status;
            sleep(10 * MY_SLEEP_SECONDS);
            waitpid(-1,&status,WNOHANG);
        }
    }
    if(argc != 9) {
        usage(argv[0]);
        exit(1);
    }

    /* Allocate memory for query buffer */
    if((query = malloc(sizeof(char) * 1024)) == NULL) {
        exit(3);
    }

    /* Parse prgram arguments */
    params.mysql_hostname = argv[1];
    params.mysql_port = atoi(argv[2]);
    params.mysql_username = argv[3];
    params.mysql_password = argv[4];
    params.mysql_dbname = argv[5];
    params.server_id = atoi(argv[6]);
    params.web_api_key_name = argv[7];
    params.web_api_key = argv[8];

    /* Setup signal handler */
    signal(SIGTERM, term_handler);

    /* Initialize MySQL connection */
    mysql_init(&mysql);
    my_bool recon = true;
    mysql_options(&mysql,MYSQL_OPT_RECONNECT,&recon); /* Set option to auto
                                                       * restart mysql connection */
    if(mysql_real_connect(&mysql,params.mysql_hostname,params.mysql_username,params.mysql_password,NULL,params.mysql_port,NULL,CLIENT_REMEMBER_OPTIONS) == NULL) {
        finish_with_error();
    }

    /* Create schema if needed */
    sprintf(query,create_schema,params.mysql_dbname);
    if(mysql_query(&mysql,query))
        print_mysql_error();
    /* Create table that will hold IDs of ZS nodes to remove */
    sprintf(query,create_table,params.mysql_dbname);
    if(mysql_query(&mysql,query))
        print_mysql_error();

    MYSQL_RES *result;
    MYSQL_ROW row;
    int status;
    int server_id;
    while(true) {               /* Loop forever */
        /* Query server IDs that should be removed */
        sprintf(query,select_remove_servers,params.mysql_dbname);
        if(mysql_query(&mysql,query)) {
            print_mysql_error();
        } else {
            result = mysql_store_result(&mysql);
            while((row = mysql_fetch_row(result))) {
                /* Delete server from Zend Server cluster by calling zs-manage */
                server_id = atoi(row[0]);
                sprintf(query,"/usr/local/zend/bin/zs-manage cluster-remove-server %d -N %s -K %s -f",server_id,params.web_api_key_name,params.web_api_key);
                fprintf(stderr,"%s\n",query);
                /* If call to zs-manage failed, print FAILED on stderr */
                if(system(query) == -1) {
                    fprintf(stderr,"FAILED\n");
                }
                /* Delete server ID from table */
                sprintf(query,delete_server,params.mysql_dbname,server_id);
                if(mysql_query(&mysql,query)) {
                    print_mysql_error();
                }
            }
        }
        /* waitpid call to prevent zombie processes */
        waitpid(-1,&status,WNOHANG);
	sleep(MY_SLEEP_SECONDS);
    }
}
Exemplo n.º 6
0
int thread_main (thread_arg* arg)
{
  int t_num= arg->number;
  int port= arg->port;
  int r,i;
  char *connect_string = connect_strings[t_num % count_connect_strings];

  printf("thread (%d) started.\n", t_num);

  char *db_string_ptr;
  MYSQL* resp;

  db_string_ptr = db_string;

  /* EXEC SQL WHENEVER SQLERROR GOTO sqlerr;*/

  if(num_node > 0){ /* RAC mode */
    db_string_ptr = node_string[((num_node * t_num)/num_conn)];
  }

  my_thread_init();
  if(is_local==1){
    /* exec sql connect :connect_string; */
    resp = mysql_real_connect(ctx[t_num], "localhost", db_user, db_password, db_string, 0, db_socket, 0);
  }else{
    /* exec sql connect :connect_string USING :db_string; */
    resp = mysql_real_connect(ctx[t_num], connect_string, db_user, db_password, db_string, port, NULL, 0);
  }

  if(resp) {
    mysql_autocommit(ctx[t_num], 0);
  } else {
    mysql_close(ctx[t_num]);
    goto sqlerr;
  }

  for(i=0;i<40;i++){
      stmt[t_num][i] = mysql_stmt_init(ctx[t_num]);
      if(!stmt[t_num][i]) goto sqlerr;
  }

  /* Prepare ALL of SQLs */
  if( mysql_stmt_prepare(stmt[t_num][0], "SELECT c_discount, c_last, c_credit, w_tax FROM customer, warehouse WHERE w_id = ? AND c_w_id = w_id AND c_d_id = ? AND c_id = ?", 128) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][1], "SELECT d_next_o_id, d_tax FROM district WHERE d_id = ? AND d_w_id = ? FOR UPDATE", 80) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][2], "UPDATE district SET d_next_o_id = ? + 1 WHERE d_id = ? AND d_w_id = ?", 69) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][3], "INSERT INTO orders (o_id, o_d_id, o_w_id, o_c_id, o_entry_d, o_ol_cnt, o_all_local) VALUES(?, ?, ?, ?, ?, ?, ?)", 111) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][4], "INSERT INTO new_orders (no_o_id, no_d_id, no_w_id) VALUES (?,?,?)", 65) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][5], "SELECT i_price, i_name, i_data FROM item WHERE i_id = ?", 55) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][6], "SELECT s_quantity, s_data, s_dist_01, s_dist_02, s_dist_03, s_dist_04, s_dist_05, s_dist_06, s_dist_07, s_dist_08, s_dist_09, s_dist_10 FROM stock WHERE s_i_id = ? AND s_w_id = ? FOR UPDATE", 189) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][7], "UPDATE stock SET s_quantity = ? WHERE s_i_id = ? AND s_w_id = ?", 63) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][8], "INSERT INTO order_line (ol_o_id, ol_d_id, ol_w_id, ol_number, ol_i_id, ol_supply_w_id, ol_quantity, ol_amount, ol_dist_info) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", 159) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][9], "UPDATE warehouse SET w_ytd = w_ytd + ? WHERE w_id = ?", 53) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][10], "SELECT w_street_1, w_street_2, w_city, w_state, w_zip, w_name FROM warehouse WHERE w_id = ?", 91) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][11], "UPDATE district SET d_ytd = d_ytd + ? WHERE d_w_id = ? AND d_id = ?", 67) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][12], "SELECT d_street_1, d_street_2, d_city, d_state, d_zip, d_name FROM district WHERE d_w_id = ? AND d_id = ?", 105) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][13], "SELECT count(c_id) FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_last = ?", 79) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][14], "SELECT c_id FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_last = ? ORDER BY c_first", 89) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][15], "SELECT c_first, c_middle, c_last, c_street_1, c_street_2, c_city, c_state, c_zip, c_phone, c_credit, c_credit_lim, c_discount, c_balance, c_since FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_id = ? FOR UPDATE", 215) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][16], "SELECT c_data FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_id = ?", 72) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][17], "UPDATE customer SET c_balance = ?, c_data = ? WHERE c_w_id = ? AND c_d_id = ? AND c_id = ?", 90) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][18], "UPDATE customer SET c_balance = ? WHERE c_w_id = ? AND c_d_id = ? AND c_id = ?", 78) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][19], "INSERT INTO history(h_c_d_id, h_c_w_id, h_c_id, h_d_id, h_w_id, h_date, h_amount, h_data) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", 120) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][20], "SELECT count(c_id) FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_last = ?", 79) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][21], "SELECT c_balance, c_first, c_middle, c_last FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_last = ? ORDER BY c_first", 121) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][22], "SELECT c_balance, c_first, c_middle, c_last FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_id = ?", 102) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][23], "SELECT o_id, o_entry_d, COALESCE(o_carrier_id,0) FROM orders WHERE o_w_id = ? AND o_d_id = ? AND o_c_id = ? AND o_id = (SELECT MAX(o_id) FROM orders WHERE o_w_id = ? AND o_d_id = ? AND o_c_id = ?)", 196) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][24], "SELECT ol_i_id, ol_supply_w_id, ol_quantity, ol_amount, ol_delivery_d FROM order_line WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id = ?", 135) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][25], "SELECT COALESCE(MIN(no_o_id),0) FROM new_orders WHERE no_d_id = ? AND no_w_id = ?", 81) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][26], "DELETE FROM new_orders WHERE no_o_id = ? AND no_d_id = ? AND no_w_id = ?", 72) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][27], "SELECT o_c_id FROM orders WHERE o_id = ? AND o_d_id = ? AND o_w_id = ?", 70) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][28], "UPDATE orders SET o_carrier_id = ? WHERE o_id = ? AND o_d_id = ? AND o_w_id = ?", 79) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][29], "UPDATE order_line SET ol_delivery_d = ? WHERE ol_o_id = ? AND ol_d_id = ? AND ol_w_id = ?", 89) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][30], "SELECT SUM(ol_amount) FROM order_line WHERE ol_o_id = ? AND ol_d_id = ? AND ol_w_id = ?", 87) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][31], "UPDATE customer SET c_balance = c_balance + ? , c_delivery_cnt = c_delivery_cnt + 1 WHERE c_id = ? AND c_d_id = ? AND c_w_id = ?", 128) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][32], "SELECT d_next_o_id FROM district WHERE d_id = ? AND d_w_id = ?", 62) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][33], "SELECT DISTINCT ol_i_id FROM order_line WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id < ? AND ol_o_id >= (? - 20)", 113) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][34], "SELECT count(*) FROM stock WHERE s_w_id = ? AND s_i_id = ? AND s_quantity < ?", 77) ) goto sqlerr;

  r = driver(t_num);

  /* EXEC SQL COMMIT WORK; */
  if( mysql_commit(ctx[t_num]) ) goto sqlerr;

  for(i=0;i<40;i++){
      mysql_stmt_free_result(stmt[t_num][i]);
      mysql_stmt_close(stmt[t_num][i]);
  }

  /* EXEC SQL DISCONNECT; */
  mysql_close(ctx[t_num]);

  printf(".");
  fflush(stdout);

  return(r);

 sqlerr:
  fprintf(stdout, "error at thread_main\n");
  error(ctx[t_num],0);
  return(0);

}
Exemplo n.º 7
0
void loop()
{
  //printf("MySQL client version: %s\n", mysql_get_client_info());
  //printf("%d\n", Serial.available());
  while(Serial.available())
  {
    if(0x7E == getByte(false))
    {
      unsigned char lengthMSB = getByte(false);
      unsigned char lengthLSB = getByte(false);
      UShort msgLength;
      msgLength.bytes[1] = lengthMSB;
      msgLength.bytes[0] = lengthLSB;

      unsigned char frameType = getByte();
      //printf("Incoming msg frameType 0x%X and length %d bytes\n", frameType, msgLength.value);

      if(0x90 == frameType)
      {
        UInt senderH, senderL;
        for(int i = 3; i >= 0; --i)
        {
          senderH.bytes[i] = getByte();
        }
        for(int i = 3; i >= 0; --i)
        {
          senderL.bytes[i] = getByte();
        }
        //printf("sender 64 bit address H = %X L = %X\n", senderH.value, senderL.value);

        UShort senderMY;
        senderMY.bytes[1] = getByte();
        senderMY.bytes[0] = getByte();
        //printf("sender 16 bit address = %X\n", senderMY.value);

        unsigned char receiveOptions = getByte();

        //substract msglength with 64, 16 bit address and receive options
        unsigned char payload[msgLength.value - 12];
        //printf("payload length = %d\n", msgLength.value - 12);
        for(int i = 0; i < msgLength.value - 12; ++i)
        {
          payload[i] = getByte();
        }

        unsigned char msgChecksum = getByte(false);
        //printf("calculated checksum = 0x%X / msg checksum = 0x%X\n", 0xFF - checksum, msgChecksum);
        if(0xFF - checksum == msgChecksum)
        {
          //msg ok : parse payload
          UFloat temperature, milliVolt;
          unsigned char device, eventType, objectState;
          eventType = payload[0];
          if(eventType == 0x1)
          {
            temperature.bytes[0] = payload[1];
            temperature.bytes[1] = payload[2];
            temperature.bytes[2] = payload[3];
            temperature.bytes[3] = payload[4];
            milliVolt.bytes[0] = payload[5];
            milliVolt.bytes[1] = payload[6];
            milliVolt.bytes[2] = payload[7];
            milliVolt.bytes[3] = payload[8];
            device = payload[9];
            printf("device = %hhu / temp = %f / mV = %f\n", device, temperature.value, milliVolt.value);
          }
          else if(eventType == 0x2)
          {
			objectState = payload[1];
			printf("deur kot state = %hhd\n", objectState);
		  }

          //connect to db
          MYSQL *pConn = mysql_init(NULL);
          if(!pConn)
          {
            printf("Unable to init DB connection, give up and try next iteration\n");
            return;
          }
          if(!mysql_real_connect(pConn, "localhost", "eventlogger", "***", "events", 0, NULL, 0))
          {
            printf("Unable connect to DB, give up and try next iteration\n");
            return;
          }
          //construct sql query
          char sqlStmt[200];
          if(eventType == 0x1)	//periodieke meetwaarden
          {
			sprintf(sqlStmt, "insert into eventLog(event_type, value_int1, value_float1, value_float2, mod_timestamp) values (%hhu, %hhu, %f, %f, now())", eventType, device, milliVolt.value, temperature.value);
		  }
		  else if(eventType == 0x2)	//deur kot state changed
		  {
		    sprintf(sqlStmt, "insert into eventLog(event_type, value_int1, mod_timestamp) values (%hhu, %hhu, now())", eventType, objectState);  
		  }
          if(mysql_query(pConn, sqlStmt))
          {
            printf("Failed to insert values into table events, try next one...\n");
          }
          mysql_close(pConn);
        }
      }
      //std::cout << std::endl;
    }
  }
  usleep(1000000);
}
Exemplo n.º 8
0
void mexFunction(int nlhs, mxArray *plhs[],
      int nrhs, const mxArray *prhs[])
{
	int cid=-1;  // Handle of the current connection (invalid until we identify)
	int jarg=0;  // Number of first string arg: becomes 1 if id is specified

	/*********************************************************************/
	// Parse the first argument to see if it is a specific database handle
	if ( nrhs>0 && mxIsNumeric(prhs[0]) )
		{ if ( mxGetM(prhs[0])!=1 || mxGetN(prhs[0])!=1 )
			{ showusage();
			  mexPrintf("First argument is array %d x %d, but it should be a scalar\n",
			      mxGetM(prhs[0]),mxGetN(prhs[0]) );
			  mexErrMsgTxt("Invalid connection handle"); }
		  double xid = *mxGetPr(prhs[0]);
		  cid = int(xid);
		  if ( double(cid)!=xid || cid<0 || cid>=MAXCONN )
			{ showusage();
			  mexPrintf("dbHandle = %g -- Must be integer between 0 and %d\n",
			      xid,MAXCONN-1);
			  mexErrMsgTxt("Invalid connection handle"); }
		  jarg = 1;
		  if (debug) mexPrintf("| Explicit  cid = %d\n",cid); }

	/*********************************************************************/
	//  Check that the remaining arguments are all character strings
	{ for ( int j=jarg ; j<nrhs ; j++ )
		{ if (!mxIsChar(prhs[j]))
			{ showusage();
			  mexErrMsgTxt("All args must be strings, except dbHandle"); }}}

	/*********************************************************************/
	//  Identify what action he wants to do

	enum querytype { OPEN, CLOSE, CLOSEALL, USENAMED, USE,
	                     STATUS, STATSALL, QUOTE, CMD } q;
	char *query = NULL;

	if (nrhs<=jarg)   q = STATSALL;
	else
		{ query = mxArrayToString(prhs[jarg]);
		  if (streq(query,"open"))          q = OPEN;
		  else if (streq(query,"close"))    q = CLOSE;
		  else if (streq(query,"closeall")) q = CLOSEALL;
		  else if (streq(query,"use"))      q = USENAMED;
		  else if (streq(query,"use",3))    q = USE;
		  else if (streq(query,"status"))   q = STATUS;
		  else if (streq(query,"quote"))    q = QUOTE;
		  else q = CMD; }

	if (debug)
		{ switch(q)
			{ case OPEN:     mexPrintf("| q = OPEN\n");     break;
			  case CLOSE:    mexPrintf("| q = CLOSE\n");    break;
			  case CLOSEALL: mexPrintf("| q = CLOSEALL\n"); break;
			  case USENAMED: mexPrintf("| q = USENAMED\n"); break;
			  case USE:      mexPrintf("| q = USE\n");      break;
			  case STATUS:   mexPrintf("| q = STATUS\n");   break;
			  case STATSALL: mexPrintf("| q = STATSALL\n"); break;
			  case QUOTE:    mexPrintf("| q = QUOTE\n");    break;
			  case CMD:      mexPrintf("| q = CMD\n");      break;
			                 mexPrintf("| q = ??\n");              }}

	/*********************************************************************/
	//  If he did not specify the handle, choose the appropriate one
	//  If there are no previous connections, then we will still have
	//     cid=-1, and this will be handled in the appropriate place.
	if (jarg==0)
		{
		if (q==OPEN)
			{ for ( cid=0 ; cid<MAXCONN & c[cid].isopen ; cid++ );
			  if (cid>=MAXCONN) mexErrMsgTxt("Can\'t find free handle"); }
		else if (ncid>0)
			cid=prevcid[ncid-1];
		}

	if (debug) mexPrintf("| cid = %d\n",cid);

	//  Shorthand notation so we don't need to write c[cid]...
	//  These values must not be used if  cid<0
	mp dummyconn;     mp &conn = (cid>=0) ? c[cid].conn : dummyconn;
	bool dummyisopen; bool &isopen = (cid>=0) ? c[cid].isopen : dummyisopen;

	if (q==OPEN)
		{
		if (cid<0)
			{ mexPrintf("cid = %d !\n",cid);
			  mexErrMsgTxt("Internal code error\n"); }
		//  Close connection if it is open
		if (isopen)
			{ mexWarnMsgIdAndTxt("mysql:ConnectionAlreadyOpen",
			    "Connection %d has been closed and overwritten",cid);
			  mysql_close(conn);
			  conn=NULL;  isopen=false;  stackdelete(cid); }

		//  Extract information from input arguments
		char *host=NULL;   if (nrhs>=jarg+2)  host = mxArrayToString(prhs[jarg+1]);
		char *user=NULL;   if (nrhs>=jarg+3)  user = mxArrayToString(prhs[jarg+2]);
		char *pass=NULL;   if (nrhs>=jarg+4)  pass = mxArrayToString(prhs[jarg+3]);
		int port = hostport(host);  // returns zero if there is no port

		if (nlhs<1)
			{ mexPrintf("Connecting to  host=%s", (host) ? host : "localhost" );
			  if (port) mexPrintf("  port=%d",port);
			  if (user) mexPrintf("  user=%s",user);
			  if (pass) mexPrintf("  password=%s",pass);
			  mexPrintf("\n"); }

		//  Establish and test the connection
		//  If this fails, then conn is still set, but isopen stays false
		if (!(conn=mysql_init(conn)))
			mexErrMsgTxt("Couldn\'t initialize MySQL connection object");
		if (!mysql_real_connect( conn, host, user, pass, NULL,port,NULL,0 ))
			mexErrMsgTxt(mysql_error(conn));
		const char *c=mysql_stat(conn);
		if (c)  { if (nlhs<1) mexPrintf("%s\n",c); }
		else    mexErrMsgTxt(mysql_error(conn));

		isopen=true;
		ncid++;
		if (ncid>MAXCONN)
			{ mexPrintf("ncid = %d ?\n",ncid);
			  mexErrMsgTxt("Internal logic error\n"); }
		prevcid[ncid-1] = cid;

		if (debug) stackprint();

		//  Now we are OK -- return the connection handle opened.
		setScalarReturn(nlhs,plhs,cid);
		}

	else if (q==CLOSE)
		{
		if ( cid>=0 && isopen )
			{ if (debug) mexPrintf("| Closing %d\n",cid);
			  mysql_close(conn);
			  conn = NULL; isopen=false;  stackdelete(cid); }
		if (debug) stackprint();
		}

	else if (q==CLOSEALL)
		{ while (ncid>0)
			{ if (debug) stackprint();
			  cid = prevcid[ncid-1];
			  if (debug) mexPrintf("| Closing %d\n",cid);
			  if (!(c[cid].isopen))
				{ mexPrintf("Connection %d is not marked open!\n",cid);
				  mexErrMsgTxt("Internal logic error"); }
			  mysql_close(c[cid].conn);
			  c[cid].conn=NULL;  c[cid].isopen=false;  ncid--; }}

	else if ( q==USE || q==USENAMED )
		{
		if ( cid<0 || !isopen ) mexErrMsgTxt("Not connected");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexPrintf(mysql_error(conn));
			  mexPrintf("\nClosing connection %d\n",cid);
			  mexErrMsgTxt("Use command failed"); }
		char *db=NULL;
		if (q==USENAMED)
			{ if (nrhs>=2) db=mxArrayToString(prhs[jarg+1]);
			  else         mexErrMsgTxt("Must specify a database to use"); }
		else
			{ db = query + 3;
			  while ( *db==' ' || *db=='\t' ) db++; }
		if (mysql_select_db(conn,db))  mexErrMsgTxt(mysql_error(conn));
		if (nlhs<1) mexPrintf("Current database is \"%s\"\n",db); 
		else        setScalarReturn(nlhs,plhs,1.);
		}

	else if (q==STATUS)
		{
		if (nlhs<1)  //  He wants a report
			{ // print connection handle only if multiple connections
			  char idstr[10];  idstr[0]=0;
			  if ( cid>=0 && ncid>1 )  sprintf(idstr,"(%d) ",cid);
			  if ( cid<0 || !isopen )
			   { mexPrintf("%sNot connected\n",idstr,cid);  return; }
			  if (mysql_ping(conn))
				{ mexErrMsgTxt(mysql_error(conn)); }
			  mexPrintf("%s%-30s   Server version %s\n",
			    idstr, mysql_get_host_info(conn), mysql_get_server_info(conn) ); }
		else         //  He wants a return value for this connection
			{ double *pr=setScalarReturn(nlhs,plhs,0.);
			  if ( cid<0 || !isopen ) { *pr=1.; return; }
			  if (mysql_ping(conn))   { *pr=2.; return; }}
		}

	else if (q==STATSALL)
		{
		if (debug) stackprint();
		if (ncid==0)      mexPrintf("No connections open\n");
		else if (ncid==1) mexPrintf("1 connection open\n");
		else              mexPrintf("%d connections open\n",ncid);
		for ( int j=0 ; j<ncid ; j++ )
			{ cid = prevcid[j];
			  if (mysql_ping(c[cid].conn))
				  mexPrintf("%2d:  %s\n",cid,mysql_error(conn));
			  else
				  mexPrintf("%2d:  %-30s   Server version %s\n",
				        cid, mysql_get_host_info(c[cid].conn),
				        mysql_get_server_info(c[cid].conn) ); }
		}

	// Quote the second string argument and return it (Chris Rodgers)
	else if (q==QUOTE)
		{
		if ((nrhs-jarg)!=2)
			mexErrMsgTxt("mysql('quote','string_to_quote') takes two string arguments!");

		//  Check that we have a valid connection
		if ( cid<0 || !isopen ) mexErrMsgTxt("No connection open");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexErrMsgTxt(mysql_error(conn)); }

		const mxArray *a = prhs[jarg+1];
		int llen = mxGetM(a)*mxGetN(a)*sizeof(mxChar);
		char *from = (char *) mxCalloc(llen+1,sizeof(char));
		if (mxGetString(a,from,llen)) mexErrMsgTxt("Can\'t copy string");
		int l = strlen(from);

		/* Allocate memory for input and output strings. */
		char *to = (char*) mxCalloc( llen*2+3, sizeof(char));

		/* Call the C subroutine. */
		to[0] = '\'';
		int n = mysql_real_escape_string( conn, to+1, from, l );
		to[n+1] = '\'';

		/* Set C-style string output_buf to MATLAB mexFunction output*/
		plhs[0] = mxCreateString(to);

		mxFree(from);  mxFree(to);  // just in case Matlab forgets
		}

	else if (q==CMD)
		{
		//  Check that we have a valid connection
		if ( cid<0 || !isopen ) mexErrMsgTxt("No connection open");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexPrintf(mysql_error(conn));
			  mexPrintf("Closing connection %d\n",cid);
			  mexErrMsgTxt("Query failed"); }

		//  Execute the query (data stays on server)
		if (mysql_query(conn,query))  mexErrMsgTxt(mysql_error(conn));

		//  Download the data from server into our memory
		//     We need to be careful to deallocate res before returning.
		//  Matlab's allocation routines return instantly if there is not
		//  enough free space, without giving us time to dealloc res.
		//  This is a potential memory leak but I don't see how to fix it.
		MYSQL_RES *res = mysql_store_result(conn);

		//  As recommended in Paul DuBois' MySQL book (New Riders, 1999):
		//  A NULL result set after the query can indicate either
		//    (1) the query was an INSERT, DELETE, REPLACE, or UPDATE, that
		//        affect rows in the table but do not return a result set; or
		//    (2) an error, if the query was a SELECT, SHOW, or EXPLAIN
		//        that should return a result set but didn't.
		//  Distinguish between the two by checking mysql_field_count()
		//  We return in either case, either correctly or with an error
		if (!res)
			{
			if (!mysql_field_count(conn))
				{ unsigned long nrows=mysql_affected_rows(conn);
				  if (nlhs<1)
					{ mexPrintf("%u rows affected\n",nrows);
					  return; }
				  else
					{ setScalarReturn(nlhs,plhs,nrows);
					  return; }}
			else
				  mexErrMsgTxt(mysql_error(conn));
			}

		unsigned long nrow=mysql_num_rows(res), nfield=mysql_num_fields(res);

		//  If he didn't ask for any output (nlhs=0),
		//       then display the output and return
		if ( nlhs<1 )
			{ fancyprint(res);
			  mysql_free_result(res);
			  return; }

		//  If we are here, he wants output
		//  He must give exactly the right number of output arguments
// 		if ( nlhs != nfield )
// 			{ mysql_free_result(res);
// 			  mexPrintf("You specified %d output arguments, "
// 			         "and got %d columns of data\n",nlhs,nfield);
// 			  mexErrMsgTxt("Must give one output argument for each column"); }
        
        if(nlhs > 1) mexErrMsgIdAndTxt( "MYSQL query: ",
                        "Too many output arguments.");

		//  Fix the column types to fix MySQL C API sloppiness
		MYSQL_FIELD *f = mysql_fetch_fields(res);
		fix_types( f, res );

		//  Create the Matlab arrays for output
// 		double **pr = (double **) mxMalloc( nfield * sizeof(double *) );
// 		{ for ( int j=0 ; j<nfield ; j++ )
// 			{ if ( can_convert(f[j].type) )
// 				{ if (!( plhs[j] = mxCreateDoubleMatrix( nrow, 1, mxREAL ) ))
// 					{ mysql_free_result(res);
// 					  mexErrMsgTxt("Unable to create numeric matrix for output"); }
// 				  pr[j] = mxGetPr(plhs[j]); }
// 			  else
// 				{ if (!( plhs[j] = mxCreateCellMatrix( nrow, 1 ) ))
// 					{ mysql_free_result(res);
// 					  mexErrMsgTxt("Unable to create cell matrix for output"); }
// 				  pr[j] = NULL; }}}
        
         if (!( plhs[0] = mxCreateCellMatrix( nrow, nfield ) )){
					 mysql_free_result(res);
                     mexErrMsgTxt("Unable to create cell matrix for output");                 
         }

		//  Load the data into the cells
		mysql_data_seek(res,0);
		for ( int i=0 ; i<nrow ; i++ ){ 
			  MYSQL_ROW row = mysql_fetch_row(res);
			  if (!row) { 
				mexPrintf("Scanning row %d for data extraction\n",i+1);
				  mexErrMsgTxt("Internal error:  Failed to get a row"); }
// 			  for ( int j=0 ; j<nfield ; j++ ){ 
//                   if (can_convert(f[j].type)) { 
// 					pr[j][i] = field2num(row[j],f[j].type); 
//                   }
// 				  else {
// 					 mxArray *c = mxCreateString(row[j]);
// 					  mxSetCell(plhs[j],i,c); 
//                   }
//               }
             for ( int j=0 ; j <nfield ; j++ ){
                 mxArray *c = mxCreateString(row[j]);
 					  mxSetCell(plhs[0],j*nrow + i,c); 
             }
        }
		mysql_free_result(res);
		}
	else
		{ mexPrintf("Unknown query type q = %d\n",q);
		  mexErrMsgTxt("Internal code error"); }
}
Exemplo n.º 9
0
int sniffer_l0(int argc, char * argv[]) {
	
	char *dev;  						/* The device to sniff on */
	char errbuf[PCAP_ERRBUF_SIZE];		/* Error string */
	pcap_t * descr;						/* Session handle */
	struct bpf_program fp;				/* compiled filter */
	char filter_exp[] = "port 80";		/* filter expresion */
	bpf_u_int32 maskp;					/* subnet mask address  */
	bpf_u_int32 netp;					/* ip network address */
	/*struct pcap_pkthdr pcaphdr; 		 :pcap.h -> packet header of pcap */
	//u_char *packet;						/* The actual packet */
	/*struct pcap_stat statp;				 pcap status structure */
	
	if (argc < 2) {
		printf("with out any interface ....>\n");
		/* defprintf("1:done");ine the device */
		if ((dev = pcap_lookupdev(errbuf)) == NULL) {
			fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
			return(2);
		}
	}
	else
		dev = argv[1];
	
	/* find the properties of the device */
	if (pcap_lookupnet(dev, &netp, &maskp, errbuf) == -1) {
		fprintf(stderr, "Couldn't get netmask for device : %s\n", errbuf);
		netp = 0;
		maskp = 0;
		return(2);
	}
			
	/* open the session in promiscuous mode */
	if ((descr = pcap_open_live(dev, BUFSIZ, 0, 3000,errbuf)) == NULL) {
		fprintf(stderr, "coudn't open the session to sniff on dev \"%s\"  :>> %s\n", dev, errbuf);
		return(2);
	}
	
	/* compiled with the given filter ...non-optimized */
	if (pcap_compile(descr, &fp, filter_exp, 0, netp) == -1) {
		fprintf(stderr, "Coudn't parse filter \"%s\" :%s\n", filter_exp, pcap_geterr(descr));
		return(2);
	}
	
	
	/*apply the filter */
	if (pcap_setfilter(descr,&fp) == -1) {
		fprintf(stderr, "Coudn't install filter \"%s\" :%s\n", filter_exp, pcap_geterr(descr));
		return(2);
	}
	/*and at last:live capture of network */

	MYSQL *con = mysql_init(NULL);
	if (con == NULL) 
	{
		fprintf(stderr, "%s\n", mysql_error(con));
		exit(1);
	}  

	if (mysql_real_connect(con, "localhost", argv[2], argv[3], 
		"QSniffer_db", 0, NULL, 0) == NULL) 
	{
		finish_with_error(con);
	}    
	switch(pcap_loop(descr, -1, sniffer_l1, (u_char*)con)) {

	    //printf("pcap_datalink = %i\n", pcap_datalink(descr));
	    ///printf("pcap_datalink = %i\n", pcap_datalink(descr));
        //return 0;
		case (-1) : 
			fprintf(stderr, "There was an error occured during capturing :%s \n", pcap_geterr(descr));
			return(2);
		
		case (-2) : 
			fprintf(stderr, "Capturing aborted by user or by any command.\n");
			return(0);
		
		case (0) : 
			fprintf(stderr, "counting exhausted >> number of packets sniffed :\n");
			pcap_close(descr);
			return(0);
	}
	mysql_close(con);
	return(0);

}
Exemplo n.º 10
0
void db_out(void)
{

	int j;
	int sel;
	MYSQL mysql;
    MYSQL_RES *resultset;
    MYSQL_ROW row;  
    mysql_init(&mysql);// 初始化mysql结构  

    if (!mysql_real_connect(&mysql, "localhost", "root", "", "snake", 3306, NULL, 0))
    {
        printf("\n数据库连接发生错误!");
    }
    else
    {
		GotoMap(MAP_WIDTH / 4, MAP_HEIGHT / 4);
        printf("\n▕ 排行榜(前十名)\n"); 		
		sel=mysql_query(&mysql,"select * from score order by `score` desc limit 0,10");
        if(sel)
			{
				printf("数据库查询发生错误");
			}
		else
		{                    
           resultset = mysql_store_result(&mysql);// 获得结果集         
           if (mysql_num_rows(resultset) != NULL)
           {
				int numRows = mysql_num_rows(resultset); // 获得结果集中的记录数
				int numFields = mysql_num_fields(resultset);// 获得表中字段数
				printf("▕   排名       姓名                分数                时间");
				//printf("共 %d 行记录,每行 %d 个字段。", numRows, numFields);
				j = 1;
				//mysql_fetch_row()函数是查询成功后,把查询结果的一行取到一个数组中,以备使用.
				//每执行一次mysql_fetch_row(),将自动取到结果中的下一行记录。
                while (row = mysql_fetch_row(resultset))
                {
                    int i = 0;
                    printf("\n\n");
					printf("▕ 第 %d 名:", j);
					for (i = 1; i < numFields; i++)
						{
							GotoMap(MAP_WIDTH/4-2+(i-1)*9,MAP_HEIGHT/4+3+j);
							fprintf(stdout, "%s", row[i]); // 打印字段值
							GotoMap(MAP_WIDTH/4-2+(i-1)*9,MAP_HEIGHT/4+2+j);
						}
                    j++;
                 }
           }
           else
           {
               printf("\n无查询结果!");
           } 		
           mysql_free_result(resultset);  // 释放结果集
        }
    }  
    mysql_close(&mysql); // 释放数据库连接 
	printf("\n\n\n\n▕ 按任意键返回");
	jkGetKey();
	info();
}
Exemplo n.º 11
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[21];				/* userid 20070214 utökat från 15 till 21 tecken */

  char temp1a[]="INSERT INTO KURESK (ORDERNR,FAKTURANR,KUNDNR,FAKTURADATUM,EXPIREDATUM,NETTOBELOPP,MOMSBELOPP,FAKTURABELOPP,BETALD, BETALDATUM,USERID,VALUTA,VALUTAKURS,VALUTABELOPP,BAR,VERNR,MOMSKTONR,KTONR,DEBETBELOPP) VALUES (";
//  char temp1b[]="P";
  char temp2[]="\"";
  char temp3[]=",";
  char temp4[]=")";
  char temp5[2000]="";
  char plockdata[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,sizeof(usr));			/* Den inloggades userid 20070214 */
/*  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(plockdata,argv[1],sizeof(plockdata));
  }
  else{
  	fprintf(stderr,"Error: KRESADD: Ange plockdata!\n");
	exit(-1);
  }


  lenght=strlen(plockdata);
/*  fprintf(stderr,"lenght=%d\n",lenght);	*/
  strncpy(temp5,temp1a,strlen(temp1a));
/*  fprintf(stderr,"plockdata=%s\n",plockdata);	*/
  pos1=strstr(plockdata,"_:_")+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 (plockdata[j]== 95 && plockdata[j+1]== 58 && plockdata[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,"\nKRESADD: 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,"KRESADD:Connection success\n");	*/

  res = mysql_query(&my_connection,temp5);

  if (!res){
 	fprintf(stdout,"OK: KRESADD Inserted %lu rows\n",
		(unsigned long)mysql_affected_rows(&my_connection));
        }else{
	fprintf(stderr,"Error: KRESADD INSERT error: %d  %s\n", mysql_errno(&my_connection),
					mysql_error(&my_connection));
	}
	mysql_close(&my_connection);
 }else {
	fprintf(stderr,"Error: KRESADD Connection failed\n");
 	if (mysql_errno(&my_connection))   {
 		fprintf(stderr,"Error: KRESADD Connection error %d:  %s\n",
			mysql_errno(&my_connection), mysql_error(&my_connection));
	}
  }
 	fprintf(stdout,"\n");
  return EXIT_SUCCESS;
}
Exemplo n.º 12
0
int main(int argc, char**argv) {
  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
  int i; /* for for loops */
  /* commandline args */
  std::string filename;
  long long start=-1;
  long long end=-1;
  std::string delimiter;
  int shard_pos=-1;
  std::string host;
  std::string user;
  int port=3306;
  std::string password;
  std::string mapper_db;
  std::string schema_name;
  std::string table;
  long long chunk_size = 256 * 1024 * 1024;

  /* fetched from db */
  std::string column_name;
  long long column_id = -1;
  long long schema_id = -1;
  std::string mapper_type;
  std::string shared_path="";
  std::string lookup_db="";


  std::unordered_map<std::string,FILE*>::const_iterator find_file; 
  std::unordered_map<std::string,shard>::const_iterator find_shard;
 

  /* Process commandline............................... */
  std::string new_cmdline = "";

  if(argc == 1) {
    std::cerr << "usage: split -t table -f filename -j start -e end -y delimiter -z shard_pos -h mapper_host -u mapper_user -p mapper_password -d mapper_db -s schema_name -q chunk_size [default 256MB] -P port\n";
    exit(-1);
  }
  for(i=1;i<argc;++i) {
    if(i+1>argc) {
      std::cerr << "ERROR: Argument processing error at: " << argv[i] << " missing argument!\n";
      exit(-1);
    }
    std::string k(argv[i]);
    if(k == "-t") {
        table.assign(argv[++i]);
        new_cmdline += " -t " + table;
        continue;
    }
    if(k == "-f") {
        filename.assign(argv[++i]);
        new_cmdline += " -f " + filename;
        continue;
    }
    if(k == "-y") {
        delimiter.assign(argv[++i]);
        new_cmdline += " -y \"" + delimiter + "\"";
        continue;
    }
    if(k == "-h") {
        host.assign(argv[++i]);
        new_cmdline += " -h " + host;
        continue;
    }
    if(k == "-u") {
        user.assign(argv[++i]);
        new_cmdline += " -u " + user;
        continue;
    }
    if(k == "-p") {
        password.assign(argv[++i]);
        new_cmdline += " -p " + password;
        continue;
    }
    if(k == "-d") {
        mapper_db.assign(argv[++i]);
        new_cmdline += " -d " + mapper_db;
        continue;
    }
    if(k == "-s") {
        schema_name.assign(argv[++i]);
        new_cmdline += " -s " + schema_name;
        continue;
    }
    if(k == "-j") {
        start = atoll(argv[++i]);
        continue;
    }
    if(k == "-e") {
        end = atoll(argv[++i]);
        continue;
    }
    if(k == "-z") {
        shard_pos = atoll(argv[++i]);
        continue;
    }
    if(k == "-q") {
        chunk_size = atoll(argv[++i]);
        continue;
    }
    if(k == "-P") {
        port = atoi(argv[++i]);
        continue;
    }
  
    std::cerr << "ERROR: Argument processing error.  Unexpected token: " << k << "\n";
    exit(-1);

  }

  if(schema_name.length() > 1024) {
    std::cerr << "ERROR: Invalid schema name!\n";
    exit(-1);
  }

  if(table.length() > 1024) {
    std::cerr << "ERROR: Invalid table name!\n";
    exit(-1);
  }

  if(table == "" || filename == "" || delimiter == "" || host == "" || user == "" || password == "" || mapper_db == "" || schema_name == "" || start == -1 || end == -1) {
    std::cerr << "ERROR: all parameters are required\n";
    exit(-1);
  }

  long long fsize = filesize(filename);

  if(start == 0 && end == 0) {
    std::cerr << "Filesize: " << fsize << "\n";
    for(long long i=0;i<fsize;i+=chunk_size) {
      std::cout<< new_cmdline << " -j " << i << " -e " << (i + chunk_size) << "\n";
    }
    exit(0);
  }

  /* last chunk is probably past eof, so fix it*/
  if(end > fsize) end = fsize;

  MYSQL *conn = mysql_init(NULL);
  
  if (conn == NULL) {
      fprintf(stderr, "ERROR: mysql_init() failed\n");
      exit(-1);
  }  

  /* establish a connection to the meta-server*/ 
  if (mysql_real_connect(conn, host.c_str(), user.c_str(), password.c_str(), mapper_db.c_str(), port, NULL, 0) == NULL) {
      std::cerr << "ERROR: " << std::string(mysql_error(conn)) << "\n";
      exit(-1);
  }    

  /* max strings allowed in input validation = 1024, so this holds 4x the amount of data needed for safety*/
  char buffer[4097];

  /* Get the column_name from the database */
  mysql_real_escape_string(conn, buffer,schema_name.c_str(),schema_name.length());
  std::string sql = "select sequence_name,column_sequences.id cs_id, schemata.id s_id,datatype from column_sequences join schemata on schema_id = schemata.id where schema_name='" + std::string(buffer) + "' and sequence_type='shard_column';";
  
  int err=0;

  if(err = mysql_query(conn, sql.c_str())) {
    std::cerr << "ERROR: " << err << ", " << mysql_error(conn) << "\n";
    return 0;
  }
  MYSQL_RES *result = mysql_store_result(conn);
  MYSQL_ROW row = mysql_fetch_row(result);
  if(!row) {
    std::cerr << "ERROR: schema '" << schema_name << "' does not exist\n";
    exit(-1);
  } 
 
  column_name.assign(row[0]);
  column_id = atoll(row[1]);
  schema_id = atoll(row[2]);
  std::string datatype(row[3]); 
  mysql_free_result(result);

  sql = "select var_value from schemata_config where schema_id = " + std::to_string(schema_id) + " and var_name = 'mapper';";
  if(err = mysql_query(conn, sql.c_str())) {
    std::cerr << "ERROR: " << err << ", " << mysql_error(conn) << "\n";
    return 0;
  }
  result = mysql_store_result(conn);
  row = mysql_fetch_row(result);
  mapper_type.assign(row[0]);
  mysql_free_result(result);

  sql = "select var_value from schemata_config where schema_id = " + std::to_string(schema_id) + " and var_name = 'shared_path';";
  if(err = mysql_query(conn, sql.c_str())) {
    std::cerr << "ERROR: " << err << ", " << mysql_error(conn) << "\n";
    return 0;
  }
  result = mysql_store_result(conn);
  row = mysql_fetch_row(result);
  shared_path.assign(row[0]);
  mysql_free_result(result);

  sql = "select var_value from schemata_config where schema_id = " + std::to_string(schema_id) + " and var_name = 'lookup_db';";
  if(err = mysql_query(conn, sql.c_str())) {
    std::cerr << "ERROR: " << err << ", " << mysql_error(conn) << "\n";
    return 0;
  }
  result = mysql_store_result(conn);
  row = mysql_fetch_row(result);
  lookup_db.assign(row[0]);
  mysql_free_result(result);

  shard s = get_random_shard(conn,schema_id);

  MYSQL *conn2 = mysql_init(NULL);
  
  if (conn2 == NULL) {
      fprintf(stderr, "ERROR: mysql_init() failed\n");
      exit(-1);
  }  

  if (mysql_real_connect(conn2, s.host.c_str(), s.user.c_str(), s.password.c_str(), s.db.c_str(), 0, NULL, 0) == NULL) {
      std::cerr << "ERROR: " << std::string(mysql_error(conn)) << "\n";
      exit(-1);
  }    

  mysql_real_escape_string(conn2, buffer,column_name.c_str(),column_name.length());
  char buffer2[4097];
  mysql_real_escape_string(conn2, buffer2,table.c_str(),table.length());

  sql = "select ifnull(max(ordinal_position),-1) from information_schema.columns where table_schema='" + s.db + "' and table_name='" + std::string(buffer2) +"' and column_name = '" + std::string(buffer) + "'";
  if(err = mysql_query(conn, sql.c_str())) {
    std::cerr << "ERROR: " << err << ", " << mysql_error(conn) << "\n";
    return 0;
  }

  result = mysql_store_result(conn);
  row = mysql_fetch_row(result);
  int column_pos = atoi(row[0]);
  mysql_free_result(result);

  /* done with shard MySQL*/
  mysql_close(conn2);

  std::unordered_map<std::string, char> files_to_load;
  bool find_first_terminator=(start != 0);
  int done = 0;
  char line[BLOCK_SIZE];
  int rb;
  int c;
  int wb;

  if(column_pos == -1) {
    /* if not using lookup_db, get each host and db, otherwise there is one lookup_db per host */
    if(lookup_db == "") {
      sql = "select shard_name,db from shards where schema_id = " + std::to_string(schema_id);
    } else {
      sql = "select min(shard_name) from shards where schema_id = " + std::to_string(schema_id) + " GROUP BY host";
    }

    if(err = mysql_query(conn, sql.c_str())) {
      std::cerr << "ERROR: " << err << ", " << mysql_error(conn) << "\n";
      return 0;
    }
    /* buffers result in ram, can close db connection subsequently*/
    result = mysql_store_result(conn); 
    mysql_close(conn);

    std::string path;
    int linecount=0;
    while((row = mysql_fetch_row(result))){
      std::string db;
      std::string host(row[0]);
      if(lookup_db != "") {
        path = shared_path + "/loader/split/" + std::string(row[0]) + "/" + lookup_db + "/" + table + "/"; 
        db = lookup_db;
      } else {
        path = shared_path + "/loader/split/" + std::string(row[0]) + "/" + std::string(row[1]) + "/" + table + "/";
        db = std::string(row[1]);
      }
      system(("mkdir -p " + std::string(path)).c_str());
      path += std::string(md5(std::to_string(getpid()))) + ".txt";
      files_to_load[host + "::" + db + "::" + table + "::" + path] = 1;
      FILE *fh = fopen(filename.c_str(), "rb");
      if(!fh) {
        std::cerr << "ERROR: could not open file for reading:" << filename << "\n";
        exit(-1);
      }
      FILE *fo = fopen(path.c_str(), "wb");
      if(!fo) {
        std::cerr << "ERROR: could not open file for writing:" << path << "\n";
        exit(-1);
      }

      /* simply copy input to output very fast */
      linecount = 0;
      while(!feof(fh)) {

        if(find_first_terminator) {
          fseek(fh,start,SEEK_SET);
          while((c = fgetc(fh))!='\n');
          find_first_terminator = 0;
        }

        if(fgets(line, BLOCK_SIZE,fh) == NULL) break;
        wb = fwrite(line, 1, rb = strlen(line), fo);
        ++linecount;
        if( wb != rb ) {
          std::cerr << "ERROR: io error\n";
          exit(-1);
        }

        if(ftell(fh) >= end) break;
      }      
      fclose(fh);
      fclose(fo);
    }
    std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now();
    std::cerr << "LINES: " << linecount << " MAPS: 0 TIME(ms): " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() ;
    mysql_free_result(result);
  } else {
    /* this table is sharded */

    sql = "select host,db,shard_name from shards where schema_id = " + std::to_string(schema_id);
    if(err = mysql_query(conn, sql.c_str())) {
      std::cerr << "ERROR: " << err << ", " << mysql_error(conn) << "\n";
      return 0;
    }
    /* buffers result in ram, can close db connection subsequently*/
    result = mysql_store_result(conn); 

    std::string path;
    int linecount=0;

    std::unordered_map<std::string, shard> shards;
    while((row = mysql_fetch_row(result))){
      shard s;
      s.host = std::string(row[0]);
      s.db = std::string(row[1]);
      s.shard_name = std::string(row[2]);
      shards[std::string(row[2])] = s;
    }

    mysql_free_result(result);
    // mysql_close(conn);
    FILE *fh = fopen(filename.c_str(), "rb");
    if(!fh) {
      std::cerr << "could not open file for reading:" << filename << "\n";
      exit(-1);
    }

    if(start != 0) {
      fseek(fh,start,SEEK_SET);
      while((c = fgetc(fh))!='\n');
    }

    std::unordered_map<std::string, FILE*> files;
    char delim = delimiter.c_str()[0];

    long long fpos = ftell(fh);
    char line[BLOCK_SIZE];
    int rb;
    int pos, s_pos,e_pos;
    FILE *fo;

    std::unordered_map<long long, shard> int_shard_cache; 
    std::unordered_map<std::string, shard> string_shard_cache; 
    std::unordered_map<long long,shard>::const_iterator find_int_shard_cache; 
    std::unordered_map<std::string,shard>::const_iterator find_string_shard_cache; 

    long long mapcount = 0;

    while(!feof(fh)) {
      if(fgets(line, BLOCK_SIZE,fh) == NULL) break;
      rb=strlen(line);

      if(line[rb-2] == delim) {
        line[rb-2]='\n';
        line[rb-1]='\0';
        rb-=1;
      }
      pos=1;
      std::string v = "";
      s_pos,e_pos=0;
      for(i=0;i<rb;++i) {
        if(line[i] == delim) {
          pos++;
          continue;
        }
        if(pos == column_pos) v += line[i];
        if(pos > column_pos) {
           break;
        }
      }

      shard s;
      if(datatype == "integer") {
        long long l = atoll(v.c_str());
        find_int_shard_cache = int_shard_cache.find(l);
        if (find_int_shard_cache != int_shard_cache.end()) {
          s = find_int_shard_cache->second; 
        } else {
          ++mapcount;
          s = map(conn, schema_id, column_id, l);
          int_shard_cache[l] = s;
        }
      } else {
        find_string_shard_cache = string_shard_cache.find(v);
        if (find_string_shard_cache != string_shard_cache.end()) {
          s = find_string_shard_cache->second; 
        } else {
          ++mapcount;
          s = map(conn, schema_id, column_id, v);
          string_shard_cache[v] = s;
        }
      }

      find_file = files.find(s.shard_name);
      if( find_file != files.end()) {
        fo = find_file->second;
      } else {
        find_shard = shards.find(s.shard_name);
        std::string path;
        if(find_shard != shards.end()) {
          path = shared_path + "/loader/split/" + (find_shard->second).host+ "/" + (find_shard->second).db + "/" + table + "/";
        } else {
          std::cerr << "ERROR: shard not found in unordered_map!\n";
          exit(-1);
        }
        system(("mkdir -p " + path).c_str());
        path += std::string(md5(std::to_string(getpid()))) + ".txt";
        files_to_load[(find_shard->second).shard_name + "::" + (find_shard->second).db + "::" + table + "::" + path] = 1;
        if(!(fo = fopen(path.c_str(), "wb"))) {
          std::cerr << "Could not open: " << path << " for writing\n";
          exit(-1);
        }
        files[s.shard_name] = fo;
      }

      wb = fwrite(line, 1, rb, fo);
      if( wb != rb ) {
        std::cerr << "ERROR: io error\n";
        exit(-1);
      }

      ++linecount;

      if(ftell(fh) >= end) break;
    }
    std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now();
    std::cerr << "LINES: " << linecount << " MAPS: " << mapcount << " TIME(ms): " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count(); 

  }

 for ( auto it = files_to_load.begin(); it != files_to_load.end(); ++it ) {
    std::cerr << "|" << it->first  ;
 }
 std::cerr << "\n";
  
}
Exemplo n.º 13
0
Arquivo: dbe.c Projeto: caomw/grass
int db__driver_open_database(dbHandle * handle)
{
    char *name;
    dbConnection default_connection;
    MYSQL *res;

    db_get_connection(&default_connection);
    name = G_store(db_get_handle_dbname(handle));

    /* if name is empty use default_connection.databaseName */
    if (strlen(name) == 0)
	name = default_connection.databaseName;

    G_debug(3, "db_driver_open_database() mysql: database definition = '%s'",
	    name);

    /* Embedded version */
    {
	char *datadir, *database;
	char *server_args[4];
	char *buf;

	if (!replace_variables(name, &datadir, &database)) {
	    db_d_append_error(_("Unable parse MySQL embedded database name"));
	    db_d_append_error(mysql_error(connection));
	    db_d_report_error();
	    return DB_FAILED;
	}

	server_args[0] = "mesql";	/* this string is not used */
	G_asprintf(&buf, "--datadir=%s", datadir);
	server_args[1] = buf;
	/* With InnoDB it is very slow to close the database */
	server_args[2] = "--skip-innodb";	/* OK? */
	/* Without --bootstrap it complains about missing 
	 * mysql.time_zone_leap_second table */
	server_args[3] = "--bootstrap";	/* OK? */

	if (mysql_server_init(4, server_args, NULL)) {
	    db_d_append_error(_("Cannot initialize MySQL embedded server"));
	    db_d_append_error(mysql_error(connection));
	    db_d_report_error();
	    free(datadir);
	    free(database);
	    return DB_FAILED;
	}

	connection = mysql_init(NULL);
	mysql_options(connection, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);

	res =
	    mysql_real_connect(connection, NULL, NULL, NULL, database, 0,
			       NULL, 0);

	free(datadir);
	free(database);

	if (res == NULL) {
	    db_d_append_error(_("Unable to connect to MySQL embedded server: "));
	    db_d_append_error(mysql_error(connection));
	    db_d_report_error();
	    return DB_FAILED;
	}
    }

    return DB_OK;
}
Exemplo n.º 14
0
int main(int argc, char **argv)
{
	MYSQL mysql_conn; /* Connection handle */

    MYSQL_RES *mysql_result; /* Result handle */
    MYSQL_ROW mysql_row; /* Row data */

    MYSQL_FIELD *field;

    FILE *fp;



    int f1, f2, num_row, num_col,i;

    char a[100],b[100],q[100],re[100],sql[100]="select * from hanshu0 where name like '%";

    if((fp = fopen("txt//sou.txt","r"))==NULL)
    {
        printf("wrong");
        exit(0);
    }
    fscanf(fp,"%s",q);
 //   puts(q);

	if (mysql_init(&mysql_conn) != NULL)
    {

	//	printf("----------------Init succeeds!\n");

	}
    else
    {
		printf("Init fails!\n");
		exit(0);
	}
/*
	printf("user:");
	gets(a);
	printf("password:");
	gets(b);
    printf("which database?\n");
    gets(q);*/

    if (mysql_real_connect(
    &mysql_conn, "localhost","root",
    "root", "hanshu", MYSQL_PORT,
    NULL, 0) != NULL)
    {
 //       printf("----------------Link start!\n");
    }

    else
    {
        printf("----------------Connection fails.\n");
        exit(0);
    }


/*    printf("input your SQL:\n");

    gets(q);

    if(mysql_query(&mysql_conn, q))//成功返回0
    {
        printf("%s\n", mysql_error(&mysql_conn));
        exit(0);
    }*/

   /*  printf("输入你要搜索的函数名(模糊搜索):\n");
    gets(q);*/

    strcat(sql,q);
    strcat(sql,"%'");

    if(mysql_query(&mysql_conn, sql))//成功返回0
    {
        printf("%s\n", mysql_error(&mysql_conn));
        exit(0);
    }

    mysql_result = mysql_store_result(&mysql_conn);
/*    if(mysql_result!=NULL)
    {
        printf("-----------获取结果集成功\n");
    }
    else
    {
        printf("----------获取结果集失败\n");
        exit(0);
    }*/

//    printf("---------引用的行数:%llu\n",mysql_affected_rows(&mysql_conn));
//返回受之前执行的update,delete,insert等查询影响的行数
    //返回被一个更新操作修改的行数,但其他许多数据库将仅仅因为记录匹配where字句而把它视为已经更新过。


    num_col = mysql_num_fields(mysql_result);
/*
    num_row = mysql_num_rows(mysql_result);

    for (f1 = 0; f1 < num_row; f1++) {
         mysql_row = mysql_fetch_row(mysql_result);

         for (f2 = 0; f2 < num_col; f2++)
              printf("[Row %d, Col %d] ==> [%s]\n",f1+1, f2+1, mysql_row[f2]);
        }*/
if(mysql_affected_rows(&mysql_conn)==0)
{
    printf("nothing to search");
        system("pause");
    return 0;

}

 while ((mysql_row = mysql_fetch_row(mysql_result)))
  {
      for(i = 0; i < num_col; i++)
      {
          if (i == 0) { while(field = mysql_fetch_field(mysql_result)) {
                printf("%s ", field->name);
             }
          printf("\n");
          }

          printf("%s ", mysql_row[i] ? mysql_row[i] : "NULL");
      }
      printf("\n");
  }

    /* Free the result to release the heap memory*/
    mysql_free_result(mysql_result);

    mysql_close(&mysql_conn);
    system("pause");
	return 0;
}
Exemplo n.º 15
0
static int driver_mysql_connect(struct sql_db *_db)
{
	struct mysql_db *db = (struct mysql_db *)_db;
	const char *unix_socket, *host;
	unsigned long client_flags = db->client_flags;
	unsigned int secs_used;
	bool failed;

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

	sql_db_set_state(&db->api, SQL_DB_STATE_CONNECTING);

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

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

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

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

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

		if (db->api.connect_delay < secs_used)
			db->api.connect_delay = secs_used;
		sql_db_set_state(&db->api, SQL_DB_STATE_DISCONNECTED);
		i_error("%s: Connect failed to database (%s): %s - "
			"waiting for %u seconds before retry",
			mysql_prefix(db), db->dbname,
			mysql_error(db->mysql), db->api.connect_delay);
		return -1;
	} else {
		db->last_success = ioloop_time;
		sql_db_set_state(&db->api, SQL_DB_STATE_IDLE);
		return 1;
	}
}
Exemplo n.º 16
0
static BOOL OpenMySQL(DBIO *db)
{
#define NUMTOKEN 5 /* host:user:passwd:dbname:port */
char *token[NUMTOKEN];
int ntoken;
char copy[MAXPATHLEN+1];
MYSQL *unused;
static char *fid = "dbioOpen:OpenMySQL";

    strlcpy(copy, db->dbid, MAXPATHLEN+1);

    if ((ntoken = utilParse(copy, token, ":", NUMTOKEN, 0)) != NUMTOKEN) {
        logioMsg(db->lp, LOG_DEBUG, "%s: dbid parse error (got %d tokens, expected %d)", fid, ntoken, NUMTOKEN);
        logioMsg(db->lp, LOG_DEBUG, "%s: dbid = '%s'", fid, db->dbid);
        errno = EINVAL;
        return FALSE;
    }

    db->dbname = db->host = db->user = db->passwd = NULL;

    if (mysql_init(&db->mysql) == NULL) {
        logioMsg(db->lp, LOG_ERR, "%s: mysql_init: %s", fid, strerror(errno));
        free(db);
        return FALSE;
    }

    if (strcasecmp(token[0], "NULL") == 0) {
        db->host = NULL;
    } else if ((db->host = strdup(token[0])) == NULL) {
        logioMsg(db->lp, LOG_ERR, "%s: strdup: %s", fid, strerror(errno));
        dbioClose(db);
        return FALSE;
    }

    if (strcasecmp(token[1], "NULL") == 0) {
        db->user = NULL;
    } else if ((db->user = strdup(token[1])) == NULL) {
        logioMsg(db->lp, LOG_ERR, "%s: strdup: %s", fid, strerror(errno));
        dbioClose(db);
        return FALSE;
    }

    if (strcasecmp(token[2], "NULL") == 0) {
        db->passwd = NULL;
    } else if ((db->passwd = strdup(token[2])) == NULL) {
        logioMsg(db->lp, LOG_ERR, "%s: strdup: %s", fid, strerror(errno));
        dbioClose(db);
        return FALSE;
    }

    if (strcasecmp(token[3], "NULL") == 0) {
        db->dbname = NULL;
    } else if ((db->dbname = strdup(token[3])) == NULL) {
        logioMsg(db->lp, LOG_ERR, "%s: strdup: %s", fid, strerror(errno));
        dbioClose(db);
        return FALSE;
    }

    db->port = (unsigned int) atoi(token[4]);

    if ( (unused=mysql_real_connect(
        &db->mysql,
        db->host,
        db->user,
        db->passwd,
        db->dbname,
        db->port,
        NULL,
        0
    ))!=NULL) return TRUE;

    logioMsg(db->lp, LOG_ERR, "%s: mysql_real_connect: error %d: %s", fid, mysql_errno(&db->mysql), mysql_error(&db->mysql));
    dbioClose(db);

    return FALSE;

}
/**
 *	Verify the request token digest.
 *
 *		digest = HMAC_SHA1( EXPIRE_TIME|REQUEST_URI, client_secret )
 *
 *	@params:	*r				this http request;
 *				*client_id		API client id;
 *				*issued_time	the request issued time (unix epoch);
 *				*client_digest	the digest from the request token;
 *
 *	@return		NGX_DECLINE		if verification fails;
 *				NGX_OK			on success;
 *
 */
static ngx_int_t
ngx_apikey_verify( ngx_http_request_t *r, ngx_str_t *client_id, ngx_str_t *issued_time, ngx_str_t *client_digest ) {

	ngx_int_t	rc;

	ngx_str_t	computed_digest		= ngx_null_string;
	ngx_str_t	message				= ngx_null_string;
	ngx_str_t	client_secret		= ngx_null_string;
	ngx_str_t	expire_time			= ngx_null_string;


	ngx_apikey_access_filter_loc_conf_t  *lcf = NULL;

	MYSQL	*con = NULL;
	
	u_char *last = NULL;


	lcf = ngx_http_get_module_loc_conf(r, ngx_apikey_access_filter_module);
    if ( !lcf->enable ) {
		return NGX_OK;
    }

	
	rc = ngx_apikey_token_expire_time(r->pool, lcf->expire_time, &expire_time);
	if ( rc != NGX_OK ) {
		return NGX_ERROR;	
	}
	ngx_log_debug( NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "expire time -->: %V", &expire_time );
	
	if ( ngx_strcmp(issued_time->data, expire_time.data) > 0 ) {
		ngx_log_error( NGX_LOG_WARN, r->connection->log, 0, 
			"token issued time <%V> expired <%V>", issued_time, &expire_time );
		return NGX_ERROR;
	}
	
	//.Init MySQL connection object.	
	con = mysql_init( NULL );
	if ( con == NULL ) {
		ngx_log_error( NGX_LOG_ERR, r->connection->log, 0, "connecting to mysql" );
		return NGX_ERROR;
	}

	//.Connect to the specified MySQL database.
	if( !mysql_real_connect(
			con, 
			(const char *)lcf->dbhost, 
			(const char *)lcf->dbuser, 
			(const char *)lcf->dbpass, 
			(const char *)lcf->dbschema, 
			lcf->dbport, NULL,0) ) { 
		ngx_log_error( NGX_LOG_ERR, r->connection->log, 0, "Failed to connect to database: Error: %s", mysql_error(con) );
		return NGX_ERROR;
	}

	//.Fetch the client secret.
	rc = ngx_apikey_mysql_fetch_client_secret( r, con, client_id, &client_secret );
	if ( rc != NGX_OK ) {
		mysql_close( con );
		return NGX_DECLINED;
	}
	ngx_log_debug( NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "client secret fetched: %V", &client_secret );

	//.Close the database connection and free the allocated memory.
	mysql_close( con );

	//.Compute the token digest.
	message.len = issued_time->len + 1 + r->uri.len;
	message.data = ngx_pcalloc( r->pool, message.len + 1 );
	if ( message.data == NULL ) {
		ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "(%s) failed allocating memory", __func__ );
		return NGX_HTTP_INTERNAL_SERVER_ERROR;
	}
	last = (u_char *)ngx_copy( message.data, issued_time->data, issued_time->len );
	*last++ = '|';
	last = (u_char *)ngx_copy( last, r->uri.data, r->uri.len );
	*last = (u_char)'\0';

	ngx_log_debug( NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "message: %V", &message );

	rc = ngx_apikey_hamac_sha1_digest( r->pool, &client_secret, &message, &computed_digest );
	if ( rc != NGX_OK ) {
		return NGX_DECLINED;
	}
	ngx_log_debug( NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "calculated digest: %V", &computed_digest );

	//.Compare the digest from the request and the calculated digest.
	if ( ngx_strcmp(computed_digest.data, client_digest->data) != 0 ) {
		return NGX_DECLINED;	
	}

	return NGX_OK;
}
Exemplo n.º 18
0
//write data on emoncms3 server via mysql
static void vSendDataMysql(void)
{
	MYSQL *conn;
	MYSQL_RES *res;
	MYSQL_ROW row;

	int iTime=0;
	time_t tTime=_tTime;
	int iDay,iHour;
	char acBuf[MAX_REQ_SQL];
	conn = mysql_init(NULL);
	/* Connect to database */
	if (!mysql_real_connect(conn, _acServer,
			_acUser, _acPassword, _acDatabase, 0, NULL, 0)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		return;
	}
	/* GET last entry */
	sprintf(acBuf,"SELECT MAX(time)  FROM  `%s`",_acFeed);
	if (mysql_query(conn, acBuf)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		return;
	}
	res = mysql_use_result(conn);
	while ((row = mysql_fetch_row(res)) != NULL)
		iTime=atoi(row[0]);



	//save KWatt per hour
	tTime=_tTime-(NB_JOUR*24)*3600;
	for(iDay=NB_JOUR-1;iDay>=0;iDay--)
	{
		for(iHour=0;iHour<NB_HEURE;iHour++)
		{
			char acCmd[255];
			float fWatt=afKWatt[iDay][iHour]*1000;

			//update last entry
			if((tTime==iTime)&&(afKWatt[iDay][iHour]!=0)&&(iDay*NB_HEURE+NB_HEURE-iHour!=6144))
			{
				printf("update %ld;%f;%s",tTime,fWatt,ctime(&tTime));

				sprintf(acBuf,"UPDATE %s SET data = %f  WHERE time=%ld",_acFeed ,fWatt,tTime);
				if (mysql_query(conn, acBuf)) {
					fprintf(stderr, "%s\n", mysql_error(conn));
					return;
				}
			}
			//insert new one
			if((tTime>iTime)&&(afKWatt[iDay][iHour]!=0)&&(iDay*NB_HEURE+NB_HEURE-iHour!=6144))
			{
				printf("insert %ld;%f;%s",tTime,fWatt,ctime(&tTime));
				sprintf(acBuf,"INSERT INTO %s (time,data) VALUES(%ld,%f)",_acFeed ,tTime,fWatt);
				if (mysql_query(conn, acBuf)) {
					fprintf(stderr, "%s\n", mysql_error(conn));
					return;
				}
			}
			tTime=_tTime-(iDay*24+(NB_HEURE-iHour-1))*60*60;
		}
	}

	/* close connection */
	mysql_free_result(res);
	mysql_close(conn);


}
Exemplo n.º 19
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)
    {
        DETAIL_LOG( "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));

        /*----------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
        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
        PExecute("SET NAMES `utf8`");
        PExecute("SET CHARACTER SET `utf8`");

        return true;
    }
    else
    {
        sLog.outError( "Could not connect to MySQL database at %s: %s\n",
            host.c_str(),mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Exemplo n.º 20
0
bool MySQLConnection::Open() {
    MYSQL *mysqlInit;
    mysqlInit = mysql_init(NULL);
    if (!mysqlInit) {
        sLog->outError("Could not initialize Mysql connection to database `%s`",
                m_connectionInfo.database.c_str());
        return false;
    }

    int port;
    char const* unix_socket;

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

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

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

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

        // set connection properties to UTF8 to properly handle locales for different
        // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
        mysql_set_character_set(m_Mysql, "utf8");
        return PrepareStatements();
    } else {
        sLog->outError("Could not connect to MySQL database at %s: %s\n",
                m_connectionInfo.host.c_str(), mysql_error(mysqlInit));
        mysql_close(mysqlInit);
        return false;
    }
}
Exemplo n.º 21
0
void *
mysql_connector(void *args) {
    char *neaf;

    char *uid;
    char *birth_year;
    char *birth_month;
    char *birth_day;
    char *constellation;
    char *blood_types;
    char *sex;
    char *home_nation;
    char *home_pro;
    char *home_city;
    char *now_nation;
    char *now_pro;
    char *now_city;

    char *header;

    char *edu;
    char *school;
    char *department;
    char *class_;
    char *year;

    char *begin_year;
    char *begin_month;
    char *end_year;
    char *end_month;
    char *company;
    char *post;

    char *update_proto;
    char *delete_proto;
    char *insert_proto;

    int mysql_query_rc;
    int flag;

    void *pop_string;
    char *raw_string;
    char *tmp;
    unsigned long long affect;
    int raw_len;

    MYSQL mysql;

    my_bool reconnect = 1;

    mysql_init(&mysql);
    mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);

    /* Connect to mysql server */
    if(!mysql_real_connect(
                &mysql, server.mysqlIP, server.mysqlUser,
                server.mysqlPasswd, server.db, MYSQL_PORT, NULL, 0)) {
        log4c_category_log(
                log_handler, LOG4C_PRIORITY_ERROR,
                "MySQL_conn: MySQL connecotr error");
        return ((void *)-1);
    }
    log4c_category_log(
            log_handler, LOG4C_PRIORITY_INFO,
            "MySQL_conn: MySQL connecotr start up");

    /* Turn on auto commint */
    mysql_autocommit(&mysql, 1);

    if(!mysql_ping(&mysql)) {
        mysql_query(&mysql, "SET NAMES UTF8");
        log4c_category_log(
                log_handler, LOG4C_PRIORITY_TRACE,
                "MySQL_conn: Mysql Server set utf-8");
        log4c_category_log(
                log_handler, LOG4C_PRIORITY_INFO,
                "MySQL_conn: %s", "SET NAMES UTF8");
    } else {
        log4c_category_log(
                log_handler, LOG4C_PRIORITY_FATAL,
                "MySQL_conn: lost connect to Mysql Server");
        return ((void *)0);
    }

    int malloc_size;

    while(1) {
        update_proto = NULL;
        delete_proto = NULL;
        insert_proto = NULL;
        apr_queue_pop(queue, &pop_string);

        raw_string = pop_string;
        raw_len = strlen(raw_string);

        if(NULL == raw_string) {
            log4c_category_log(
                    log_handler, LOG4C_PRIORITY_NOTICE,
                    "MySQL_conn: POP from queue is NULL");
            continue;
        }

        log4c_category_log(
                log_handler, LOG4C_PRIORITY_TRACE,
                "MySQL_conn: POP from queue: %s", raw_string);

        /* Get flag */
        tmp = strsep(&raw_string, ":");
        flag= atoi(tmp);

        /* Keep elegant */
        /* If Basic Info */
        if(1 == flag) {
            log4c_category_log(
                    log_handler, LOG4C_PRIORITY_TRACE,
                    "MySQL_conn_basic: post basic");
            /* Split raw string */
            uid = strsep(&raw_string, ",");
            birth_year = strsep(&raw_string, ",");
            birth_month = strsep(&raw_string, ",");
            birth_day = strsep(&raw_string, ",");
            constellation = strsep(&raw_string, ",");

            blood_types = strsep(&raw_string, ",");
            sex = strsep(&raw_string, ",");

            home_nation = strsep(&raw_string, ",");
            home_pro = strsep(&raw_string, ",");
            home_city = strsep(&raw_string, ",");

            now_nation = strsep(&raw_string, ",");
            now_pro = strsep(&raw_string, ",");
            now_city = strsep(&raw_string, ",");

            /* Magic number 350 is SQL proto length */
            malloc_size = raw_len + 350;
            update_proto = xmalloc(malloc_size);
            snprintf(update_proto, (malloc_size), "update base_user_info set\
                    birth_year=%s, birth_month=%s, birth_day=%s,\
                    constellation=%s, blood_types=%s, sex=%s,\
                    home_nation='%s', home_pro='%s', home_city='%s',\
                    now_nation='%s', now_pro='%s', now_city='%s'\
                    where uid=%s", 
                    birth_year, birth_month, birth_day,
                    constellation, blood_types, sex,
                    home_nation, home_pro, home_city,
                    now_nation, now_pro, now_city,
                    uid);
            log4c_category_log(
                    log_handler, LOG4C_PRIORITY_TRACE,
                    "MySQL_conn_basic: updata proto: %s", update_proto);
            /* query mysql */
            if(!mysql_ping(&mysql)) {
                mysql_query(&mysql, "SET NAMES UTF8");
                mysql_query_rc = mysql_query(&mysql, update_proto);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_TRACE,
                        "MySQL_conn_basic: Mysql Server update return: %d",
                        mysql_query_rc);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_INFO,
                        "MySQL_conn_basic: %s", update_proto);
            } else {
                /* Dump to file */
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_ERROR,
                        "MySQL_conn_basic: lost connect to Mysql Server");
                fprintf(server.dump_file_handler, "%s\n", update_proto);
                fflush(server.dump_file_handler);
            }

            if(mysql_field_count(&mysql) == 0) {
                affect = (unsigned long long )mysql_affected_rows(&mysql);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_TRACE,
                        "MySQL_conn_basic: update affect:%d", affect);
            }
            /* new user */
            if(0 == affect) {
                malloc_size = raw_len + 358;
                insert_proto = xmalloc(malloc_size);
                snprintf(insert_proto, malloc_size,
                        "insert into base_user_info set\
                        birth_year=%s, birth_month=%s, birth_day=%s,\
                        constellation=%s, blood_types=%s, sex=%s,\
                        home_nation='%s', home_pro='%s', home_city='%s',\
                        now_nation='%s', now_pro='%s', now_city='%s',\
                        uid=%s", 
                        birth_year, birth_month, birth_day,
                        constellation, blood_types, sex,
                        home_nation, home_pro, home_city,
                        now_nation, now_pro, now_city,
                        uid);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_TRACE,
                        "MySQL_conn_basic: insert proto: %s", insert_proto);
                if(!mysql_ping(&mysql)) {
                    mysql_query(&mysql, "SET NAMES UTF8");
                    mysql_query_rc = mysql_query(&mysql, insert_proto);
                    log4c_category_log(
                            log_handler, LOG4C_PRIORITY_TRACE,
                            "MySQL_conn_basic: Mysql Server insert return: %d",
                            mysql_query_rc);
                    log4c_category_log(
                            log_handler, LOG4C_PRIORITY_INFO,
                            "MySQL_conn_basic: %s", insert_proto);
                } else {
                    log4c_category_log(
                            log_handler, LOG4C_PRIORITY_ERROR,
                            "MySQL_conn_basic: lost connect to Mysql Server");
                    /* Dump to file */
                    fprintf(server.dump_file_handler, "%s\n", insert_proto);
                    fflush(server.dump_file_handler);
                }
                affect = (unsigned long long )mysql_affected_rows(&mysql);
                log4c_category_log(
                        log_handler, LOG4C_PRIORITY_TRACE,
                        "MySQL_conn_basic: insert affect:%d", affect);
            }

            xfree(insert_proto);
            xfree(update_proto);
        }
Exemplo n.º 22
0
/**
 * Monitor an individual server
 *
 * @param handle        The MySQL Monitor object
 * @param database      The database to probe
 */
static void
monitorDatabase(MONITOR *mon, MONITOR_SERVERS *database)
{
    GALERA_MONITOR* handle = (GALERA_MONITOR*)mon->handle;
MYSQL_ROW	row;
MYSQL_RES	*result,*result2;
int		isjoined = 0;
char		*uname  = mon->user;
char		*passwd = mon->password;
unsigned long int	server_version = 0;
char 			*server_string;

	if (database->server->monuser != NULL)
	{
		uname = database->server->monuser;
		passwd = database->server->monpw;
	}
	if (uname == NULL)
		return;

	/* Don't even probe server flagged as in maintenance */
	if (SERVER_IN_MAINT(database->server))
		return;

	/** Store previous status */
	database->mon_prev_status = database->server->status;

	if (database->con == NULL || mysql_ping(database->con) != 0)
	{
		char *dpwd = decryptPassword(passwd);
		int connect_timeout = mon->connect_timeout;
		int read_timeout = mon->read_timeout;
		int write_timeout = mon->write_timeout;

		if(database->con)
		    mysql_close(database->con);
		database->con = mysql_init(NULL);

		mysql_options(database->con, MYSQL_OPT_CONNECT_TIMEOUT, (void *)&connect_timeout);
		mysql_options(database->con, MYSQL_OPT_READ_TIMEOUT, (void *)&read_timeout);
		mysql_options(database->con, MYSQL_OPT_WRITE_TIMEOUT, (void *)&write_timeout);

		if (mysql_real_connect(database->con, database->server->name,
			uname, dpwd, NULL, database->server->port, NULL, 0) == NULL)
		{
			free(dpwd);

			server_clear_status(database->server, SERVER_RUNNING);

			/* Also clear Joined, M/S and Stickiness bits */
			server_clear_status(database->server, SERVER_JOINED);
			server_clear_status(database->server, SERVER_SLAVE);
			server_clear_status(database->server, SERVER_MASTER);
			server_clear_status(database->server, SERVER_MASTER_STICKINESS);

			if (mysql_errno(database->con) == ER_ACCESS_DENIED_ERROR)
			{
				server_set_status(database->server, SERVER_AUTH_ERROR);
			}

			database->server->node_id = -1;

			if (mon_status_changed(database) && mon_print_fail_status(database))
			{
				LOGIF(LE, (skygw_log_write_flush(
					LOGFILE_ERROR,
					"Error : Monitor was unable to connect to "
					"server %s:%d : \"%s\"",
					database->server->name,
					database->server->port,
					mysql_error(database->con))));
			}

			return;
		}
		else
		{
			server_clear_status(database->server, SERVER_AUTH_ERROR);
		}
		free(dpwd);
	}

	/* If we get this far then we have a working connection */
	server_set_status(database->server, SERVER_RUNNING);

	/* get server version string */
	server_string = (char *)mysql_get_server_info(database->con);
	if (server_string) {
		database->server->server_string = realloc(database->server->server_string, strlen(server_string)+1);
		if (database->server->server_string)
			strcpy(database->server->server_string, server_string);
	}	

	/* Check if the the Galera FSM shows this node is joined to the cluster */
	if (mysql_query(database->con, "SHOW STATUS LIKE 'wsrep_local_state'") == 0
		&& (result = mysql_store_result(database->con)) != NULL)
	{
		if(mysql_field_count(database->con) < 2)
		{
		    mysql_free_result(result);
		    skygw_log_write(LE,"Error: Unexpected result for \"SHOW STATUS LIKE 'wsrep_local_state'\". Expected 2 columns."
				    " MySQL Version: %s",version_str);
		    return;
		}

		while ((row = mysql_fetch_row(result)))
		{
			if (strcmp(row[1], "4") == 0) 
				isjoined = 1;
	
			/* Check if the node is a donor and is using xtrabackup, in this case it can stay alive */
			else if (strcmp(row[1], "2") == 0 && handle->availableWhenDonor == 1) {
				if (mysql_query(database->con, "SHOW VARIABLES LIKE 'wsrep_sst_method'") == 0
					&& (result2 = mysql_store_result(database->con)) != NULL)
				{
				    		if(mysql_field_count(database->con) < 2)
						{
						    mysql_free_result(result);
						    mysql_free_result(result2);
						    skygw_log_write(LE,"Error: Unexpected result for \"SHOW VARIABLES LIKE 'wsrep_sst_method'\". Expected 2 columns."
							    " MySQL Version: %s",version_str);
						    return;
						}
					while ((row = mysql_fetch_row(result)))
					{
						if (strncmp(row[1], "xtrabackup", 10) == 0)
							isjoined = 1;
					}
					mysql_free_result(result2);
				}
			}
		}
		mysql_free_result(result);
	}

	/* Check the the Galera node index in the cluster */
	if (mysql_query(database->con, "SHOW STATUS LIKE 'wsrep_local_index'") == 0
		&& (result = mysql_store_result(database->con)) != NULL)
	{
		long local_index = -1;

		if(mysql_field_count(database->con) < 2)
		{
		    mysql_free_result(result);
		    skygw_log_write(LE,"Error: Unexpected result for \"SHOW STATUS LIKE 'wsrep_local_index'\". Expected 2 columns."
							    " MySQL Version: %s",version_str);
		    return;
		}

		while ((row = mysql_fetch_row(result)))
		{
			local_index = strtol(row[1], NULL, 10);
			if ((errno == ERANGE && (local_index == LONG_MAX
				|| local_index == LONG_MIN)) || (errno != 0 && local_index == 0))
			{
				local_index = -1;
			}
			database->server->node_id = local_index;
		}
		mysql_free_result(result);
	}

	if (isjoined)
		server_set_status(database->server, SERVER_JOINED);
	else
		server_clear_status(database->server, SERVER_JOINED);
}
Exemplo n.º 23
0
int main(int argc, char *argv[]) {
	struct configuration conf= { NULL, NULL, NULL, 0 };

	GError *error= NULL;
	GOptionContext *context;

	g_thread_init(NULL);

	init_mutex= g_mutex_new();

	if(db == NULL && source_db != NULL){
		db = g_strdup(source_db);
	}

	context= g_option_context_new("multi-threaded MySQL loader");
	GOptionGroup *main_group= g_option_group_new("main", "Main Options", "Main Options", NULL, NULL);
	g_option_group_add_entries(main_group, entries);
	g_option_group_add_entries(main_group, common_entries);
	g_option_context_set_main_group(context, main_group);
	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("option parsing failed: %s, try --help\n", error->message);
		exit(EXIT_FAILURE);
	}
	g_option_context_free(context);

	//prompt for password if it's NULL
	if ( sizeof(password) == 0 || ( password == NULL && askPassword ) ){
		password = passwordPrompt();
	}

	if (program_version) {
		g_print("myloader %s, built against MySQL %s\n", VERSION, MYSQL_VERSION_STR);
		exit(EXIT_SUCCESS);
	}

	set_verbose(verbose);

	if (!directory) {
		g_critical("a directory needs to be specified, see --help\n");
		exit(EXIT_FAILURE);
	} else {
		char *p= g_strdup_printf("%s/metadata", directory);
		if (!g_file_test(p, G_FILE_TEST_EXISTS)) {
			g_critical("the specified directory is not a mydumper backup\n");
			exit(EXIT_FAILURE);
		}
	}
	MYSQL *conn;
	conn= mysql_init(NULL);

	configure_connection(conn,"myloader");
	if (!mysql_real_connect(conn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Error connection to database: %s", mysql_error(conn));
		exit(EXIT_FAILURE);
	}

	if (mysql_query(conn, "SET SESSION wait_timeout = 2147483")){
		g_warning("Failed to increase wait_timeout: %s", mysql_error(conn));
	}

	if (!enable_binlog)
		mysql_query(conn, "SET SQL_LOG_BIN=0");

	mysql_query(conn, "/*!40014 SET FOREIGN_KEY_CHECKS=0*/");
	conf.queue= g_async_queue_new();
	conf.ready= g_async_queue_new();

	guint n;
	GThread **threads= g_new(GThread*, num_threads);
	struct thread_data *td= g_new(struct thread_data, num_threads);
	for (n= 0; n < num_threads; n++) {
		td[n].conf= &conf;
		td[n].thread_id= n+1;
		threads[n]= g_thread_create((GThreadFunc)process_queue, &td[n], TRUE, NULL);
		g_async_queue_pop(conf.ready);
	}
	g_async_queue_unref(conf.ready);

	g_message("%d threads created", num_threads);

	restore_databases(&conf, conn);

	for (n= 0; n < num_threads; n++) {
		struct job *j= g_new0(struct job, 1);
		j->type = JOB_SHUTDOWN;
		g_async_queue_push(conf.queue, j);
	}

	for (n= 0; n < num_threads; n++) {
		g_thread_join(threads[n]);
	}

	restore_schema_post(conn);

	restore_schema_view(conn);

	restore_schema_triggers(conn);

	g_async_queue_unref(conf.queue);
	mysql_close(conn);
	mysql_thread_end();
	mysql_library_end();
	g_free(directory);
	g_free(td);
	g_free(threads);

	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
}
Exemplo n.º 24
0
Arquivo: exec.c Projeto: kien8995/loki
void exec()
{
    int problemid;
    int userid;
    long int tokenid;
    char execfilename[256];
    memset(execfilename, '\0', sizeof(execfilename));

    MYSQL *conn;
    conn = mysql_init(NULL);
    mysql_real_connect(conn, server, user, password, database, 0, NULL, 0);

    MYSQL_RES * res;
    MYSQL_ROW row;

    char *query = "SELECT problemid, userid, tokenid, file FROM exec_table";
    mysql_query(conn, query);

    res = mysql_store_result(conn);

    if(res)
    {
        while( ( row = mysql_fetch_row(res) ) )
        {
            problemid = atoi(row[0]);
            userid = atoi(row[1]);
            tokenid = atol(row[2]);
            strcpy(execfilename, row[3]);

            /*
             * again we need to get this from a conf file
             * for now refer main.c to change execfilepath_prefix
             */

            char execfilename_fully_qualified[strlen(execfilepath_prefix)+strlen(execfilename)+1];
            memset(execfilename_fully_qualified, '\0', sizeof(execfilename_fully_qualified));

            sprintf(execfilename_fully_qualified, "%s%s", execfilepath_prefix, execfilename);

            int pid;
            int insyscall = 0;
            FILE *fp_pipe;
            struct user_regs_struct uregs;

            struct tms tms_start, tms_end;

            chroot(chroot_jail_path);
            chdir("/");

            char judgeoutput_query[256];
            memset(judgeoutput_query, '\0', sizeof(judgeoutput_query));

            char diffcmd[256];
            memset(diffcmd, '\0', sizeof(diffcmd));

            sprintf(judgeoutput_query, "SELECT input, output FROM solutions WHERE problemid=%d", problemid);
            mysql_query(conn, judgeoutput_query);

            MYSQL_RES *tempres = mysql_store_result(conn);

            MYSQL_ROW temprow;

            while ( ( temprow = mysql_fetch_row(tempres) ) )
            {
                char input[32], output[32];
                memset(input, '\0', sizeof(input));
                memset(output, '\0', sizeof(output));

                strcpy(input, temprow[0]);
                strcpy(output, temprow[1]);

                char inputfile[strlen(inputfilepath_prefix)+strlen(input)+1];
                char outputfile[strlen(outputfilepath_prefix)+strlen(output)+1];
                memset(inputfile, '\0', sizeof(inputfile));
                memset(outputfile, '\0', sizeof(outputfile));

                sprintf(inputfile, "%s%s", inputfilepath_prefix, input);
                sprintf(outputfile, "%s%s", outputfilepath_prefix, output);

                times(&tms_start);
                if ( !(pid = fork()) )
                {
                    /*apply restrictions and all*/
                    struct rlimit rl;
                    getrlimit(RLIMIT_CPU, &rl);

                    rl.rlim_cur = 3;
                    rl.rlim_max = 3;

                    /*a restriction on just the CPU time, TODO:need to add more like stack size*/
                    setrlimit(RLIMIT_CPU, &rl);

                    /*Redirect standard input to the input file*/
                    freopen(inputfile, "r", stdin);

                    /*This is supposed to be a temp file, gets overwritten every time*/
                    freopen("/home/judge/outfile", "w", stdout);

                    ptrace(PTRACE_TRACEME, 0, NULL, NULL);
                    execl(execfilename_fully_qualified, execfilename, NULL);
                }

                else if ( pid )
                {
                    int status;
                    ptrace(PTRACE_SYSCALL, pid, NULL, NULL);

                    while(1)
                    {
                        wait(&status);
                        if ( WIFEXITED(status) )
                            break;

                        /*entry to syscall*/
                        if (!insyscall)
                        {
                            insyscall = 1;
                            /*
                             * Get the values stored in registers for the child process
                             * We need the value in EAX to identify the system call being attempted
                             */
                            ptrace(PTRACE_GETREGS, pid, NULL, &uregs);
                        }
                        /*exit from syscall*/
                        else
                            insyscall = 0;

                        ptrace(PTRACE_SYSCALL, pid, NULL, NULL);
                    } //end of child

                    times(&tms_end);

                    sprintf(diffcmd, "diff --ignore-space-change %s %s", "home/judge/outfile", outputfile);
                    /*Open a pipe to the diff command*/
                    fp_pipe = popen(diffcmd, "r");

                    if ( WEXITSTATUS(status) == 0 && getc(fp_pipe) == EOF )
                    {
                        pclose(fp_pipe);
                        /*This uses the clock ticks returned by times() to calculate the "user CPU time"*/
                        clock_t real = tms_end.tms_cutime - tms_start.tms_utime;
                        double running_time = real / (double)sysconf(_SC_CLK_TCK);

                        /*
                         * The following uses getrusage() to get the "user CPU time" of the child process.
                         * Uncomment it and comment out the code using times() to see if there is any difference
                         */

                        /*struct rusage ru;
                        getrusage(RUSAGE_CHILDREN, &ru);

                        struct timeval tv = ru.ru_utime;

                        float running_time = (float)tv.tv_sec+(float)(tv.tv_usec/1000000.0);*/

                        detect_update_score(conn, userid, problemid, tokenid, running_time);
                    }
                    else
                        printf("Diff not matching\n");

                    /*Delete entry of exec file from DB after it has been processed*/
                    char delete_query[256];
                    memset(delete_query, '\0', sizeof(delete_query));

                    sprintf(delete_query, "DELETE FROM exec_table WHERE userid=%d AND problemid=%d AND tokenid=%ld", userid, problemid, tokenid);

                    mysql_query(conn, delete_query);
                }
            }
            mysql_free_result(tempres);
        }
        mysql_free_result(res);
    }
}
Exemplo n.º 25
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;
}
Exemplo n.º 26
0
int
main (int argc, char **argv)
{

	MYSQL mysql;
	MYSQL_RES *res;
	MYSQL_ROW row;

	/* should be status */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field], row[slave_sql_field], seconds_behind_field!=-1?row[seconds_behind_field]:"Unknown");
			if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

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

			if ((seconds_behind_field != -1) && (strcmp (row[seconds_behind_field], "NULL") != 0)) {
				double value = atof(row[seconds_behind_field]);
				int status;

				status = get_status(value, my_threshold);

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

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

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

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

	return STATE_OK;
}
Exemplo n.º 27
0
int main()
{

	int Val;


	mysql_init(&conn);//연결 지시자 초기화
	connection = mysql_real_connect(&conn, DB_HOST, DB_USER, DB_PASS, DB_NAME, 3306, (char *)NULL, 0);//mysql서버에 직접 접근

	if (connection == NULL){
		fprintf(stderr, "MySQL Connection Error :%s", mysql_error(&conn));
		return 1;
	}




	while (1)
	{
		icnt = checkfile();

		menulist();
		fprintf(stdout, "Menu Select = ");
		fscanf(stdin, "%d", &Val);
		getchar();

		switch (Val)
		{

		case 1:
		{
			while (1)
			{
				Datainput();
    			icnt++;
				break;
			}
			break;
		}
		case 2:{
			while (1){
				deleteData();
				icnt--;
				break;
			}
		}

		case 3:
		{
			datalist();
			break;
		}

		case 4:{
			run_server();
			break;
		}

		case 5:
		{
			printf("Program Exit!!\n");
			return 0;
		}
		default:
			return 0;
		}
	}

	return 0;
}
Exemplo n.º 28
0
int main(int argc, char **argv)
{
	MYSQL *conn;
	char stat[SQL_STATEMENT_LENGTH + 1];

	FILE *fp_enc_ssl_cert;
	int len, enc_ssl_cert_size;
	char enc_ssl_cert_data[1000*1024];
	char enc_ssl_cert_chunk[sizeof(enc_ssl_cert_data)*2+1];
  	char query[sizeof(enc_ssl_cert_chunk)+sizeof(stat)+1];

	FILE *fp_enc_ssl_cert_hash;
	char enc_ssl_cert_hash[SHA1_DIGEST_LENGTH + 1];

  	conn = mysql_init(NULL);
  	if(!conn) 
  	{
      		printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      		exit(1);
  	}

	// Connect a database
  	if(mysql_real_connect(conn, DB_IP, DB_USERNAME, DB_PASSWD, EMUDB_NAME, 0, NULL, 0) == NULL) 
  	{
      		printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      		exit(1);
  	}

	// Read an SSL certificate from file
	fp_enc_ssl_cert = fopen("../Certs/EmU_admin.pem", "rb");
	if(fp_enc_ssl_cert == NULL)
	{
		printf("Could not open file \"enc_EmU_admin_ssl_cert\"\n");
      		exit(1);
	}

  	enc_ssl_cert_size = fread(enc_ssl_cert_data, 1, sizeof(enc_ssl_cert_data), fp_enc_ssl_cert);
	fclose(fp_enc_ssl_cert);

	// Read an SSL certificate hash from file
	fp_enc_ssl_cert_hash = fopen("../Certs/enc_EmU_admin_ssl_cert_hash", "rb");
	if(fp_enc_ssl_cert == NULL)
	{
		printf("Could not open file \"enc_EmU_admin_ssl_cert_hash\"\n");
      		exit(1);
	}

  	fread(enc_ssl_cert_hash, 1, SHA1_DIGEST_LENGTH, fp_enc_ssl_cert_hash);
	fclose(fp_enc_ssl_cert_hash);

	// Insert data into an ESA__BASIC_AUTHORITY_INFO table
	sprintf(stat, "INSERT INTO %s(authority_name, mail_server_url, authority_email_address, authority_email_passwd) "
		"VALUES('Emergency', 'smtp://smtp.gmail.com:587', 'emergency.staff.authority@gmail.com', 'bright23')", 
		ESA__BASIC_AUTHORITY_INFO);

	if(mysql_query(conn, stat))
  	{
      		printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      		exit(1);
  	}

	// Insert data into an ESA__ADMINS table (echo \"bright23qwertyui\" | sha1sum)
	mysql_real_escape_string(conn, enc_ssl_cert_chunk, enc_ssl_cert_data, enc_ssl_cert_size);
	sprintf(stat, "INSERT INTO %s(username, salted_passwd_hash, salt_value, email_address, passwd_resetting_code, enc_ssl_cert, enc_ssl_cert_hash) "
		      "VALUES('admin', '1deb859d0bc645529deccf254815a7d1c3700d5c', 'qwertyui', 'mr.thummavet@gmail.com', '', '%%s', '%s')", ESA__ADMINS, enc_ssl_cert_hash);

	len = snprintf(query, sizeof(stat)+sizeof(enc_ssl_cert_chunk), stat, enc_ssl_cert_chunk);
  	if(mysql_real_query(conn, query, len))
	{
      		printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      		exit(1);
  	}

  	mysql_close(conn);
	return 0;
}
Exemplo n.º 29
0
static int mysql_drive_session(eventer_t e, int mask, void *closure,
                                  struct timeval *now) {
  const char *dsn, *sql;
  char sql_buff[8192];
  char dsn_buff[512];
  mysql_check_info_t *ci = closure;
  noit_check_t *check = ci->check;
  struct timeval t1, t2, diff;
  mtev_hash_table dsn_h = MTEV_HASH_EMPTY;
  const char *host=NULL;
  const char *user=NULL;
  const char *password=NULL;
  const char *dbname=NULL;
  const char *port_s=NULL;
  const char *socket=NULL;
  const char *sslmode=NULL;
  u_int32_t port;
  unsigned long client_flag = CLIENT_IGNORE_SIGPIPE;
  unsigned int timeout;

  if(mask & (EVENTER_READ | EVENTER_WRITE)) {
    /* this case is impossible from the eventer.  It is called as
     * such on the synchronous completion of the event.
     */
    mysql_log_results(ci->self, ci->check);
    mysql_cleanup(ci->self, ci->check);
    check->flags &= ~NP_RUNNING;
    return 0;
  }
  switch(mask) {
    case EVENTER_ASYNCH_WORK:
      ci->connect_duration = NULL;
      ci->query_duration = NULL;

      FETCH_CONFIG_OR(dsn, "");
      noit_check_interpolate(dsn_buff, sizeof(dsn_buff), dsn,
                             &ci->attrs, check->config);

      mysql_parse_dsn(dsn_buff, &dsn_h);
      mtev_hash_retrieve(&dsn_h, "host", strlen("host"), (void**)&host);
      mtev_hash_retrieve(&dsn_h, "user", strlen("user"), (void**)&user);
      mtev_hash_retrieve(&dsn_h, "password", strlen("password"), (void**)&password);
      mtev_hash_retrieve(&dsn_h, "dbname", strlen("dbname"), (void**)&dbname);
      mtev_hash_retrieve(&dsn_h, "port", strlen("port"), (void**)&port_s);
      if(mtev_hash_retrieve(&dsn_h, "sslmode", strlen("sslmode"), (void**)&sslmode) &&
         !strcmp(sslmode, "require"))
        client_flag |= CLIENT_SSL;
      port = port_s ? strtol(port_s, NULL, 10) : 3306;
      mtev_hash_retrieve(&dsn_h, "socket", strlen("socket"), (void**)&socket);

      ci->conn = mysql_init(NULL); /* allocate us a handle */
      if(!ci->conn) AVAIL_BAIL("mysql_init failed");
      timeout = check->timeout / 1000;
      mysql_options(ci->conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
      if(!mysql_real_connect(ci->conn, host, user, password,
                             dbname, port, socket, client_flag)) {
        mtevL(noit_stderr, "error during mysql_real_connect: %s\n",
          mysql_error(ci->conn));
        AVAIL_BAIL(mysql_error(ci->conn));
      }
      if(mysql_ping(ci->conn))
        AVAIL_BAIL(mysql_error(ci->conn));

#if MYSQL_VERSION_ID >= 50000
      if (sslmode && !strcmp(sslmode, "require")) {
        /* mysql has a bad habit of silently failing to establish ssl and
         * falling back to unencrypted, so after making the connection, let's 
         * check that we're actually using SSL by checking for a non-NULL 
         * return value from mysql_get_ssl_cipher().
         */
        if (mysql_get_ssl_cipher(ci->conn) == NULL) {
          mtevL(nldeb, "mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
          AVAIL_BAIL("mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
        }
      }
#endif

      gettimeofday(&t1, NULL);
      sub_timeval(t1, check->last_fire_time, &diff);
      ci->connect_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
      ci->connect_duration = &ci->connect_duration_d;

      FETCH_CONFIG_OR(sql, "");
      noit_check_interpolate(sql_buff, sizeof(sql_buff), sql,
                             &ci->attrs, check->config);
      if (mysql_query(ci->conn, sql_buff))
        AVAIL_BAIL(mysql_error(ci->conn));

      gettimeofday(&t2, NULL);
      sub_timeval(t2, t1, &diff);
      ci->query_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
      ci->query_duration = &ci->query_duration_d;

      ci->result = mysql_store_result(ci->conn);
      if(!ci->result) AVAIL_BAIL("mysql_store_result failed");
      ci->rv = mysql_num_rows(ci->result);
      mysql_ingest_stats(ci);
      if(ci->result) {
        MYSQL_RES *result_swap = ci->result;
        ci->result = NULL;
        mysql_free_result(result_swap);
      }
      if(ci->conn) {
        MYSQL *conn_swap = ci->conn;
        ci->conn = NULL;
        mysql_close(conn_swap);
      }
      ci->timed_out = 0;
      mtev_hash_destroy(&dsn_h, free, free);
      return 0;
      break;
    case EVENTER_ASYNCH_CLEANUP:
      /* This sets us up for a completion call. */
      e->mask = EVENTER_READ | EVENTER_WRITE;
      break;
    default:
      abort();
  }
  return 0;
}
Exemplo n.º 30
0
int db_connect(char *database, MYSQL *mysql) {
    char logmessage[LOGSIZE];
    MYSQL *db;
    int tries;
    int result;
    char *hostname;
    char *socket;

    if ((hostname = strdup(set.dbhost)) == NULL) {
        snprintf(logmessage, LOGSIZE-1, "ERROR: malloc(): strdup() failed\n");
        cacti_log(logmessage);
        exit_cactid();
    }

    if ((socket = strstr(hostname,":"))) {
        *socket++ = 0x0;
    }

    /* initialalize my variables */
    tries = 20;
    result = 0;

    if (set.verbose == POLLER_VERBOSITY_DEBUG) {
        snprintf(logmessage, LOGSIZE-1, "MYSQL: Connecting to MySQL database '%s' on '%s'...\n", database, set.dbhost);
        cacti_log(logmessage);
    }

    thread_mutex_lock(LOCK_MYSQL);
    db = mysql_init(mysql);
    if (db == NULL) {
        cacti_log("ERROR: MySQL unable to allocate memory and therefore can not connect\n");
        exit_cactid();
    }

    while (tries > 0) {
        tries--;
        if (!mysql_real_connect(mysql, hostname, set.dbuser, set.dbpass, database, set.dbport, socket, 0)) {
            if (set.verbose == POLLER_VERBOSITY_DEBUG) {
                snprintf(logmessage, LOGSIZE-1, "MYSQL: Connection Failed: %s\n", mysql_error(mysql));
                cacti_log(logmessage);
            }
            result = 1;
        } else {
            tries = 0;
            result = 0;
            if (set.verbose == POLLER_VERBOSITY_DEBUG) {
                snprintf(logmessage, LOGSIZE-1, "MYSQL: Connected to MySQL database '%s' on '%s'...\n", database, set.dbhost);
                cacti_log(logmessage);
            }
        }
        usleep(2000);
    }

    free(hostname);

    if (result == 1) {
        snprintf(logmessage, LOGSIZE-1, "MYSQL: Connection Failed: %s\n", mysql_error(mysql));
        cacti_log(logmessage);
        thread_mutex_unlock(LOCK_MYSQL);
        exit_cactid();
    } else {
        thread_mutex_unlock(LOCK_MYSQL);
        return 0;
    }
}