void connectSQL(){ conn = mysql_init(NULL); mysql_options(conn, MYSQL_SET_CHARSET_NAME, "utf8"); mysql_options(conn, MYSQL_INIT_COMMAND, "SET NAMES utf8"); if (!mysql_real_connect(conn, "127.0.0.1", "root", "", "english", 0, 0, 0)) { finish_with_error(conn); }else{ printf("[Server]: Succsess connect to Database!\n"); } querySQL("UPDATE account SET online = 0"); }
int coba(char* server, char* user ,char* password ,char* dbname,char* nama, int umur, char* nm_table) { MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "mysql_init() failed\n"); exit(1); } if (mysql_real_connect(con, server, user, password, dbname, 0, NULL, 0) == NULL) { finish_with_error(con); } char select[100]; sprintf(select,"select*from %s ",nm_table); //if (mysql_query(con, "SELECT * FROM %s",nm_table)) ; //{ // finish_with_error(con); //} if (mysql_query(con,select)) { finish_with_error(con); } char insert[100]; sprintf(insert,"insert into %s values('','%s',%d)",nm_table,nama,umur); if (mysql_query(con,insert)) { finish_with_error(con); } return coba (server, user ,password ,dbname,nama,umur, nm_table); }
int main(int argc, char **argv) { printf("MySQL client version: %s\n", mysql_get_client_info()); MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "Error on Connection: %s\n", mysql_error(con)); exit (1); } if (mysql_real_connect(con, "127.0.0.1", "root", "Passwd", "ranking_old", 3306, NULL, 0) == NULL) { fprintf(stderr, "Erron on Establish conn: %s\n", mysql_error(con)); mysql_close(con); exit (1); } if (mysql_query(con, "SELECT * FROM player_login")) finish_with_error(con); MYSQL_RES *result = mysql_store_result(con); if (result == NULL) finish_with_error(con); int num_fields = mysql_num_fields(result); MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { for (int i = 0; i < num_fields; i++) { printf("%s ", row[i] ? row[i] : "NULL"); } printf("\n"); } mysql_free_result(result); mysql_close(con); return 0; }
int main(int argc, char *argv[]) { MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "mysql_init() has failed!\n"); exit(1); } if (mysql_real_connect(con, "localhost", "sqlusr", "q1w2e3!", "tst1", 0, NULL, 0) == NULL) { finish_with_error(con); } if (mysql_query(con, "SELECT * FROM tblPerson")) { finish_with_error(con); } MYSQL_RES *result = mysql_store_result(con); if (result == NULL) { finish_with_error(con); } int num_fields = mysql_num_fields(result); MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { for (int i = 0; i < num_fields; i++) { printf("%s ", row[i] ? row[i] : "NULL"); } printf("\n"); } mysql_free_result(result); mysql_close(con); exit(0); }
int querySQL(char *str){ //printf("\nquery - %s\n ",str); if (mysql_query(conn, str)) { finish_with_error(conn); } result = mysql_store_result(conn); if (result) { num_rows = mysql_num_rows(result); return 1; }else{ if (mysql_field_count(conn) == 0) { num_rows = mysql_affected_rows(conn); return 1; }else{ finish_with_error(conn); return 0; } } }
int db_read_fetch() { _fetch = mysql_stmt_fetch(_mysql_stmt); switch(_fetch) { case 1: mysql_stmt_close(_mysql_stmt); finish_with_error(LOG_ERR, "Failed to fetch prepared MySQL statement result"); return -1; break; case MYSQL_NO_DATA: return 0; default: return 1; } }
void Mysql_results(void *self) { Mysql *m = self; // Reading from query if (m->result == NULL) finish_with_error(m); int num_fields = mysql_num_fields(m->result); MYSQL_ROW row; while ((row = mysql_fetch_row(m->result))) { for (int i = 0; i < num_fields; i++) { printf("%s ", row[i] ? row[i] : "NULL"); } printf("\n"); } }
int check_balance(int *argc, char **argv) { MYSQL_RES *result; unsigned long long num_rows; long long amount; if (mysql_query(con, "select amount from balance")) finish_with_error(con); if ((result = mysql_store_result(con)) == 0) finish_with_error(con); if ((num_rows = mysql_num_rows(result)) == 0) { if (strchr("ibefm", (*argv[1])) != NULL) { amount = atoi(argv[2]); snprintf(query, BUFSIZE, "insert into balance values (CURDATE(), %lld)", amount); mysql_insert(query); } return 0; } return 1; }
void initMySQLdb(){ con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } if (mysql_real_connect(con, "localhost", "root", "PASSWORD", "softsys", 0, NULL, 0) == NULL) { finish_with_error(con); } }
int db_read_open(const char *query, MYSQL_BIND *params, MYSQL_BIND *results) { /* Make sure we have a valid database connection. */ if (_mysql_con == NULL) { _mysql_con = mysql_init(NULL); if (_mysql_con == NULL) { finish_with_error(LOG_ERR, "Failed to initialize MySQL connection structure"); return -1; } if (mysql_real_connect(_mysql_con, options.db.host, options.db.nss.username, options.db.nss.password, options.db.database, 0, NULL, 0) == NULL) { finish_with_error(LOG_ERR, "Failed to connect to MySQL"); return -1; } } _mysql_stmt = mysql_stmt_init(_mysql_con); if (_mysql_stmt == NULL) { finish_with_error(LOG_ERR, "Failed to allocate MySQL prepared statement structure"); return -1; } if (mysql_stmt_prepare(_mysql_stmt, query, strlen(query) + 1) != 0) { mysql_stmt_close(_mysql_stmt); finish_with_error(LOG_ERR, "Failed to prepare MySQL statement"); return -1; } if (mysql_stmt_bind_param(_mysql_stmt, params) != 0) { mysql_stmt_close(_mysql_stmt); finish_with_error(LOG_ERR, "Failed to bind parameters to prepared MySQL statement"); return -1; } if (mysql_stmt_bind_result(_mysql_stmt, results) != 0) { mysql_stmt_close(_mysql_stmt); finish_with_error(LOG_ERR, "Failed to bind results for prepared MySQL statement"); return -1; } if (mysql_stmt_execute(_mysql_stmt) != 0) { mysql_stmt_close(_mysql_stmt); finish_with_error(LOG_ERR, "Failed to execute prepared MySQL statement"); return -1; } return 0; }
static int create_db_comm(){ con = mysql_init(NULL); if (con == NULL) { LOG_MESSAGE("%s\n", mysql_error(con)); return -1; } if (mysql_real_connect(con, "localhost", NULL, NULL, "bancotr", 0, NULL, 0) == NULL) { finish_with_error(con); return -1; } LOG_MESSAGE("Created DB connection\n"); return 0; }
int db_read_close() { int rows; rows = mysql_stmt_affected_rows(_mysql_stmt); mysql_stmt_close(_mysql_stmt); if (rows < 0) { /* Only LOG_WARNING as we have successfully fetched SOMETHING. */ finish_with_error(LOG_WARNING, "Problem fetching number of rows from prepared MySQL statement"); if (_fetch == MYSQL_NO_DATA) { return 0; } else { return 1; } } return rows; }
int edit_product_warranty (void) { char query[2048]; system("clear"); printf("\n"); printf("Quanto tempo de garantia voce deseja atribuir a '%s'?\n", current_goods.name); scanf("%f", &inputed_info.warranty); getchar(); sprintf(query, "UPDATE Produtos SET Tempo_de_garantia = %f WHERE ID = %d", inputed_info.warranty, inputed_info.ID); if (mysql_query(con, query)) { finish_with_error(con); } else { get_product_info(); if (current_goods.warranty >= 2) { printf("\n"); printf("A garantia foi alterada com sucesso para '%f' anos!\n", current_goods.warranty); printf("\n"); printf("Aperte enter para continuar:\n"); } else { printf("\n"); printf("A garantia foi alterada com sucesso para '%f' ano!\n", current_goods.warranty); printf("\n"); printf("Aperte enter para continuar:\n"); } getchar(); return-1 } return 0; }
void log_out() { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row, r; char *server = "localhost"; char *user = "******"; char *password = "******"; char *database = "socket"; char query[1024]; conn = mysql_init(NULL); if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(0); } snprintf(query, sizeof query, "UPDATE clients SET active = 0 WHERE username = '******'", curr_user); if(mysql_query(conn,query)){ finish_with_error(conn); } mysql_close(conn); }
int pesquisar_produto (void) { // String que acionará o "mysql_query": char query[2048]; // Escanear informações do usuário: int opcao; printf ("Deseja pesquisar o lote por Id do produto ou por Data de entrada?\n"); printf ("Escolha uma opcao(1-Id, 2-Data): "); scanf ("%d", &opcao); getchar(); if (opcao == 1) { printf ("Informe o Id do produto a ser pesquisado: "); scanf ("%d", &id); getchar(); sprintf(query, "SELECT Id, Id_do_produto, Nome_do_produto, Fabricante, Tempo_de_garantia, Referencia, Data_de_entrada, Quantidade, Valor_de_compra FROM Lotes HAVING Id_do_produto=%d && Estado_do_item=1", id); // Consultar o BD: if (mysql_query(con, query)) { finish_with_error(con); } // Guardar o resultado: MYSQL_RES *resultado = mysql_store_result(con); MYSQL_ROW *linha; if (resultado == NULL) { finish_with_error(con); } linha = mysql_fetch_row(resultado); // Exibir linha com o Id do produto pesquisado: printf("%s\n", linha); mysql_free_result(resultado); } else if (opcao == 2) { printf ("Informe a Data de entrada do lote a ser pesquisado no formato DD/MM/AAAA: "); scanf ("%d/%d/%d", &data.dia, &data.mes, &data.ano); getchar(); sprintf(query, "SELECT Id, Id_do_produto, Nome_do_produto, Fabricante, Tempo_de_garantia, Referencia, Data_de_entrada, Quantidade, Valor_de_compra FROM Lotes HAVING Data_de_entrada=%d-%d-%d && Estado_do_item=1", data.dia, data.mes, data.ano); // Consultar o BD: if (mysql_query(con, query)) { finish_with_error(con); } // Guardar o resultado: MYSQL_RES *resultado = mysql_store_result(con); MYSQL_ROW *linha; if (resultado == NULL) { finish_with_error(con); } linha = mysql_fetch_row(resultado); // Exibir linha com o Nome pesquisado: printf("%s\n", linha); mysql_free_result(resultado); } }
int calculate_balance(int *argc, char **argv) { MYSQL_RES *result; MYSQL_ROW row; my_ulonglong num_rows; unsigned long long balance_amount = 0, amount = 0; char * date; date = mysql_date(); snprintf(query, BUFSIZE, "select amount from balance where day='%s'", date); if (mysql_query(con, query)) finish_with_error(con); if ((result = mysql_store_result(con)) == 0) finish_with_error(con); num_rows = mysql_num_rows(result); mysql_data_seek(result, num_rows - 1); if ((row = mysql_fetch_row(result)) == NULL) { fprintf(stderr, "error from fetch\n"); finish_with_error(con); } balance_amount = atoll(row[0]); mysql_free_result(result); switch(*argv[1]) { case 'i': amount = atoll(argv[2]); snprintf(query, BUFSIZE, "insert into balance values (CURDATE(), %lld)", balance_amount + amount); mysql_insert(query); break; case 'b': amount = atoll(argv[2]); snprintf(query, BUFSIZE, "insert into balance values (CURDATE(), %lld)", balance_amount - amount); mysql_insert(query); break; case 'e': amount = atoll(argv[2]); snprintf(query, BUFSIZE, "insert into balance values (CURDATE(), %lld)", balance_amount - amount); mysql_insert(query); break; case 'f': amount = atoll(argv[2]); snprintf(query, BUFSIZE, "insert into balance values (CURDATE(), %lld)", balance_amount - amount); mysql_insert(query); break; case 'm': amount = atoll(argv[2]); snprintf(query, BUFSIZE, "insert into balance values (CURDATE(), %lld)", balance_amount - amount); mysql_insert(query); break; default: break; } }
//<--- main ---> int main(int argc, char **argv) { MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } // Verbindungsaufbau zur MySQL Datenbank if (!mysql_real_connect(con, "127.0.0.1", /*Server hostname or IP-Adresse*/ "datauser", /*mysql user*/ "datauser", /*password*/ "databank", /*default Database to use, NULL for none*/ 3306, /*port number, 0 for default*/ "NULL", /*socket file or named pipe name*/ 0)) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); } for(;;) { int auswahl, done = 0; int r = rand() % 20; auswahl = menu(); switch (auswahl) { // In Datenbank schreiben case 1: for(;;) { int wahl; if(done != 0) { printf("Eingabe ende\n"); break; } printf("3:Fehler 2:Warnung 1:Gut 0:Ende\n"); printf("Iher Wahl: "); scanf("%d",&wahl); switch(wahl) { case 1: printf("Good\n"); if (mysql_query(con, "INSERT INTO `tab` (`date`, `red`, `yellow`, `green`, `status`) VALUES (CURRENT_TIMESTAMP, '0', '0', '1', 'PI -> Good')")) { finish_with_error(con); } else { if(mysql_query(con, "INSERT INTO `tab1` (`frequenz`) VALUES ('%d' )",r)) { finish_with_error(con); } } break; case 2: printf("Warning\n"); if (mysql_query(con, "INSERT INTO `tab` (`date`, `red`, `yellow`, `green`, `status`) VALUES (CURRENT_TIMESTAMP, '0', '1', '0', 'PI -> Warning')")) { finish_with_error(con); } else { if(mysql_query(con, "INSERT INTO `tab1` (`frequenz`) VALUES ('%d' )",r)) { finish_with_error(con); } } break; case 3: printf("Error\n"); if (mysql_query(con, "INSERT INTO `tab` (`date`, `red`, `yellow`, `green`, `status`) VALUES (CURRENT_TIMESTAMP, '1', '0', '0', 'PI -> Error')")) { finish_with_error(con); } else { if(mysql_query(con, "INSERT INTO `tab1` (`frequenz`) VALUES ('%d' )",r)) { finish_with_error(con); } } break; case 0: done = 1; break; } } break; // Datenbank auslesen case 2: if (mysql_query(con, "SELECT * FROM tab")) { finish_with_error(con); } MYSQL_RES *result = mysql_store_result(con); if (result == NULL) { finish_with_error(con); } int num_fields = mysql_num_fields(result); MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { for(int i = 0; i < num_fields; i++) { printf("%s ", row[i] ? row[i] : "NULL"); } printf("\n"); } mysql_free_result(result); break; case 0: printf("Programm wird beendet\n"); // Verbindung zur Datenbank schliessen mysql_close(con); exit(0); break; default: printf("Ihre Auswahl ist ungueltig\n"); break; } } }
static int check_packet(){ char * msg_rcv; unsigned int signature; unsigned char state; struct tm tm; time_t t; t_msgsup *msg; t_msgsupsq *msg_sq; msg_rcv = WaitT(hist_socket_receive, 2000); if(msg_rcv != NULL) { t = time(NULL); tm = *localtime(&t);//get local time //first of all, if month has changed, or first time check/create a new table if(tm.tm_mon!=currmon){ MYSQL_RES * result; int found=0; memset(query,0,QUERY_SIZE); snprintf(query, QUERY_SIZE, "show tables like 'h%d_%02d'",tm.tm_year+1900, tm.tm_mon+1); if (mysql_query(con,query)) { finish_with_error(con); return -1; } result=mysql_store_result(con); if(result){ if(mysql_num_rows(result)){ found=1; } } mysql_free_result(result); if(!found){ memset(query,0,QUERY_SIZE); snprintf(query, QUERY_SIZE, "create table `h%d_%02d` like `h0000_00`",tm.tm_year+1900, tm.tm_mon+1); LOG_MESSAGE("%s\n",query); if (mysql_query(con,query)) { finish_with_error(con); return -1; } } currmon=tm.tm_mon; } //copy type of message memcpy(&signature, msg_rcv, sizeof(unsigned int)); //digital report if(signature==IHM_SINGLE_POINT_SIGN){ msg=(t_msgsup *)msg_rcv; if(msg->tipo==30){ digital_w_time7_seq *info; info=(digital_w_time7_seq *)msg->info; events_msgs++; state=(info->iq&0xF7); //first insert into history if it has already been writen once (events are never writen) if(msg->endereco<DATABASE_SIZE && data[msg->endereco].flags != FLAGS_INIT){ memset(query,0,QUERY_SIZE); snprintf(query, QUERY_SIZE, "INSERT IGNORE INTO h%d_%02d VALUES ('%d','%02d-%02d-%02d','%02d:%02d:%02d','%d','%d')", tm.tm_year+1900, tm.tm_mon+1, msg->endereco, tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,(state&0x01), (state&0xFD)); // LOG_MESSAGE("%s\n", query); if (mysql_query(con,query)) { finish_with_error(con); return -1; } } //always update val_tr memset(query,0,QUERY_SIZE); snprintf(query, QUERY_SIZE, "REPLACE INTO val_tr VALUES ('%d','%02d-%02d-%02d','%02d:%02d:%02d','%d','%d')", msg->endereco, tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,(state&0x01),state); if (mysql_query(con,query)) { finish_with_error(con); return -1; } //than insert into sde memset(query,0,QUERY_SIZE); snprintf(query, QUERY_SIZE, "INSERT IGNORE INTO sde VALUES('%d','0','20%02d-%02d-%02d','%02d:%02d:%02d', '%d', '%d', '0', NULL)", msg->endereco, info->ano, info->mes, info->dia, info->hora, info->min, info->ms/1000, info->ms%1000, state); //LOG_MESSAGE("%s\n", query); if (mysql_query(con,query)) { finish_with_error(con); return -1; } } else if(msg->tipo==1){ events_msgs++; should_be_type_30++; } else{ error_msgs++; } } //if it is a list of data else if(signature==IHM_POINT_LIST_SIGN){ unsigned int i,nponto,total,insertone=0; msg_sq=(t_msgsupsq *)msg_rcv; nponto=0; //new day or starting process, reset flags in order to write again all data (once a day) if(tm.tm_mday!=currday){ for(i=0;i<DATABASE_SIZE;i++) data[i].flags=FLAGS_INIT; currday=tm.tm_mday; } //if digital if(msg_sq->tipo==1){ digital_seq * info; //first update val_tr table memset(longquery,0,LONG_QUERY_SIZE); snprintf(longquery, QUERY_SIZE, "REPLACE INTO val_tr (NPONTO, DATA, HORA, VALOR, FLAGS) VALUES "); for (i=0;i<msg_sq->numpoints;i++){ memcpy(&nponto, &msg_sq->info[i*(sizeof(digital_seq)+sizeof(int))], sizeof(int)); info=(digital_seq *)&msg_sq->info[i*(sizeof(digital_seq)+sizeof(int))+sizeof(int)]; state=(info->iq&0xF7); snprintf(longquery+strlen(longquery), QUERY_SIZE, "('%d','%02d-%02d-%02d','%02d:%02d:%02d','%d','%d'),", nponto, tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min,tm.tm_sec, (state&0x01), (state&0xFD)); } longquery[strlen(longquery)-1]=';'; if (mysql_query(con,longquery)) { finish_with_error(con); return -1; } //than update history table memset(longquery,0,LONG_QUERY_SIZE); snprintf(longquery, QUERY_SIZE, "INSERT IGNORE INTO h%d_%02d (NPONTO, DATA, HORA, VALOR, FLAGS) VALUES ",tm.tm_year+1900, tm.tm_mon+1); for (i=0;i<msg_sq->numpoints;i++){ memcpy(&nponto, &msg_sq->info[i*(sizeof(digital_seq)+sizeof(int))], sizeof(int)); info=(digital_seq *)&msg_sq->info[i*(sizeof(digital_seq)+sizeof(int))+sizeof(int)]; if(data[nponto].flags!=info->iq){ state=(info->iq&0xF7); snprintf(longquery+strlen(longquery), QUERY_SIZE, "('%d','%02d-%02d-%02d','%02d:%02d:%02d','%d','%d'),", nponto, tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min,tm.tm_sec, (state&0x01), (state&0xFD)); insertone=1; data[nponto].flags=info->iq; } } if(insertone){ longquery[strlen(longquery)-1]=';'; if (mysql_query(con,longquery)) { finish_with_error(con); return -1; } } digital_msgs++; //if analog data }else if(msg_sq->tipo==13){ flutuante_seq *info; //first update val_tr memset(longquery,0,LONG_QUERY_SIZE); snprintf(longquery, QUERY_SIZE, "REPLACE INTO val_tr (NPONTO, DATA, HORA, VALOR, FLAGS) VALUES "); for (i=0;i<msg_sq->numpoints;i++){ memcpy(&nponto, &msg_sq->info[i*(sizeof(flutuante_seq)+sizeof(int))], sizeof(int)); info=(flutuante_seq *)&msg_sq->info[i*(sizeof(flutuante_seq)+sizeof(int))+sizeof(int)]; snprintf(longquery+strlen(longquery), QUERY_SIZE, "('%d','%02d-%02d-%02d','%02d:%02d:%02d','%.2f','%d'),", nponto, tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,info->fr,info->qds); } longquery[strlen(longquery)-1]=';'; if (mysql_query(con,longquery)) { finish_with_error(con); return -1; } //than update history memset(longquery,0,LONG_QUERY_SIZE); snprintf(longquery, QUERY_SIZE, "INSERT IGNORE INTO h%d_%02d (NPONTO, DATA, HORA, VALOR, FLAGS) VALUES ",tm.tm_year+1900, tm.tm_mon+1); for (i=0;i<msg_sq->numpoints;i++){ memcpy(&nponto, &msg_sq->info[i*(sizeof(flutuante_seq)+sizeof(int))], sizeof(int)); info=(flutuante_seq *)&msg_sq->info[i*(sizeof(flutuante_seq)+sizeof(int))+sizeof(int)]; //write analog if flag has changed otherwise write if values have changed more than 0.5% or 0.5 within a minute //every five minutes write if value have changed more than 0.2% or at least 0.2 if(data[nponto].flags!=info->qds || ((t-data[nponto].lastchange)>=60 && ((fabs(info->fr)>100 && (fabs(info->fr-data[nponto].value)/fabs(info->fr) > 0.005)) || (fabs(info->fr)<=100 && fabs(info->fr-data[nponto].value)>=0.5) )) || ((t-data[nponto].lastchange)>=300 && ((fabs(info->fr)>100 && (fabs(info->fr-data[nponto].value)/fabs(info->fr) > 0.002)) || (fabs(info->fr)<=100 && fabs(info->fr-data[nponto].value)>=0.2) ))){ snprintf(longquery+strlen(longquery), QUERY_SIZE, "('%d','%02d-%02d-%02d','%02d:%02d:%02d','%.2f','%d'),", nponto, tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, info->fr, info->qds); insertone=1; data[nponto].flags =info->qds; data[nponto].value =info->fr; data[nponto].lastchange = t; } } if(insertone){ longquery[strlen(longquery)-1]=';'; if (mysql_query(con,longquery)) { finish_with_error(con); return -1; } } analog_msgs++; }else{ error_msgs++; } } else{ error_msgs++; } free(msg_rcv); } return 0; }
void main() { MYSQL *con = mysql_init(NULL); char statement[512]; char myHash[] = "d5852d4dac50bbc61d6cb794f99bdf0f12cc5220dd2d043bbde18ebedd3ca95f"; unsigned char dynamicHash[32]; char *plaintext = NULL; char *currentHash = NULL; char hash64[65]; char temp[3]; char r[6]; int num_fields,i,k; MYSQL_ROW row; MYSQL_RES *result; int successFlag = 0; char *pos = myHash; size_t count = 0; /* Convert back from hex string to byte array */ for(count = 0; count < sizeof(dynamicHash)/sizeof(dynamicHash[0]); count++) { sscanf(pos, "%2hhx", &dynamicHash[count]); pos += 2 * sizeof(char); } plaintext = malloc(7); currentHash = malloc(33); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } if (mysql_real_connect(con, "localhost", "root", "botiotia", "test", 0, NULL, 0) == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); } for(k=0;k<32;k++) { snprintf(temp,3,"%02x",dynamicHash[k]); hash64[2*k] = temp[0]; hash64[2*k+1] = temp[1]; } hash64[64] = '\0'; for(i = chainLength-1; i >= 0; i--) //iterate chain backwards { snprintf(statement, 512, "SELECT * FROM Rainbow where Hash = '%s'",hash64); if (mysql_query(con, statement) ) { finish_with_error(con); } result = mysql_store_result(con); if (result == NULL) { finish_with_error(con); } row = mysql_fetch_row(result); //we know that if any result is produced, it is going to be distinct from creation and thus no iteration with num_fields is required.(maximum 1 row per query) if(row != NULL) //if found a result { if(plaintext == NULL) plaintext = malloc(7); if(currentHash == NULL) currentHash = malloc(33); //copy to the corresponding buffers strncpy(plaintext,row[0],7); //row[0] to plaintext char *pos1 = row[1]; //now convert this row[1] to byte array and copy it to hash size_t count = 0; /* Convert back from hex string to byte array, because the R and Blake take the byte array as a parameter */ for(count = 0; count < sizeof(currentHash)/sizeof(currentHash[0]); count++) { sscanf(pos1, "%2hhx", ¤tHash[count]); pos1 += 2 * sizeof(char); } } else //else both NULL { plaintext = NULL; currentHash = NULL; } if(currentHash != NULL) //hash is found. { blake256_hash(dynamicHash,plaintext,6); //start from the beginning of the chain for(k = 0; k <= i; k++) //iterate through all the R functions until the hash { Reduce(dynamicHash,k,r); //k is the position //printf("%s\n",currentHash); if(i == k) { printf("Found at %d. The password is: %s \n",k,r); successFlag = 1; } blake256_hash(dynamicHash,r,6); } i = -1; //to stop the iteration } Reduce(dynamicHash,i,r); blake256_hash(dynamicHash,r,6); for(k=0;k<32;k++) { snprintf(temp,3,"%02x",dynamicHash[k]); hash64[2*k] = temp[0]; hash64[2*k+1] = temp[1]; } hash64[64] = '\0'; if((i % 10000) == 0) printf("%d steps from %d\n",chainLength-i,chainLength); } if(!successFlag) printf("Password not Found :-(\n"); mysql_free_result(result); mysql_close(con); exit(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); }
int search_file(char *buffer, char *final_list) { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row, r; char *server = "localhost"; char *user = "******"; char *password = "******"; char *database = "socket"; char query[1024], file_name[1024]; char temp[1024]; char list[100][100]; conn = mysql_init(NULL); int ret; /* Connect to database */ if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(0); } /* send SQL query */ /*if (mysql_query(conn, "show tables")) { fprintf(stderr, "%s\n", mysql_error(conn)); return 0; }*/ snprintf(query, sizeof query, "SELECT username, ip, port FROM clients WHERE active = 1"); if (mysql_query(conn, query)) { fprintf(stderr, "%s\n", mysql_error(conn)); return 0; } res = mysql_use_result(conn); char list2[100][100]; ret = query_check(buffer, file_name, 2); int num=0,i,len=0; while ((row = mysql_fetch_row(res)) != NULL) { strcpy(list[num], row[0]); snprintf(list2[num], sizeof list2[num], "%s %s %s",row[0],row[1],row[2]); num++; } final_list[0] = '\0'; char cat[1024]; for(i=0;i<num;i++){ if(strcmp(list[i], "clients")!=0 && strcmp(list[i], curr_user)!=0) { mysql_free_result(res); snprintf(query, sizeof query, "SELECT * FROM %s WHERE filename = '%s'",list[i], file_name); if (mysql_query(conn,query)) { finish_with_error(conn); return 0; } res = mysql_use_result(conn); if ((r = mysql_fetch_row(res)) != NULL) { snprintf(cat, sizeof cat, "%s %s %s", list2[i], r[0], r[1]); strcat(final_list, cat); len+=strlen(cat); final_list[len++]='\n'; final_list[len]='\0'; } } } /* close connection */ mysql_free_result(res); mysql_close(conn); return 1; }
int sqlite3_open(const char* filename, /* Database filename (UTF-8) */ sqlite3** ppDb /* OUT: SQLite db handle */ ) { MYSQL* con = mysql_init(NULL); const char* host = NULL; const char* user = NULL; const char* pass = NULL; const char* db = NULL; if (con == NULL) { fprintf(stderr, "sqlite3_open() -> mysql_init() failed\n"); return 0; } FILE* fh = fopen(filename, "r"); if (fh) { json_t* root = json_loadf(fh, JSON_DECODE_ANY, NULL); if (root) { // We got JSON host = json_string_value(json_object_get(root, "host")); user = json_string_value(json_object_get(root, "user")); pass = json_string_value(json_object_get(root, "pass")); db = json_string_value(json_object_get(root, "db")); if (mysql_real_connect(con, host, user, pass, NULL, 0, NULL, 0) == NULL) { finish_with_error(con); *ppDb = NULL; } else { if (mysql_select_db(con, db) != 0) { char* sql; int len = asprintf(&sql, "CREATE DATABASE %s", db); mysql_real_query(con, sql, len); free(sql); } if (mysql_select_db(con, db) != 0) { finish_with_error(con); *ppDb = NULL; } else { *ppDb = (sqlite3*)con; } } // Cleanup json_decref(root); } fclose(fh); } return 0; };
void Server_Create_FlatAccount(int nSock) { char szQuery[200]; char szBuf[200]; char szUserName[10]; char szPassword[15]; char szFlatOwnerName[10]; char szResidingDate[15]; char szDetails[nSize]; char *pszRecv=NULL; int nContactNo=bZero; int nMembers=bZero; int nResult=bZero; int nFlatNo,i,numrow; int num_fields=bZero; MYSQL_RES *result=NULL; MYSQL *con = mysql_init(NULL); if(con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); //exit(1); } printf("In func login %u\n",nSock); pszRecv=Receive_Message(nSock); nFlatNo=atoi(pszRecv); sprintf(szQuery,"select * from Login_Credentials where FlatNo=%d",nFlatNo); // printf("*******%s****\n",pszRecv); if(mysql_real_connect(con, "localhost", "root", "labh","rll", 0, NULL, 0) == NULL) { finish_with_error(con); return; } if (mysql_query(con, szQuery)) { finish_with_error(con); } result = mysql_store_result(con); if (result == NULL) { finish_with_error(con); } //num_fields = mysql_num_fields(result); numrow = mysql_num_rows(result); if(numrow==0) { Send_Message(nSock,"1"); pszRecv=Receive_Message(nSock); sscanf(pszRecv,"%s %d %s %d ",szFlatOwnerName,&nContactNo,szResidingDate,&nMembers); sprintf(szQuery,"insert into Flat_Account values(%d,'%s','%d','%s',%d)",nFlatNo,szFlatOwnerName,nContactNo,szResidingDate,nMembers); printf("%s\n",szQuery); if (mysql_query(con, szQuery)) { finish_with_error(con); } sprintf(szUserName,"%.2s%d",szFlatOwnerName,nContactNo%1000); srand(time(NULL)); sprintf(szPassword,"%d",rand()%10000); sprintf(szBuf,"%s %s\n",szUserName,szPassword); sprintf(szQuery,"insert into Login_Credentials(FlatNo,FlatOwner,LoginName,LoginPwd) values(%d,'%s','%s','%s')",nFlatNo,szFlatOwnerName,szUserName,szPassword); printf("%s\n",szQuery); printf("%s\n",szBuf); if (mysql_query(con, szQuery)) { finish_with_error(con); } sprintf(szQuery,"insert into Registered_Appliances (FlatNo) values (%d)",nFlatNo); if (mysql_query(con, szQuery)) { finish_with_error(con); } sprintf(szQuery,"insert into Appliance_Status (FlatNo) values (%d)",nFlatNo); if (mysql_query(con, szQuery)) { finish_with_error(con); } Send_Message(nSock,szBuf); } else { Send_Message(nSock,"0"); Server_Create_FlatAccount(nSock); } printf("in create_flatacc fun %u\n",nSock); mysql_close(con); }
int main(int argc, char **argv) { MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } if (mysql_real_connect(con, "localhost", "root", "51Perkins", "boxerdb", 0, NULL, 0) == NULL) { finish_with_error(con); } if (mysql_query(con, "DROP TABLE IF EXISTS Boxers")) { finish_with_error(con); } if (mysql_query(con, "CREATE TABLE Boxers(Id INT PRIMARY KEY AUTO_INCREMENT, FirstName varchar(255) NOT NULL, LastName varchar(255) NOT NULL, Sex varchar(2) NOT NULL, Age INT NOT NULL, Weight varchar(50) NOT NULL, Bouts INT NOT NULL)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Hayley', 'Hansson', 'F', 20, 'Super Lightweight', 2)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Alison', 'Berkowitz', 'F', 19, 'Lightweight', 3)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Ben', 'Kahle', 'M', 20, 'Cruiserweight', 8)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Abe', 'Levitan', 'M', 20, 'Welterweight', 7)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Cory', 'Dolphin', 'M', 21, 'Heavyweight', 8)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Dan', 'Kearney', 'M', 21, 'Super Middleweight', 6)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Evan', 'Dorsky', 'M', 20, 'Super Bantamweight', 7)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Forest', 'Bourke', 'M', 19, 'Lightweight', 2)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Erin', 'Pierce', 'F', 19, 'Flyweight', 4)")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Boxers(FirstName, LastName, Sex, Age, Weight, Bouts) VALUES('Adam', 'Coppola', 'M', 20, 'Welterweight', 2)")) { finish_with_error(con); } mysql_close(con); exit(0); }
void chat(int sd2){ int n,i; char socket_name[BUFF_LENGTH]; char *var; char message[BUFF_LENGTH]; char in[BUFF_LENGTH]; char out[BUFF_LENGTH]; while(1){ for(i = 0; i < BUFF_LENGTH; i++){ in[i] = 0;out[i] = 0;} n = read(sd2, in, sizeof(in)); if(!strcmp(in, "@EXIT@")){ sprintf(out, "Client"); for(i = 0; i < contacts; i++){ if(onlinecontacts[i].contactsd != sd2) sprintf(out, "%s@%s",out, onlinecontacts[i].contactname); } for(i = 0; i < contacts; i++){ if(onlinecontacts[i].contactsd != sd2) write(onlinecontacts[i].contactsd, out, sizeof(out)); } return ; }else if(!((in != NULL) && (in[0] == '\0'))){ if(!strncmp(in, "<", 1)){ var = strstr(in, "<"); i = 0; var++; while(*var != '>'){socket_name[i] = *var;var++;i++;} socket_name[i] = '\0'; var = strstr(in, ">"); i = 0; var++; while(*var != '\0'){message[i] = *var;var++;i++;} message[i] = '\0'; //printf("\nMessage [%s] is for [%s]\n\n", message, socket_name); for(i = 0; onlinecontacts[i].contactsd != sd2; i++); sprintf(out, "MSG@%s:%s", onlinecontacts[i].contactname, message); /**/ char buf[200]; memset(&buf,0,sizeof(buf)); if ( con ){ sprintf(buf, "INSERT INTO message(src,dst,msg) VALUES('%s','%s','%s')",onlinecontacts[i].contactname,socket_name,message); if (mysql_query(con, buf)) { finish_with_error(con);} } i = 0; while(strcmp(onlinecontacts[i].contactname, socket_name)){ i++; } write(onlinecontacts[i].contactsd, out, sizeof(out)); }else if(!strncmp(in, ";", 1)){ var = strstr(in, ";"); i = 0; var++; while(*var != ':'){socket_name[i] = *var;var++;i++;} socket_name[i] = '\0'; for(i = 0; onlinecontacts[i].contactsd != sd2; i++); if ( con ){ char buf[200]; sprintf(buf, "SELECT DISTINCT * FROM message where (src='%s' and dst='%s') or (src='%s' and dst='%s') ORDER BY ordate",onlinecontacts[i].contactname, socket_name, socket_name,onlinecontacts[i].contactname); if (mysql_query(con, buf)) { finish_with_error(con); }else{ printf("sending historique\n"); MYSQL_RES *result = mysql_store_result(con); if (result == NULL){ finish_with_error(con);} MYSQL_ROW row; char Bbuf[BUFF_HST]; sprintf(Bbuf,"HST@"); while ((row = mysql_fetch_row(result))){ sprintf(Bbuf,"%s<%s>%s>%s",Bbuf,row[0],row[1],row[3]); } for(i = 0; onlinecontacts[i].contactsd != sd2; i++); write(onlinecontacts[i].contactsd, Bbuf, sizeof(Bbuf)); printf("Buf :%s\n",Bbuf ); mysql_free_result(result); } } }else{ for(i = 0; onlinecontacts[i].contactsd != sd2; i++); sprintf(message, "BRD@%s : %s ", onlinecontacts[i].contactname, in); strcpy(out, message); for(i = 0; i < contacts; i++){ if(onlinecontacts[i].contactsd != sd2) write(onlinecontacts[i].contactsd, out, sizeof(out)); } } } } }
int main(int argc, char **argv) { /* //Display version printf("My sql client version: %s\n", mysql_get_client_info()); */ //Initial value MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } /* //Connnect database_1 if (mysql_real_connect(con, "localhost", "root", "123", NULL, 0, NULL, 0) == NULL) finish_with_error(con); //Create database if (mysql_query(con, "CREATE DATABASE testdb")) finish_with_error(con); */ //Connect database_2 if (mysql_real_connect(con, "localhost", "root", "123", "testdb", 0, NULL, 0) == NULL) finish_with_error(con); //Drop table if (mysql_query(con, "DROP TABLE IF EXISTS Cars")) finish_with_error(con); //Create table if (mysql_query(con, "CREATE TABLE Cars(Id INT PRIMARY KEY AUTO_INCREMENT, Name TEXT, Price INT)")) finish_with_error(con); //P.S. AUTO_INCREMENT if for mysql_insert_id(); //Insert data if (mysql_query(con, "INSERT INTO Cars VALUES(1, 'Audi', 52642)")) finish_with_error(con); if (mysql_query(con, "INSERT INTO Cars VALUES(2,'Mercedes',57127)")) finish_with_error(con); if (mysql_query(con, "INSERT INTO Cars VALUES(3,'Skoda',9000)")) finish_with_error(con); if (mysql_query(con, "INSERT INTO Cars VALUES(4,'Volvo',29000)")) finish_with_error(con); if (mysql_query(con, "INSERT INTO Cars VALUES(5,'Bentley',350000)")) finish_with_error(con); if (mysql_query(con, "INSERT INTO Cars VALUES(6,'Citroen',21000)")) finish_with_error(con); if (mysql_query(con, "INSERT INTO Cars VALUES(7,'Hummer',41400)")) finish_with_error(con); if (mysql_query(con, "INSERT INTO Cars VALUES(8,'Volkswagen',21600)")) finish_with_error(con); //Display last inserted row id int id = mysql_insert_id(con); printf("The last inserted row id is: %d\n\n", id); //Look for data if (mysql_query(con, "SELECT * FROM Cars")) finish_with_error(con); //Store the data MYSQL_RES *result = mysql_store_result(con); if (result == NULL) finish_with_error(con); //Display the column headers and data. int num_fields = mysql_num_fields(result); MYSQL_ROW row; MYSQL_FIELD *field; while (field = mysql_fetch_field(result)) { printf("%s ", field->name); } printf("\n"); while (row = mysql_fetch_row(result)) { for (int i = 0; i < num_fields; i++) { printf("%s ", row[i] ? row[i] : "NULL"); } printf("\n"); } mysql_free_result(result); mysql_close(con); exit(0); }
int main(int argc, char **argv) { MYSQL_STMT *stmt; MYSQL_BIND param[4]; char *sql = "insert into Measurements VALUES(?,?,?,?)"; int value, value_type, time_ms, sensor_id; size_t data_length = sizeof(value); int affected_rows; MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } if (mysql_real_connect(con, "localhost", "till", NULL, "till", 0, NULL, 0) == NULL) { finish_with_error(con); } if (mysql_query(con, "DROP TABLE IF EXISTS Measurements")) { finish_with_error(con); } if (mysql_query(con, "CREATE TABLE Measurements(value INT, time INT, valuetype INT, sensor_id INT) engine=myisam")) { finish_with_error(con); } if (mysql_query(con, "INSERT INTO Measurements VALUES(1,1,1,1)")) { finish_with_error(con); } stmt = mysql_stmt_init(con); if (!stmt) { fprintf(stderr, " mysql_stmt_init(), out of memory\n"); exit(EXIT_FAILURE); } if (mysql_stmt_prepare(stmt, sql, strlen(sql))) { fprintf(stderr, " mysql_stmt_prepare(), INSERT failed\n"); fprintf(stderr, " %s\n", mysql_stmt_error(stmt)); exit(EXIT_FAILURE); } memset(param, 0, sizeof(param)); param[0].buffer_type = MYSQL_TYPE_LONG; param[0].buffer = (char *)&value; param[0].buffer_length = sizeof(value); param[0].is_null = 0; param[0].length = &data_length; param[1].buffer_type = MYSQL_TYPE_LONG; param[1].buffer = (char *)&value_type; param[1].buffer_length = sizeof(value); param[1].is_null = 0; param[1].length = &data_length; param[2].buffer_type = MYSQL_TYPE_LONG; param[2].buffer = (char *)&time_ms; param[2].buffer_length = sizeof(value); param[2].is_null = 0; param[2].length = &data_length; param[3].buffer_type = MYSQL_TYPE_LONG; param[3].buffer = (char *)&sensor_id; param[3].buffer_length = sizeof(value); param[3].is_null = 0; param[3].length = &data_length; if (mysql_stmt_bind_param(stmt, param)) { fprintf(stderr, " mysql_stmt_bind_param() failed\n"); fprintf(stderr, " %s\n", mysql_stmt_error(stmt)); exit(EXIT_FAILURE); } int iValues = 10000; int iSensors = 10; int i,j; intmax_t t; //printf("%ld\n", get_current_time_in_ms()); for(i=0;i<iValues;i++) { t = get_current_time_in_ms(); for(j=0;j<iSensors;j++) { value = i+j; value_type = VALUE_TYPE_TEMP_CENTIGRADE; time_ms = t; sensor_id = j; if (mysql_stmt_execute(stmt)) { fprintf(stderr, " mysql_stmt_execute(), 1 failed\n"); fprintf(stderr, " %s\n", mysql_stmt_error(stmt)); exit(EXIT_FAILURE); } } } mysql_close(con); exit(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); } }