示例#1
0
文件: Network.c 项目: tv/battleship
THREAD(udpTrapReceiveThread, arg)
{
	//NutThreadSetPriority(32);
	NH * nh = (NH*)arg;

	uint8_t data[256];
	uint32_t addr;
	uint16_t port;
	int i;

	for(;;)
	{
		i = NutUdpReceiveFrom(nh->udpTrapSock, &addr, &port, data, 256, 0);

		//printf("Some trap traffic...\n");
		data[i] = '\0';
		if (i > 0)
		{
			//printf("a trap received...\n");
			if(nh->opponent == addr)
			{
				snmpPacket* packetIn = snmp_packetalloc(); //input
				snmp_parse(packetIn, data, i);

				uint8_t* ptr = (uint8_t*)packetIn->value;
				strcpy(nh->trapMessage, ptr);
				// printf("Viesti: \"%s\"\n", ptr);
				nh->opponent = 0;
				snmp_free(packetIn);
			}
		}else if( i== 0) printf("trap thread running\n");
		else printf("trap thread running\n");
	}
}
示例#2
0
int main(int argc, char *argv[]) {
	struct timeval now;
	char *conf_file = NULL;
	double begin_time, end_time;
	int num_rows;
	int device_counter = 0;
	int last_active_threads = 0;
	long int THREAD_SLEEP = 100000;
	time_t nowbin;
	const struct tm *nowstruct;

	pthread_t* threads = NULL;
	pthread_attr_t attr;
	pthread_mutexattr_t mutexattr;

	int* ids = NULL;
	MYSQL mysql;
	MYSQL_RES *result = NULL;
	MYSQL_ROW mysql_row;
	int canexit = 0;
	int host_id;
	int i;
	int mutex_status = 0;
	int thread_status = 0;
	char result_string[BUFSIZE] = "";
	char logmessage[LOGSIZE];

	/* set start time for cacti */
	gettimeofday(&now, NULL);
	begin_time = (double) now.tv_usec / 1000000 + now.tv_sec;

	/* get time for poller_output table */
	if (time(&nowbin) == (time_t) - 1)
		printf("ERROR: Could not get time of day from time()\n");

	nowstruct = localtime(&nowbin);

	if (strftime(start_datetime, sizeof(start_datetime), "%Y-%m-%d %H:%M:%S", nowstruct) == (size_t) 0)
		printf("ERROR: Could not get string from strftime()\n");

	set.verbose = POLLER_VERBOSITY_HIGH;

	/* get static defaults for system */
	config_defaults(&set);

	/* scan arguments for errors */
	if ((argc != 1) && (argc != 3)) {
		printf("ERROR: Cactid requires either 0 or 2 input parameters\n");
		printf("USAGE: <cactidpath>/cactid [start_id end_id]\n");
		exit(-1);
	}

	/* return error if the first arg is greater than the second */
	if (argc == 3) {
		if (atol(argv[1]) > atol(argv[2])) {
			printf("ERROR: Invalid row specifications.  First row must be less than the second row\n");
			exit(-2);
		}
	}

	/* read configuration file to establish local environment */
	if (conf_file) {
		if ((read_cactid_config(conf_file, &set)) < 0) {
			printf("ERROR: Could not read config file: %s\n", conf_file);
			exit(-3);
		}
	}else{
		conf_file = malloc(BUFSIZE);

		if (!conf_file) {
			printf("ERROR: Fatal malloc error!\n");
			exit(-1);
		}

		for(i=0;i<CONFIG_PATHS;i++) {
			snprintf(conf_file, BUFSIZE, "%s%s", config_paths[i], DEFAULT_CONF_FILE);

			if (read_cactid_config(conf_file, &set) >= 0) {
				break;
			}

			if (i == CONFIG_PATHS-1) {
				snprintf(conf_file, BUFSIZE, "%s%s", config_paths[0], DEFAULT_CONF_FILE);
			}
		}
	}

	/* read settings table from the database to further establish environment */
	read_config_options(&set);

	/* set the poller ID, stub for next version */
	set.poller_id = 0;

	if (set.verbose == POLLER_VERBOSITY_DEBUG) {
		snprintf(logmessage, LOGSIZE, "CACTID: Version %s starting\n", VERSION);
		cacti_log(logmessage);
	} else {
		printf("CACTID: Version %s starting\n", VERSION);
	}

	/* connect to database */
	db_connect(set.dbdb, &mysql);

	/* initialize SNMP, Unix only */
	#if !defined(__CYGWIN__)
	init_snmp("cactid");
	#endif

	/* initialize PHP */
	php_init();

	/* get the id's to poll */
	switch (argc) {
		case 1:
			result = db_query(&mysql, "SELECT id FROM host WHERE disabled='' ORDER BY id");

			break;
		case 3:
			snprintf(result_string, sizeof(result_string), "SELECT id FROM host WHERE (disabled='' and (id >= %s and id <= %s)) ORDER BY id\0", argv[1], argv[2]);
			result = db_query(&mysql, result_string);

			break;
		default:
			break;
	}

	num_rows = mysql_num_rows(result);
	threads = (pthread_t *)malloc(num_rows * sizeof(pthread_t));
	ids = (int *)malloc(num_rows * sizeof(int));

	/* initialize threads and mutexes */
	pthread_attr_init(&attr);

	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	init_mutexes();

	if (set.verbose == POLLER_VERBOSITY_DEBUG) {
		snprintf(logmessage, LOGSIZE, "DEBUG: Initial Value of Active Threads is %i\n", active_threads);
		cacti_log(logmessage);
	}

	/* loop through devices until done */
	while (device_counter < num_rows) {
		mutex_status = thread_mutex_trylock(LOCK_THREAD);

		switch (mutex_status) {
		case 0:
			if (set.verbose == POLLER_VERBOSITY_DEBUG) {
				snprintf(logmessage, LOGSIZE, "DEBUG: Valid Thread to be Created\n");
				cacti_log(logmessage);
			}
			if (last_active_threads != active_threads) {
				last_active_threads = active_threads;
			}

			while ((active_threads < set.threads) && (device_counter < num_rows)) {
				mysql_row = mysql_fetch_row(result);
				host_id = atoi(mysql_row[0]);
				ids[device_counter] = host_id;

				/* create child process */
				thread_status = pthread_create(&threads[device_counter], &attr, child, &ids[device_counter]);

				switch (thread_status) {
					case 0:
						if (set.verbose == POLLER_VERBOSITY_DEBUG) {
							snprintf(logmessage, LOGSIZE, "DEBUG: Valid Thread to be Created\n");
							cacti_log(logmessage);
						}

						device_counter++;
						active_threads++;

						if (set.verbose == POLLER_VERBOSITY_DEBUG) {
							snprintf(logmessage, LOGSIZE, "DEBUG: The Value of Active Threads is %i\n", active_threads);
							cacti_log(logmessage);
						}

						break;
					case EAGAIN:
						snprintf(logmessage, LOGSIZE, "ERROR: The System Lacked the Resources to Create a Thread\n");
						cacti_log(logmessage);
						break;
					case EFAULT:
						snprintf(logmessage, LOGSIZE, "ERROR: The Thread or Attribute Was Invalid\n");
						cacti_log(logmessage);
						break;
					case EINVAL:
						snprintf(logmessage, LOGSIZE, "ERROR: The Thread Attribute is Not Initialized\n");
						cacti_log(logmessage);
						break;
					default:
						snprintf(logmessage, LOGSIZE, "ERROR: Unknown Thread Creation Error\n");
						cacti_log(logmessage);
						break;
				}
				usleep(500);
			}

			thread_mutex_unlock(LOCK_THREAD);

			break;
		case EBUSY:
			snprintf(logmessage, LOGSIZE, "ERROR: Deadlock Occured\n");
			cacti_log(logmessage);
			break;
		case EINVAL:
			snprintf(logmessage, LOGSIZE, "ERROR: Attempt to Unlock an Uninitialized Mutex\n");
			cacti_log(logmessage);
			break;
		case EFAULT:
			snprintf(logmessage, LOGSIZE, "ERROR: Attempt to Unlock an Invalid Mutex\n");
			cacti_log(logmessage);
			break;
		default:
			snprintf(logmessage, LOGSIZE, "ERROR: Unknown Mutex Lock Error Code Returned\n");
			cacti_log(logmessage);
			break;
		}

		usleep(THREAD_SLEEP);
	}

	/* wait for all threads to complete */
	while (canexit == 0) {
		if (thread_mutex_trylock(LOCK_THREAD) != EBUSY) {
			if (last_active_threads != active_threads) {
				last_active_threads = active_threads;
			}

			if (active_threads == 0) {
				canexit = 1;
			}

			thread_mutex_unlock(LOCK_THREAD);
		}

		usleep(THREAD_SLEEP);
	}

	/* print out stats */
	gettimeofday(&now, NULL);

	/* update the db for |data_time| on graphs */
	db_insert(&mysql, "replace into settings (name,value) values ('date',NOW())");
	db_insert(&mysql, "insert into poller_time (poller_id, start_time, end_time) values (0, NOW(), NOW())");

	/* cleanup and exit program */
	pthread_attr_destroy(&attr);
	pthread_mutexattr_destroy(&mutexattr);

	if (set.verbose == POLLER_VERBOSITY_DEBUG) {
		cacti_log("DEBUG: Thread Cleanup Complete\n");
	}

	/* cleanup the snmp process*/
    #if !defined(__CYGWIN__)
	snmp_free();

	if (set.verbose == POLLER_VERBOSITY_DEBUG) {
		cacti_log("DEBUG: SNMP Cleanup Complete\n");
	}
	#endif

	/* close the php script server */
	php_close();

	if (set.verbose == POLLER_VERBOSITY_DEBUG) {
		cacti_log("DEBUG: PHP Script Server Pipes Closed\n");
	}

	/* free malloc'd variables */
	free(threads);
	free(ids);
	free(conf_file);

	if (set.verbose == POLLER_VERBOSITY_DEBUG) {
		cacti_log("DEBUG: Allocated Variable Memory Freed\n");
	}

	/* close mysql */
	mysql_free_result(result);
	mysql_close(&mysql);

	if (set.verbose == POLLER_VERBOSITY_DEBUG) {
		cacti_log("DEBUG: MYSQL Free & Close Completed\n");
	}

	/* finally add some statistics to the log and exit */
	end_time = (double) now.tv_usec / 1000000 + now.tv_sec;

	if ((set.verbose >= POLLER_VERBOSITY_MEDIUM) && (argc != 1)) {
		snprintf(logmessage, LOGSIZE, "Time: %.4f s, Threads: %i, Hosts: %i\n", (end_time - begin_time), set.threads, num_rows);
		cacti_log(logmessage);
	} else {
		printf("CACTID: Execution Time: %.4f s, Threads: %i, Hosts: %i\n", (end_time - begin_time), set.threads, num_rows);
	}

	exit(0);
}
示例#3
0
文件: Network.c 项目: tv/battleship
THREAD(udpReceiveThread, arg)
{
	NH * nh = (NH*)arg;
	uint8_t data[256];
	uint32_t addr;
	uint16_t port;
	int i;
	for(;;)
	{
		i = NutUdpReceiveFrom(nh->udpSock, &addr, &port, data, 256, 0);
		data[i] = '\0';
		if (i > 0)
		{
			//printf("Udp connection\n");
			//printf("%s:%d \n", inet_ntoa(addr), port);
			//fflush(stdout);

			//bool doCleanPacketIn = true;

			snmpPacket* packetIn = snmp_packetalloc();
			snmpPacket* packetOut = snmp_packetalloc();
			snmp_parse(packetIn, data, i);

			packetOut->command 		= SNMP_GET_RESP;
			packetOut->requestID 	= packetIn->requestID;
			packetOut->objectID		= packetIn->objectID;

			long value;

			// --- vastataan ready to play -viestiin
			if(packetIn->objectID == 1 && packetIn->command == SNMP_GET_REQ) //READY-TO-PLAY -message
			{
				if(nh->readyToPlay == true)
					value = 1;
				else value = 0;
				packetOut->valueType	= SNMP_INT;
				packetOut->valueLength	= 1;
				packetOut->value		= &value;
				packetOut->error 		= 0x00;

				snmp_construct(packetOut);
				NutUdpSendTo(nh->udpSock, addr, port, packetOut->packet, packetOut->length);
			}
			// --- odotetaan vastausta ready to play viestiin
			else if(nh->getOpponentList && packetIn->objectID == 1 && packetIn->command == SNMP_GET_RESP)
			{
				uint8_t tmp;
				tmp = *((uint8_t*)(packetIn->value));
				if(tmp == 1) //fill the opponent list, if broadcast is sent
				{
					nh->opponentList[nh->numOpponents] = addr;
					nh->numOpponents++;
				}
			}
			// --- haaste vastaanotettu
			else if (nh->opponent == 0 && packetIn->objectID == 2 && packetIn->command == SNMP_SET_REQ)
			{
				nh->openRequest = true;
				nh->opponent  = addr;
				nh->requestID = packetIn->requestID;
			}
			//haaste vastaanotettu, mutta meillä oli jo haaste päällä
			else if ( (nh->openRequest || addr != nh->opponent) && packetIn->objectID == 2 && packetIn->command == SNMP_SET_REQ)
				NH_sendSnmpError(nh, addr, SNMP_PORT, SNMP_GET_RESP, 2, packetOut->requestID);
			// --- odotetaan vastausta haasteeseen
			else if( packetIn->objectID == 2 && nh->challengeSend == true && nh->opponent == addr &&
					 packetIn->command == SNMP_GET_RESP )
			{
				nh->challengeSend = false;
				if( packetIn->error != 0x00)
					nh->opponent = false;
				else
					nh->challengeAccepted = true;
			}
			// --- odotetaan vastustajan START-TURN
			else if(packetIn->objectID == 2 && nh->opponent == addr &&
					packetIn->command == SNMP_SET_REQ )
			{
				nh->enemyStartedTurn = true;
				//printf("NW: enemy started turn\n");
			}

			// --- odotetaan vastustajalta OK-viestiä
			else if(nh->opponent == addr && packetIn->command == SNMP_GET_RESP
					&& packetIn->objectID == nh->currentOID && packetIn->valueType == SNMP_INT)
			{
				if(packetIn->error == 0x00)
				{
					nh->enemyOK = true;
					//printf("NW: Received enemyOK!\n");
				}
			}

			// --- odotetaan salvoja
			else if( packetIn->objectID == 3 && nh->opponent == addr && packetIn->command == SNMP_SET_REQ )
			{
				nh->enemySalvoReceived = true;
				//printf("NW: SALVO received (%d):\n", nh->enemySalvoReceived); // debug
				uint8_t* ptr = (uint8_t*)packetIn->value;
				for(i = 0; i < 5; i++)
				{
					nh->lastEnemySalvo[i].x = ptr[i*2];
					nh->lastEnemySalvo[i].y = ptr[i*2+1];
					//printf("%d - %d\n", nh->lastEnemySalvo[i].x, nh->lastEnemySalvo[i].y);
				}
				// OK vastaus
				NH_sendBooleanResponse(nh, 3, true);
			}
			// --- Odotetaan salvon  tuloksia
			else if( packetIn->objectID == 4 && nh->opponent == addr && packetIn->command == SNMP_GET_RESP)
			{
				//printf("NW: SALVO results received: \n"); // debug
				uint8_t* ptr = (uint8_t*)packetIn->value;
				for (i = 0; i < 5; i++)
					nh->salvoResults[i] = ptr[i];

				//debug
				//for (i = 0; i < 5; i++)
					//printf("%d:  %d\n", i, nh->salvoResults[i]);

				nh->salvoResultsReceived = true;
			}
			// --- odotetaan salvon tuloksien pyyntöä
			else if(packetIn->objectID == 4 && packetIn->command == SNMP_GET_REQ && nh->opponent == addr)
			{
				nh->resultsQueryReceived = true;
				//printf("NW: enemy asked for salvo results: %d\n", nh->resultsQueryReceived);
			}
			// --- chattiviesti:
			else if(packetIn->objectID == 5 && packetIn->command == SNMP_SET_REQ && packetIn->valueType == SNMP_OCT)
			{
				/*
				uint8_t* ptr = (uint8_t*)packetIn->value;

				//lisätään viestin alkuun lähettähän ip
				sprintf(nh->chatMsgs[nh->emptyMsg], inet_ntoa(addr));
				strcat(nh->chatMsgs[nh->emptyMsg], ":\n");
				strncat(nh->chatMsgs[nh->emptyMsg], message, MAX_MSG_LENGTH - 16);

				//lisätään viesti listaan
				sprintf(chatMsgs[nh->emptyMsg], ptr);
				nh->manageMessages();
				*/
			}
			else if(packetIn->command == SNMP_GET_REQ) //debug
			{
				printf("NW: weird SNMP_GET_REQ received, OID: %d, opponent: %s", packetIn->objectID, inet_ntoa(nh->opponent));
			}
			snmp_free(packetIn);
			snmp_free(packetOut);
		}
		else if (i == 0)
		{
			printf ("Udp timeout\n");
		}
		else
		{
			printf ("Udp error\n");
		}

	}
}