void *engine_run(void *args) { engine *p = (engine *) args; time_t current_second; struct timespec tick_start, tick_end, remaining_sleep; long elapsed_nanos; p->stats.run_start = clock(); glog(LOG_INFO, "Engine: Starting"); while (p->keep_running) { p->current_tick++; current_second = time(NULL); clock_gettime(CLOCK_MONOTONIC, &tick_start); _engine_check_active_clients(p, current_second); _engine_process_command_queue(p); engine_update_gamerooms(p); clock_gettime(CLOCK_MONOTONIC, &tick_end); elapsed_nanos = tick_end.tv_nsec - tick_start.tv_nsec; if(elapsed_nanos > 1000){ } remaining_sleep = p->sleep; remaining_sleep.tv_nsec -= elapsed_nanos; nanosleep(&remaining_sleep, NULL); } p->stats.run_end = clock(); glog(LOG_INFO, "Engine: Finished"); netadapter_shutdown(&p->netadapter); return NULL; }
void _engine_process_command_queue(engine *p) { network_command cmd; net_client *p_cli; int ret_val; char *reason; while (!cmd_queue_is_empty(&p->cmd_in_queue)) { cmd = cmd_queue_get(&p->cmd_in_queue); p_cli = engine_client_by_socket(p, cmd.origin_socket); if (p_cli == NULL) { ret_val = _engine_authorize_connection(p, cmd); if (ret_val) { p->p_netadapter->stats->commands_received_invalid++; netadapter_close_connection_by_socket(p->p_netadapter, cmd.origin_socket); } continue; } ret_val = _engine_process_command(p, p_cli, cmd); if (ret_val) { reason = _engine_close_connection_label(ret_val); glog(LOG_FINE, "Engine: Closing connection on socket %02d, reason = %s", p_cli->connection->socket, reason); netadapter_close_connection_by_client(p->p_netadapter, p_cli); } } }
/** \brief Generic Wavelet-Denoising. \ingroup grpwavelet compute DWT of signal, call the thresholding function 'threshfct' for each resolution level and IDWT the signal */ int wavelet_denoise ( double *data, int n, WaveletParameters P ){ gsl_wavelet *w; gsl_wavelet_workspace *work; int j, J, k, offset; double lambda; /* population sd, threshold */ dprintf("Db: generic_denoising\n"); w = gsl_wavelet_alloc( P.wavelet, P.vanishing_moments ); work = gsl_wavelet_workspace_alloc( n ); gsl_wavelet_transform_forward( w, data, 1, n, work ); /* -- thresholding here -- */ J = (int)round(glog((double)n, 2)); for(j=P.first_thresholding_level; j<J; j++){ /* loop through levels */ offset = (int)pow(2, j); lambda = (*(P.threshselfct))(&(data[offset]), offset); for(k=offset; k<2*offset; k++){ /* loop through coefficients */ /* soft or hard thresholding */ data[k]=(*(P.threshfct))(data[k], lambda); } } /* -- thresholding end -- */ gsl_wavelet_transform_inverse(w, data, 1, n, work); gsl_wavelet_free(w); gsl_wavelet_workspace_free(work); return 0; }
/** \brief Wavelet estimation of single trial ERP's using Wang et al.'s (2007) technique. \ingroup grpwavelet Formula \f[ \lambda = \sigma \sqrt{2\log_e{n\log_2{n}}} \f]. */ double translation_invariant_thresholding(const double *data, int n){ dprintf("Db: translation_invariant_thresholding\n"); double sigma, lambda; /* population sd, threshold */ sigma = mad(data, n)/0.6745; /* funny constant, eh? */ lambda = sigma * sqrt(2*log(n*glog(n, 2))); return lambda; }
char char_from_num(my_byte val){ char buf[2]; if(val < 0 || val > 16){ glog(LOG_WARNING, "Invalid char value %d", val); return 'X'; } snprintf(buf, 2, "%01X", val); return buf[0]; }
/* Display the console Web page */ void show_web_ui(int csock, char *request) { char *data = NULL; int data_size = 0; if(!request) { glog("NULL request received by Web UI",LOG_ERROR_TYPE); return; } /* Point data at the data blob associated with the requested URL */ if(strstr(request,BODY_BG_PNG_PATH)) { data = BODY_BG_PNG; data_size = BODY_BG_PNG_SIZE; } else if(strstr(request,HEADER_PNG_PATH)) { data = HEADER_PNG; data_size = HEADER_PNG_SIZE; } else if(strstr(request,HEADER_BG_PNG_PATH)) { data = HEADER_BG_PNG; data_size = HEADER_PNG_SIZE; } else if(strstr(request,FOOTER_BG_PNG_PATH)) { data = FOOTER_BG_PNG; data_size = FOOTER_BG_PNG_SIZE; } else if((strlen(request) == INDEX_PATH_SIZE) && (memcmp(request,INDEX_PATH,INDEX_PATH_SIZE) == 0)) { data = PROXY_HTML; data_size = PROXY_HTML_SIZE; } if(data) { /* Write data to browser */ if(send_http_response(csock,data,data_size) == SOCK_FAIL) { glog("Proxy server failed to write image data to client browser",LOG_ERROR_TYPE); return; } } else { /* Write client list to browser */ print_client_list(csock); } return; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); std::string logfile = createLogDir("./logs"); GLogger glog( argv[0], logfile.c_str() ); std::cout << "Log to path: " << logfile << std::endl; MainWindow w; w.show(); return a.exec(); }
/* Add the extension to the list of extensions to filter. These extensions will not be proxied through the client browser. */ void filter_ext(char *ext) { char *query = sqlite3_mprintf("INSERT INTO %s (extension) VALUES (%Q)",FILTER_TABLE,ext); char *message = NULL; int result_size = 0, err_code = 0; sql_exec(query,&result_size,&err_code); sqlite3_free(query); if(err_code != SQLITE_OK){ message = sqlite3_mprintf("Failed to add extension filter for file extension '%s'",ext); glog(message,LOG_ERROR_TYPE); sqlite3_free(message); } return; }
int warzone_set_block(warzone *p, int x, int y, block b) { struct block_diff diff; int changed = tunneler_map_set_block(&p->map, x, y, b); if(!changed){ return p->map_change_count; } if(p->map_change_count + 1 >= WARZONE_BLOCK_DIFF_BUFFER_SIZE){ glog(LOG_ERROR, "Warzone block diff buffer overflow"); } diff.x = x; diff.y = y; diff.b = b; p->map_change_buffer[p->map_change_count] = diff; return ++p->map_change_count; }
int main(void) { GEN M,N1,N2, F1,F2,D; struct pari_thread pth[MAXTHREADS]; int numth = omp_get_max_threads(), i; /* Initialise the main PARI stack and global objects (gen_0, etc.) */ pari_init(4000000,500000); if (numth > MAXTHREADS) { numth = MAXTHREADS; omp_set_num_threads(numth); } /* Compute in the main PARI stack */ N1 = addis(int2n(256), 1); /* 2^256 + 1 */ N2 = subis(int2n(193), 1); /* 2^193 - 1 */ M = mathilbert(80); /*Allocate pari thread structures */ for (i = 1; i < numth; i++) pari_thread_alloc(&pth[i],4000000,NULL); #pragma omp parallel { int this_th = omp_get_thread_num(); if (this_th) (void)pari_thread_start(&pth[this_th]); #pragma omp sections { #pragma omp section { F1 = factor(N1); } #pragma omp section { F2 = factor(N2); } #pragma omp section { D = det(M); } } /* omp sections */ if (this_th) pari_thread_close(); } /* omp parallel */ pari_printf("F1=%Ps\nF2=%Ps\nlog(D)=%Ps\n", F1, F2, glog(D,3)); for (i = 1; i < numth; i++) pari_thread_free(&pth[i]); return 0; }
/**\brief Extend data to length 2^j using sigextfct and denoise it. \ingroup grpwavelet * \see generic_denoising() */ int wavelet_extend_and_denoise ( double *data, int n, WaveletParameters P ){ int J; double *tmp, *dptr; J = (int)round(glog((double)n, 2)); J++; if(((int)pow(2, J))<n) dprintf(" Warning: Signal length %i is not a power of 2 -> extending signal to length %i\n", n, (int)pow(2,J)); tmp = (double*)malloc((int)pow(2,J) * sizeof(double)); tmp = memcpy(tmp, data, n*sizeof(double)); dptr=(*(P.sigextfct))(tmp, n, (int)pow(2, J)); wavelet_denoise(tmp, (int)pow(2,J), P ); data = memcpy(data, dptr, n*sizeof(double)); free(tmp); return 0; }
int _engine_process_command(engine *p, net_client *p_cli, network_command cmd) { int(* handle_action) ENGINE_HANDLE_FUNC_HEADER; str_scanner scanner; game_room *p_gr; int ret_val; if (cmd.type < 0 || cmd.type > NETWORK_COMMAND_TYPES_COUNT) { network_command_prepare(&p_cli->connection->_out_buffer, NCT_LEAD_DISCONNECT); snprintf(p_cli->connection->_out_buffer.data, NETWORK_COMMAND_DATA_LENGTH, g_loc.server_protection_illegal_cmd_type, cmd.type); engine_send_command(p, p_cli, &p_cli->connection->_out_buffer); return ENGINE_CLOSE_REASON_ACTION_NOT_IMPLEMENTED; } handle_action = p->command_proccess_func[cmd.type]; if (handle_action == NULL) { network_command_prepare(&p_cli->connection->_out_buffer, NCT_LEAD_DISCONNECT); snprintf(p_cli->connection->_out_buffer.data, NETWORK_COMMAND_DATA_LENGTH, g_loc.server_protection_unimplemented_cmd_type, cmd.type); engine_send_command(p, p_cli, &p_cli->connection->_out_buffer); return ENGINE_CLOSE_REASON_ACTION_NOT_IMPLEMENTED; } str_scanner_set(&scanner, cmd.data, cmd.length); p_gr = engine_game_room_by_id(p, p_cli->room_id); ret_val = handle_action(p, p_cli, &scanner, p_gr); if (ret_val) { glog(LOG_FINE, "Processed command of type 0x%2X from client %d which " "resulted in %s", cmd.type, p_cli - p->resources->clients , _engine_cmd_exe_retval_label(ret_val)); netadapter_handle_invallid_command(p->p_netadapter, p_cli, cmd); p->p_netadapter->stats->commands_received_invalid++; if (p_cli->connection->invalid_counter > p->p_netadapter->ALLOWED_INVALLID_MSG_COUNT) { return ENGINE_CLOSE_REASON_TOO_MANY_INVALIDES; } } return 0; }
void _engine_check_active_clients(engine *p, time_t now) { int i; net_client *p_cli; for (i = 0; i < p->resources->clients_length; i++) { p_cli = p->resources->clients + i; if (p_cli->connection != NULL) { // connection is open // _engine_check_client_for_idling(p, p_cli, now); } else { // connection is not open if (p_cli->status != NET_CLIENT_STATUS_DISCONNECTED && p_cli->status != NET_CLIENT_STATUS_EMPTY) { glog(LOG_FINE, "Engine: Client %d found to be disconnected", i); engine_client_disconnected(p, p_cli, "Client timed out"); } } } }
int main() { if (oamlInitAudioDevice(44100, 2) != OAML_OK) { fprintf(stderr, "Unable to open audio device!\n"); exit(1); } oamlInit("oaml.defs"); // for some better random numbers (and not always the same) srand(time(NULL)); init_curses(); main_menu(); oamlShutdown(); end_curses(); // free the allocated memory for the highscore read_highscore(NULL); // close the logfile glog(NULL); return EXIT_SUCCESS; }
void *engine_cli_run(void *args) { engine *p_engine = (engine *) args; char input[ENGINE_CLI_BUFFER_SIZE]; while (p_engine->keep_running) { printf("TTS >: "); memset(input, 0, ENGINE_CLI_BUFFER_SIZE); scanf("%s", input); if (!strcmp(input, "exit")) { _cli_shutdown(p_engine); } else if (!strcmp(input, "clients")) { _cli_list_clients(&p_engine->netadapter); } else if (!strcmp(input, "connections")) { _cli_list_connections(&p_engine->netadapter); } else if (!strcmp(input, "status")) { _cli_status(p_engine); } else if (!strcmp(input, "rooms")) { _cli_list_rooms(p_engine); } } glog(LOG_FINE, "Engine CLI: Exittig"); return NULL; }
void engine_update_gamerooms(engine *p) { int i; game_room *p_gr; void(* update_action)(engine *, game_room *); int tickskip; for (i = 0; i < p->resources->game_rooms_length; i++) { p_gr = p->resources->game_rooms + i; if (p_gr->state < 0 || p_gr->state >= GAME_ROOM_STATES_COUNT) { glog(LOG_WARNING, "Game room %d is in invalid state.", i); engine_game_room_cleanup(p, p_gr); continue; } update_action = p->game_room_update_functions[p_gr->state]; if (update_action == NULL) { continue; } tickskip = p->game_room_update_tickskip[p_gr->state]; if ((p->current_tick + p_gr->state) % tickskip == 0) { update_action(p, p_gr); } } }
/* Used by the proxy server to display active IPs. Prints results to csock. */ void print_client_list(int csock) { int rc = 0, col_type = 0, line_size = 0, class_toggle = TD_GREY; sqlite3_stmt *stmt = NULL; char *ip = NULL, *timestamp = NULL, *line = NULL; char *query = NULL, *path = NULL, *attack_port = NULL; /* Write out the HTML table headers */ if(write(csock,CLIENT_TABLE_HEADERS,CLIENT_TABLE_HEADERS_SIZE) != CLIENT_TABLE_HEADERS_SIZE) { glog("Proxy server failed to write out the client table headers",LOG_ERROR_TYPE); return; } /* Prepare the SQL query */ query = sqlite3_mprintf("SELECT ip,callback_time FROM %s WHERE strftime('%%s',callback_time) > strftime('%%s','now') ORDER BY id",CLIENTS_TABLE); if(!query) { sql_log_error(); return; } rc = sqlite3_prepare_v2(globals.db,query,strlen(query),&stmt,NULL); if(rc != SQLITE_OK) { sql_log_error(); sqlite3_free(query); return; } path = config_get_path(); attack_port = config_get_attack_port(); /* Loop until the query has finished */ while((rc = sqlite3_step(stmt)) != SQLITE_DONE) { switch(rc) { case SQLITE_ERROR: sql_log_error(); sqlite3_finalize(stmt); sqlite3_free(query); if(path) free(path); if(attack_port) free(attack_port); return; case SQLITE_BUSY: /* If the table is locked, wait then try again */ usleep(BUSY_WAIT_PERIOD); break; case SQLITE_ROW: { col_type = sqlite3_column_type(stmt,0); switch(col_type) { case SQLITE_TEXT: ip = (void *) sqlite3_column_text(stmt,0); timestamp = (void *) sqlite3_column_text(stmt,1); line = sqlite3_mprintf("<tr class=\"tr%d\" onmouseover=\"lock_updates()\" onmouseout=\"unlock_updates()\" onclick=\"go('%s:%s%s')\"><td>%s</td><td>%s</td></tr>",class_toggle,ip,attack_port,path,ip,timestamp); if(!line) { glog("Failed to generate Web UI entry",LOG_ERROR_TYPE); break; } line_size = strlen(line); if(write(csock,line,line_size) != line_size) { glog("Proxy server failed to write out active client list to Web UI",LOG_ERROR_TYPE); } /* Toggle the class (and thus, the color) of the next table row */ if(class_toggle) { class_toggle = TD_GREY; } else { class_toggle = TD_WHITE; } sqlite3_free(line); line_size = 0; break; } } } } sqlite3_finalize(stmt); sqlite3_free(query); if(path) free(path); if(attack_port) free(attack_port); return; }
int proxy_server() { int rx_bytes = 0, post_data_size = 0; int lsock = 0, csock = 0, client_data_size = 0; int result_size = 0, err_code = 0, id = 0; int addrlen = sizeof(struct sockaddr_in); struct sockaddr_in clientaddr; char *buffer = NULL, *post_data = NULL; char *host = NULL, *url = NULL; char *query = NULL, *fifo_file = NULL; char *get_data = NULL; char *client_data = NULL, *headers = NULL; char *server_ip = NULL; memset((void *) &clientaddr,0,addrlen); server_ip = config_get_server_ip(); /* Create TCP socket */ if((lsock = create_socket(server_ip,PROXY_PORT,SOCK_STREAM)) == SOCK_FAIL) { glog("Failed to create TCP socket for proxy server",LOG_ERROR_TYPE); if(server_ip) free(server_ip); return EXIT_FAILURE; } if(server_ip) free(server_ip); /* Infinite receive loop */ while(1) { /* Accept incoming connection */ if((csock = accept(lsock,(struct sockaddr *) &clientaddr,(socklen_t *) &addrlen)) < 0) { glog("Failed to accept TCP connection to proxy server",LOG_ERROR_TYPE); if(buffer) free(buffer); return EXIT_FAILURE; } if(!fork()) { /* Receive client request */ if((buffer = receive(lsock,SOCK_STREAM,&rx_bytes,csock,&clientaddr)) == NULL) { glog("Failed to read data from client request sent to proxy server",LOG_ERROR_TYPE); exit(EXIT_FAILURE); } if(is_using_proxy(buffer)) { /* Get the target's IP address */ host = get_host_name(buffer); /* Get the target URL path */ url = get_url(buffer); /* Get POST data, if any */ post_data = get_post_data(buffer,rx_bytes,&post_data_size); /* Get HTTP headers from request */ headers = get_headers(buffer); /* If the CONSOLE_HOST is requested, then display the Web console interface */ if(memcmp(host,CONSOLE_HOST,CONSOLE_HOST_SIZE) == 0) { show_web_ui(csock,url); close_socket(csock); } else { /* Make sure the requested host is in our clients list */ query = sqlite3_mprintf("SELECT id FROM %s WHERE strftime('%%s',callback_time) >= strftime('%%s','now') AND ip = %Q LIMIT 1",CLIENTS_TABLE,host); sql_exec(query,&result_size,&err_code); sqlite3_free(query); if(result_size > 0) { /* Don't allow requests for filtered file extensions */ if(!is_url_filtered(url)) { fifo_file = create_fifo(host); if(!fifo_file) { glog("Failed to create fifo file",LOG_ERROR_TYPE); } else { /* Insert query into queue table */ query = sqlite3_mprintf("INSERT INTO %s (fifo,host,url,headers,pdata,sent) VALUES (%Q,%Q,%Q,%Q,%Q,0)",QUEUE_TABLE,fifo_file,host,url,headers,post_data); sql_exec(query,&result_size,&err_code); sqlite3_free(query); if(err_code != SQLITE_OK) { sql_log_error(); } else { /* When the client data has returned, the callback server will write the ID of the callback to the FIFO */ id = read_from_fifo(fifo_file); /* Extract the data from the DB */ get_data = sqlite3_mprintf("SELECT rdata FROM %s WHERE id = '%d'",QUEUE_TABLE,id); client_data = sql_exec(get_data,&client_data_size,&err_code); sqlite3_free(get_data); if(err_code != SQLITE_OK) { sql_log_error(); } else { /* Write data to socket */ if(write(csock,client_data,client_data_size) != client_data_size) { glog("Proxy socket write failed",LOG_ERROR_TYPE); } } if(client_data) free(client_data); /* Make sure the fifo gets deleted */ destroy_fifo(fifo_file); } } } } } } /* Exit the child process */ close_socket(csock); if(fifo_file) free(fifo_file); if(buffer) free(buffer); if(host) free(host); if(url) free(url); if(post_data) free(post_data); if(headers) free(headers); exit(EXIT_SUCCESS); } } /* Close up shop */ close_socket(csock); close_socket(lsock); return EXIT_FAILURE; }
int _engine_authorize_connection(engine *p, network_command cmd) { net_client* p_cli; network_command cmd_out; my_byte reintroduce; int socket = cmd.origin_socket; if (cmd.type != NCT_LEAD_INTRODUCE) { glog(LOG_FINE, "Authorization of connection %02d failed because command" "type was not correct. Expected %d, got %d", socket, NCT_LEAD_INTRODUCE, cmd.type); return 1; } if (cmd.length < 2) { glog(LOG_FINE, "Authorization of connection %02d failed because command" " was too short", socket); return 1; } reintroduce = read_hex_byte(cmd.data); if (reintroduce) { p_cli = engine_client_by_secret(p, cmd.data + 2); if (p_cli == NULL) { reintroduce = 0; } else { if (p_cli->status != NET_CLIENT_STATUS_DISCONNECTED) { glog(LOG_FINE, "Reauthorization of connection %02d failed " "because command client is not disconnected", socket); return 1; } } } if (!reintroduce) { p_cli = engine_first_free_client_offset(p); } if (p_cli == NULL) { glog(LOG_FINE, "Authorization of socket %02d failed because there" "was no more room for new client", socket); return 1; } p->resources->con_to_cli[socket] = p_cli - p->resources->clients; if (!reintroduce) { net_client_init(p_cli, p->resources->connections + socket); strrand(p_cli->connection_secret, NET_CLIENT_SECRET_LENGTH); p_cli->connection_secret[NET_CLIENT_SECRET_LENGTH] = '\0'; p_cli->room_id = ITEM_EMPTY; } else { p_cli->connection = p->resources->connections + socket; } p_cli->status = NET_CLIENT_STATUS_CONNECTED; network_command_prepare(&cmd_out, NCT_LEAD_INTRODUCE); write_hex_byte(cmd_out.data, reintroduce); memcpy(cmd_out.data + 2, p_cli->connection_secret, NET_CLIENT_SECRET_LENGTH); netadapter_send_command(p->p_netadapter, p_cli->connection, &cmd_out); if (reintroduce) { _engine_authorize_reconnect(p, p_cli); } else { glog(LOG_INFO, "Connection %02d authorized as client %02d", socket, p->resources->con_to_cli[socket]); } return 0; }