Example #1
0
int main(int argc, char const *argv[]) {
    char strings[][73] = {  "$GPGGA,152606.000,3732.7200,N,07726.9881,W,1,4,1.56,159.0,M,-33.6,M,,*64",
                            "$GPGSA,A,3,21,14,22,24,,,,,,,,,1.85,1.56,0.99*0C",
                            "$GPRMC,152606.000,A,3732.7200,N,07726.9881,W,0.29,81.28,110413,,,A*48",
                            "$GPVTG,81.28,T,,M,0.29,N,0.53,K,A*03",
                            "$PGTOP,11,2*6E" };
    for (int i = 0; i < 5; i++) {
        nmea_parse(strings[i], strlen(strings[i]));
    }

    // Validate state
    within_range(get_latitude(), 37.545333, 0.00001f);
    within_range(get_longitude(), -77.449802, 0.00001f);
    within_range(get_altitude(), 159.0, 0.1f);
    validate_int(get_sat_count(), 4);
    validate_int(get_fix_type(), 3);

    nmea_parser_t *parser = nmea_parser_new();
    for (int i = 0; i < 5; i++) {
        nmea_parse_r(strings[i], strlen(strings[i]), parser);
    }
    within_range(get_latitude_r(parser), 37.545333, 0.00001f);
    within_range(get_longitude_r(parser), -77.449802, 0.00001f);
    within_range(get_altitude_r(parser), 159.0, 0.1f);
    validate_int(get_sat_count_r(parser), 4);
    validate_int(get_fix_type_r(parser), 3);
    nmea_parser_free(&parser); 
    assert(NULL == parser);
    return error;
}
Example #2
0
static int validate_one_option( const SPUOptions *opt, 
                const char *response,
                const char *min,
                const char *max )
{
    switch (opt->type) {
    case CR_BOOL:
        return validate_int( response, "0", "1" );
    case CR_INT:
        return validate_int( response, min, max );
    case CR_FLOAT:
        return validate_float( response, min, max );
    case CR_ENUM:
        /* Make sure response string is present in the min string.
         * For enums, the min string is a comma-separated list of valid values.
         */
        CRASSERT(opt->numValues == 1); /* an enum limitation for now */
        {
            const char *p = crStrstr(min, response);
            if (!p)
                return 0;  /* invalid value! */
            if (p[-1] != '\'')
                return 0;  /* right substring */
            if (p[crStrlen(response)] != '\'')
                return 0;  /* left substring */
            return 1;
        }
    default:
        return 0;
    }
}
Example #3
0
/**
 * nm_setting_bond_validate_option:
 * @name: the name of the option to validate
 * @value: the value of the option to validate
 *
 * Checks whether @name is a valid bond option and @value is a valid value for
 * the @name. If @value is %NULL, the function only validates the option name.
 *
 * Returns: %TRUE, if the @value is valid for the given name.
 * If the @name is not a valid option, %FALSE will be returned.
 **/
gboolean
nm_setting_bond_validate_option (const char *name,
                                 const char *value)
{
	guint i;

	if (!name || !name[0])
		return FALSE;

	for (i = 0; i < G_N_ELEMENTS (defaults); i++) {
		if (g_strcmp0 (defaults[i].opt, name) == 0) {
			if (value == NULL)
				return TRUE;
			switch (defaults[i].opt_type) {
			case NM_BOND_OPTION_TYPE_INT:
				return validate_int (name, value, &defaults[i]);
			case NM_BOND_OPTION_TYPE_STRING:
				return validate_list (name, value, &defaults[i]);
			case NM_BOND_OPTION_TYPE_BOTH:
				return (   validate_int (name, value, &defaults[i])
				        || validate_list (name, value, &defaults[i]));
			case NM_BOND_OPTION_TYPE_IP:
				return validate_ip (name, value);
			case NM_BOND_OPTION_TYPE_MAC:
				return nm_utils_hwaddr_valid (value, ETH_ALEN);
			case NM_BOND_OPTION_TYPE_IFNAME:
				return validate_ifname (name, value);
			}
			return FALSE;
		}
	}
	return FALSE;
}
Example #4
0
bool cutFlowHandler::mask()
{
	for(TMapiP2cc::iterator ii=list->begin() ; ii!=list->end() ; ++ii)
	{
		int num    = ii->first;
		string str = (string)ii->second;
		_INFO("["+tostring(num)+"]="+str);
		
		if(str=="obj")
		{
			if(Next(ii)=="NAME")    name    = Next(ii); else {_ERROR("obj: failed to read NAME->"+PreviousStay(ii)); return false;}
			if(Next(ii)=="FLAG")    flag    = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read FLAG->"+PreviousStay(ii)); return false;}
			if(Next(ii)=="order")   order   = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read order->"+PreviousStay(ii)); return false;}
			if(Next(ii)=="phase")   phase   = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read phase->"+PreviousStay(ii)); return false;}
			if(Next(ii)=="skip")    skip    = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read skip->"+PreviousStay(ii)); return false;}
			if(Next(ii)=="nparameters") nparameters = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read nparameters->"+PreviousStay(ii)); return false;}
			_INFO("NAME="+name+", FLAG="+flag+", order="+order+", phase="+phase+", skip="+skip+", nparameters="+nparameters);

			if(Next(ii)=="parameters")
			{
				vdtmp.clear();
				for(int v=1 ; v<=validate_int(nparameters) ; ++v)
				{
					if(Next(ii)=="parameter") /* do nothing*/
					if(Next(ii)=="NAME")  attrname  = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read NAME->"+PreviousStay(ii)); return false;}
					if(Next(ii)=="ORDER") attrorder = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read ORDER->"+PreviousStay(ii)); return false;}
					if(Next(ii)=="TYPE")  attrtype  = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read TYPE->"+PreviousStay(ii)); return false;}
					val = Next(ii);
					_INFO("\tparameter["+tostring(v)+"] NAME="+attrname+", ORDER="+attrorder+", TYPE="+attrtype+", val="+val);
					// HAVE TO CHECK THE TYPE !!!!!
					vdtmp.push_back(validate_double(val));
				}
				if((int)vdtmp.size() != validate_int(nparameters)) {_ERROR("vector size doesn't match nparameters"); return false;}
			}
			else {_ERROR("obj NAME:"+name+" -> failed to read parameters->"+PreviousStay(ii)); return false;}
			
			if(Next(ii)=="description") description = Next(ii); else {_ERROR("obj NAME:"+name+" -> failed to read description->"+PreviousStay(ii)); return false;}
			_INFO("description="+description);

			m_cutFlowOrdered->insert(     make_pair(validate_double(order),name) );
			m_cutFlowTypeOrdered->insert( make_pair(validate_double(order),phase) );
			m_cutFlowNumbers->insert(     make_pair(name,0) );
			m_cutFlowMapSVD->insert(      make_pair(name,vdtmp) );
			m_cutsFlowSkipMap->insert(    make_pair(name,validate_bool(skip)) );
		}
	}
	return true;
}
Example #5
0
static int str_to_ull(const char *str, char **endptr,
		const unsigned long long int min,
		const unsigned long long int max,
		unsigned long long int *result)
{
	unsigned long long int parsed;
	int error;

	error = validate_int(str);
	if (error)
		return error;

	errno = 0;
	parsed = strtoull(str, endptr, 10);
	if (errno) {
		log_err("Parsing of '%s' threw error code %d.", str, errno);
		return errno;
	}

	if (parsed < min || max < parsed) {
		log_err("'%s' is out of bounds (%llu-%llu).", str, min, max);
		return -EINVAL;
	}

	*result = parsed;
	return 0;
}
Example #6
0
/* sampling time */
static inline int
handle_t(mmu_args_t *a,
         int val,
         const char *opt_arg)
{
    int tmp, rc;
    char *err_str = NULL;

    if (MMU_SUCCESS != (rc = validate_int(val, opt_arg, 10, &tmp, &err_str))) {
        fprintf(stderr, "%s\n", err_str);
        return rc;
    }
    a->sample_time = tmp;

    return MMU_SUCCESS;
}
Example #7
0
int get_terminal_info(int argc,char** argv,int* job_amount,int* algorithm_id) {
	int error = 0;
	if(argc == 3) {
		if(validate_int(argv[1]) == 0) {
			show_error_job_amount();
			error = 1;
		}
		else if(validate_algorithm_type(argv[2]) == 0) {
			show_error_algorithm_type();
			error = 1;
		}
		else {
			*job_amount = atoi(argv[1]);
			*algorithm_id = get_algorithm_type_id(argv[2]);
		}
	}
	else {
		show_error_command_pattern();
		error = 1;
	}
	return error;
}
Example #8
0
// Main function, the base TCP server
int main(int argc, char *argv[])
{
	//-------------------- SET UP VARIABLES -----------------------
	
	// Set up all required variables for sockets programming, starting with addrinfo "hints" struct and pointers to results list
	struct addrinfo hints, *result;

	// Integer variable used to set socket options
	int yes = 1;

	// Create command buffer, to send commands directly to the server
	char command[512] = { '\0' };

	// Define a generic indexer variable for loops
	int i = 0;

	// Set up SQLite statement struct
	sqlite3_stmt *stmt;

	// Create a buffer to store queries to process on the database
	char query[256] = { '\0' };

	//------------------ INITIALIZE SIGNAL HANDLERS ---------------

	// Install signal handlers for graceful shutdown
	// Install SIGHUP signal handler
	signal(SIGHUP, shutdown_handler);

	// Install SIGINT signal handler
	signal(SIGINT, shutdown_handler);

	// Install SIGTERM signal handler
	signal(SIGTERM, shutdown_handler);

	// Install signal handlers for statistics output
	// Install SIGUSR1 signal handler
	signal(SIGUSR1, stat_handler);

	// Install SIGUSR2 signal handler
	signal(SIGUSR2, stat_handler);

	//------------------ BEGIN SERVER INITIALIZATION --------------

	// Read in terminal on which server was started
	term = strdup(ttyname(1));

	// Print initialization message
	fprintf(stdout, "%s: %s %s - Justin Hill, Gordon Keesler, Matt Layher (CS5550 Spring 2012)\n", SERVER_NAME, INFO_MSG, SERVER_NAME);

	// Capture initial start time
	start_time = time(NULL);

	//------------------ PARSE COMMAND LINE ARGUMENTS -------------

	// Iterate through all argv command line arguments, parsing out necessary flags
	for(i = 1; i < argc; i++)
	{
		// '-d' or '--daemon' flag: daemonize the server, and run it in the background
		if(strcmp("-d", argv[i]) == 0 || strcmp("--daemon", argv[i]) == 0)
		{
			// Set daemon flag to true, so we may daemonize later
			daemonized = 1;
		}
		// '-h' or '--help' flag: print help and usage for this server, then exit
		else if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0)
		{
			// Print usage message
			fprintf(stdout, "usage: %s [-d | --daemon] [-h | --help] [-l | --lock lock_file] [-p | --port port] [-q | --queue queue_length] [-t | --threads thread_count]\n\n", SERVER_NAME);

			// Print out all available flags
			fprintf(stdout, "%s flags:\n", SERVER_NAME);
			fprintf(stdout, "\t-d | --daemon:     daemonize - start server as a daemon, running it in the background\n");
			fprintf(stdout, "\t-h | --help:            help - print usage information and details about each flag the server accepts\n");
			fprintf(stdout, "\t-l | --lock:       lock_file - specify the location of the lock file utilized when the server is daemonized (default: %s)\n", LOCKFILE);
			fprintf(stdout, "\t-p | --port:            port - specify an alternative port number to run the server (default: %s)\n", DEFAULT_PORT);
			fprintf(stdout, "\t-q | --queue:   queue_length - specify the connection queue length for the incoming socket (default: %d)\n", QUEUE_LENGTH);
			fprintf(stdout, "\t-t | --threads: thread_count - specify the number of threads to generate (max number of clients) (default: %d)\n", NUM_THREADS);
			fprintf(stdout, "\n");

			// Print out all available console commands via the common console_help() function
			console_help();

			// Exit the server
			exit(0);
		}
		// '-l' or '--lock' flag: specify an alternate lock file location
		else if(strcmp("-l", argv[i]) == 0 || strcmp("--lock", argv[i]) == 0)
		{
			// Make sure that another argument exists, specifying the lockfile location
			if(argv[i+1] != NULL)
			{
				// Set lock file location as specified on the command line
				lock_location = argv[i+1];
				i++;
			}
			else
			{
				// Print error and use default location if no lockfile was specified after the flag
				fprintf(stderr, "%s: %s no lockfile location specified, defaulting to %s\n", SERVER_NAME, ERROR_MSG, LOCKFILE);
			}
		}
		// '-p' or '--port' flag: specifies an alternative port number to run the server
		else if(strcmp("-p", argv[i]) == 0 || strcmp("--port", argv[i]) == 0)
		{
			// Make sure that another argument exists, specifying the port number
			if(argv[i+1] != NULL)
			{
				// Ensure this port is a valid integer
				if(validate_int(argv[i+1]))
				{
					// Set this port to be used if it's within the valid range, else use the default
					if(atoi(argv[i+1]) >= 0 && atoi(argv[i+1]) <= MAX_PORT)
					{
						port = argv[i+1];
						i++;
					}
					else
						fprintf(stderr, "%s: %s port lies outside valid range (0-%d), defaulting to %s\n", SERVER_NAME, ERROR_MSG, MAX_PORT, DEFAULT_PORT);
				}
				else
				{
					// Print error and use default port if an invalid port number was specified
					fprintf(stderr, "%s: %s invalid port number specified, defaulting to %s\n", SERVER_NAME, ERROR_MSG, DEFAULT_PORT);
				}
			}
			else
			{
				// Print error and use default port if no port number was specified after the flag
				fprintf(stderr, "%s: %s no port number specified after flag, defaulting to %s\n", SERVER_NAME, ERROR_MSG, DEFAULT_PORT);
			}
		}
		// '-q' or '--queue' flag: specify the connection queue length
		else if(strcmp("-q", argv[i]) == 0 || strcmp("--queue", argv[i]) == 0)
		{
			// Make sure another argument exists, specifying the queue length
			if(argv[i+1] != NULL)	
			{
				// Ensure this is a valid integer for queue length
				if(validate_int(argv[i+1]))
				{
					// Set connection queue length to the number specified on the command line, if it's a number more than 0, else use the default
					if(atoi(argv[i+1]) >= 1)
					{
						queue_length = atoi(argv[i+1]);
						i++;
					}
					else
						fprintf(stderr, "%s: %s cannot use negative or zero queue length, defaulting to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH);
				}
				else
				{
					// Print error and use default queue length if an invalid number was specified
					fprintf(stderr, "%s: %s invalid queue length specified, defaulting to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH);
				}
			}
			else
			{
				// Print error and use default queue length if no length was specified after the flag
				fprintf(stderr, "%s: %s no queue length specified after flag, default to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH);
			}
		}
		// '-t' or '--threads' flag: specify the number of threads to generate in the thread pool
		else if(strcmp("-t", argv[i]) == 0 || strcmp("--threads", argv[i]) == 0)
		{
			// Make sure next argument exists, specifying the number of threads
			if(argv[i+1] != NULL)
			{
				// Ensure this number is a valid integer
				if(validate_int(argv[i+1]))
				{
					// Set number of threads to the number specified on the command line, if it's a number more than 0, else use the default
					if(atoi(argv[i+1]) >= 1)
					{
						num_threads = atoi(argv[i+1]);
						i++;
					}
					else
						fprintf(stderr, "%s: %s cannot use negative or zero threads, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS);
				}
				else
				{
					// Print error and use default number of threads if an invalid number was specified
					fprintf(stderr, "%s: %s invalid number of threads specified, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS);
				}
			}
			else
			{
				// Print error and use default number of threads if no count was specified after the flag
				fprintf(stderr, "%s: %s no thread count specified after flag, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS);
			}
		}
		else
		{
			// Else, an invalid flag or parameter was specified; print an error and exit
			fprintf(stderr, "%s: %s unknown parameter '%s' specified, please run '%s -h' for help and usage\n", SERVER_NAME, ERROR_MSG, argv[i], SERVER_NAME);
			exit(-1);
		}
	}

	//------------------------ OPEN SQLITE DATABASE ----------------

	// Open database file, as specified in config header; check for success
	sqlite3_open(DB_FILE, &db);
	if(db == NULL)
	{
		// Print an error message and quit if database fails to open
		fprintf(stderr, "%s: %s sqlite: could not open database %s\n", SERVER_NAME, ERROR_MSG, DB_FILE);
		exit(-1);
	}

	// Create a query to truncate the files table in the database
	sprintf(query, "DELETE FROM files");

	// Prepare, evaluate, and finalize SQLite query
	sqlite3_prepare_v2(db, query, strlen(query) + 1, &stmt, NULL);
	if(sqlite3_step(stmt) != SQLITE_DONE)
	{
		// On query failure, print an error and exit
		fprintf(stderr, "%s: %s sqlite: could not truncate files table\n", SERVER_NAME, ERROR_MSG);
		exit(-1);
	}
	sqlite3_finalize(stmt);

	//------------------------ INITIALIZE TCP SERVER ---------------

	// Clear the hints struct using memset to nullify it
	memset(&hints, 0, sizeof(hints));

	// Set options for hints to use IPv4, a TCP connection, and the machine's current IP address
	hints.ai_family = AF_INET;          // IPv4
	hints.ai_socktype = SOCK_STREAM;    // Reliable TCP connection
	hints.ai_flags = AI_PASSIVE;        // Use my ip address

	// now populate our result addrinfo
	if((getaddrinfo(NULL, port, &hints, &result)) != 0)
	{ 
		// If getaddrinfo() fails, print an error and quit the program, since setup cannot continue.
		fprintf(stderr, "%s: %s getaddrinfo() call failed\n", SERVER_NAME, ERROR_MSG);
		exit(-1);
	}

	// Attempt to instantiate the local socket, using values set by getaddrinfo()
	if((loc_fd = socket(result->ai_family, result->ai_socktype, result->ai_protocol)) == -1)
	{
		// On socket creation failure, print an error and exit
		fprintf(stderr, "%s: %s local socket creation failed\n", SERVER_NAME, ERROR_MSG);
		exit(-1);
	}

	// Allow the system to free and re-bind the socket if it is already in use
	if(setsockopt(loc_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
	{
		// If setting a socket option fails, terminate the program after printing an error
		fprintf(stderr, "%s: %s failed to set socket option: SO_REUSEADDR\n", SERVER_NAME, ERROR_MSG);
		exit(-1);
	}

	// Attempt to bind the local socket
	if((bind(loc_fd, result->ai_addr, result->ai_addrlen)) == -1)
	{
		// If socket binding fails, it's typically one of two scenarios:
		// 1) Check if socket is on a privileged port, and permission is denied
		if(atoi(port) < PRIVILEGED_PORT)
			fprintf(stderr, "%s: %s failed to bind local socket (permission denied?)\n", SERVER_NAME, ERROR_MSG);
		// 2) Else, the socket is probably already bound
		else
			fprintf(stderr, "%s: %s failed to bind local socket (socket already in use?)\n", SERVER_NAME, ERROR_MSG);

		// Exit on failure
		exit(-1);
	}
	
	// Free the results struct, as it is no longer needed
	freeaddrinfo(result);

	// Begin listening on the local socket, and set connection queue length as defined above
	if((listen(loc_fd, queue_length)) == -1)
	{
		// Print error message if socket fails to begin listening
		fprintf(stderr, "%s: %s failed to begin listening on local socket\n", SERVER_NAME, ERROR_MSG);
	}
    
	//-------------------------- DAEMONIZATION ------------------

	// If server is being daemonized, do so now.
	if(daemonized == 1)
		daemonize();
	else
	{	
		// Initialize a thread pool, using number of threads as defined earlier
		threadpool = thpool_init(num_threads);

		// Initialize the network thread to handle all incoming connections
		pthread_create(&net_thread, NULL, &tcp_listen, NULL);
	
		// Print out server information and ready message
		fprintf(stdout, "%s: %s server initialized [PID: %d] [port: %s] [queue: %d] [threads: %d]\n", SERVER_NAME, OK_MSG, getpid(), port, queue_length, num_threads);

		// If server is not being daemonized, use the default console interface
		fprintf(stdout, "%s: %s type 'stop' or hit Ctrl+C (SIGINT) to stop server\n", SERVER_NAME, INFO_MSG);
	}

	//------------------------- CONSOLE COMMAND ---------------

	// Loop continuously until 'stop' is provided on the console
	while(1)
	{
		// Read in user input, clean it up
		fgets(command, sizeof(command), stdin);
		clean_string((char *)&command);

		// 'clear' - Clear the console
		if(strcmp(command, "clear") == 0)
			system("clear");
		// 'help' - Display the common console help menu
		else if(strcmp(command, "help") == 0)
			console_help();
		// 'stat' - Print out server statistics
		else if(strcmp(command, "stat") == 0)
			print_stats();
		// 'stop' - Stop the server, breaking this loop
		else if(strcmp(command, "stop") == 0)
			break;
		// Else, print console error stating command does not exist
		else
			fprintf(stderr, "%s: %s unknown console command '%s', type 'help' for console command help\n", SERVER_NAME, ERROR_MSG, command);
	}

	// Send SIGINT to the server so that it will gracefully terminate via signal handler
	kill(getpid(), SIGINT);
}