Ejemplo n.º 1
0
void configuration::sanity_check_values()
{
	if(conf[DTLS_BIND_PORT] == 0 || conf[DTLS_OUTGOING_PORT] == 0) {
		// use random but persistent ports for these
		std::ofstream conffile(conf[CONFIG_FILE], std::ios_base::out | std::ios_base::binary | std::ios_base::app);
		if(conf[DTLS_BIND_PORT] == 0) {
			uint16_t port = ntohs(get_random_port());
			iout() << "Assigned DTLS_BIND_PORT random port " << port;
			conffile << "\nDTLS_BIND_PORT=" << port << '\n';
			assign_value(DTLS_BIND_PORT, port);
		}
		if(conf[DTLS_OUTGOING_PORT] == 0) {
			uint16_t port = ntohs(get_random_port());
			iout() << "Assigned DTLS_OUTGOING_PORT random port " << port;
			conffile << "\nDTLS_OUTGOING_PORT=" << port << '\n';
			assign_value(DTLS_OUTGOING_PORT, port);
		}
	}
	if(conf[DTLS_BIND_PORT] == conf[DTLS_OUTGOING_PORT] || conf[DTLS_BIND6_PORT] == conf[DTLS_OUTGOING_PORT]) {
		eout() << "DTLS_BIND_PORT or DTLS_OUTGOING_PORT not initialized to separate valid ports, these should have been set to random ports during installation."
			<< " You must set DTLS_BIND_PORT and DTLS_OUTGOING_PORT to separate port numbers in the snow configuration file."
			   << " If you have more than one device try to choose different ports for each device.";
		abort();
	}
	check_port(conf[DTLS_OUTGOING_PORT], "DTLS_OUTGOING_PORT");
	check_port(conf[DTLS_BIND_PORT], "DTLS_BIND_PORT");
	check_port(conf[DTLS_BIND6_PORT], "DTLS_BIND6_PORT");
	check_port(conf[DHT_PORT], "DHT_PORT");
	check_port(conf[NAMESERV_PORT], "NAMESERV_PORT");
	check_nonzero(conf[NAMESERV_TIMEOUT_SECS], "NAMESERV_TIMEOUT_SECS");
	check_nonzero(conf[DTLS_IDLE_TIMEOUT_SECS], "DTLS_IDLE_TIMEOUT_SECS");
	check_nonzero(conf[HEARTBEAT_SECONDS], "HEARTBEAT_SECONDS");
	check_nonzero(conf[HEARTBEAT_RETRIES], "HEARTBEAT_RETRIES");
	if(conf[NAT_IP_GRACE_PERIOD_SECONDS] < 1800) {
		wout() << "NAT IP grace period of " << conf[NAT_IP_GRACE_PERIOD_SECONDS] << " from configuration file is too short, using minimum grace period of 1800 seconds";
		assign_value(NAT_IP_GRACE_PERIOD_SECONDS, 1800);
	}
	if(conf[DHT_BOOTSTRAP_TARGET]==0) {
		wout() << "DHT_BOOTSTRAP_TARGET cannot be zero, using default value";
		assign_value(DHT_BOOTSTRAP_TARGET, 6);
	}
	if(conf[DHT_MAX_PEERS] <= 3) {
		wout() << "DHT_MAX_PEERS cannot be " << conf[DHT_MAX_PEERS] << ", must be at least 4, using default value of 99";
		assign_value(DHT_MAX_PEERS, 99);
	}
	if(conf[NATPOOL_NETMASK_BITS] > 20 || conf[NATPOOL_NETMASK_BITS] < 4) {
		eout() << "NATPOOL_NETMASK_BITS must be between 4 and 20";
		abort();
	}
	uint32_t addr, netmask = ~htonl((1 << (32 - conf[NATPOOL_NETMASK_BITS])) - 1);
	if(inet_pton(AF_INET, conf[NATPOOL_NETWORK].c_str(), &addr) != 1 || (addr & ~netmask) != 0) {
		eout() << "NATPOOL_NETWORK/NATPOOL_NETMASK_BITS as " << conf[NATPOOL_NETWORK] << "/" << conf[NATPOOL_NETMASK_BITS] << " is not a valid subnet.";
		abort();
	}
	if(conf[VIRTUAL_INTERFACE_MTU] > 65535 || conf[VIRTUAL_INTERFACE_MTU] < 576) {
		eout() << "VIRTUAL_INTERFACE_MTU cannot be " << conf[VIRTUAL_INTERFACE_MTU];
		abort();
	}
}
Ejemplo n.º 2
0
/*-------------------------------------------------------------------------------------*/
Socket tcp_passive_open(int port) 
/*-------------------------------------------------------------------------------------*/
{
  // parameter check                                                                                         
  check_port("tcp_open_server() failed", port);

  MySocket *s = (MySocket *)malloc( sizeof(MySocket) );
  if ( s == NULL ) 
    die("tcp_open__socket() failed: mem alloc error");

  struct sockaddr_in addr;

  s->sd = socket(PROTOCOLFAMILY, TYPE, PROTOCOL);
  check_sd("tcp_open_server failed(): socket creation error", s->sd);

  /* Construct the server address structure */
  memset(&addr, 0, sizeof(struct sockaddr_in));
  addr.sin_family = PROTOCOLFAMILY;
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  addr.sin_port = htons(port);

  if ( bind(s->sd, (struct sockaddr *)&addr, sizeof(addr)) != 0 ) {
    die("tcp_open_server failed(): bind() failed");  //will fail if e.g; port is in use
  }

  if( listen(s->sd, MAX_PENDING) != 0 )
	die("tcp_open_server failed(): listen() failed");

  s->port = port;
  s->ip_addr = NULL;  //INADDR_ANY ...	

  return (Socket)s;  
}
Ejemplo n.º 3
0
std::shared_ptr<HttpEndPointServer>
HttpEndPointServer::getHttpEndPointServer (const uint port,
    const std::string &iface, const std::string &addr)
{
  std::unique_lock <std::recursive_mutex> lock (mutex);
  uint finalPort = port;


  if (instance) {
    return instance;
  }

  if (finalPort == 0) {
    GST_INFO ("HttpService will start on any available port");
  } else {
    try {
      check_port (finalPort);
    } catch (std::exception &ex) {
      GST_WARNING ("Setting default port %d to http end point server",
                   DEFAULT_PORT);
      finalPort = DEFAULT_PORT;
    }
  }

  HttpEndPointServer::port = finalPort;
  HttpEndPointServer::interface = iface;
  HttpEndPointServer::announcedAddr = addr;

  instance = std::shared_ptr<HttpEndPointServer> (new HttpEndPointServer () );
  instance->start();

  return instance;
}
RabbitMQService::RabbitMQService (Glib::KeyFile &confFile) : Service (confFile)
{
  sigset_t mask;
  std::string address;
  int port;

  try {
    address = confFile.get_string (RABBITMQ_GROUP, RABBITMQ_SERVER_ADDRESS);
  } catch (const Glib::KeyFileError &err) {
    GST_WARNING ("Setting default address %s to media server",
                 RABBITMQ_SERVER_ADDRESS_DEFAULT);
    address = RABBITMQ_SERVER_ADDRESS_DEFAULT;
  }

  try {
    port = confFile.get_integer (RABBITMQ_GROUP, RABBITMQ_SERVER_PORT);
    check_port (port);
  } catch (const Glib::KeyFileError &err) {
    GST_WARNING ("Setting default port %d to media server",
                 RABBITMQ_SERVER_PORT_DEFAULT);
    port = RABBITMQ_SERVER_PORT_DEFAULT;
  }

  this->address = address;
  this->port = port;

  setConfig (address, port);
  this->confFile.load_from_data (confFile.to_data() );

  sigemptyset (&mask);
  sigaddset (&mask, SIGCHLD);
  signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask,
                  std::bind (&RabbitMQService::childSignal, this, std::placeholders::_1) ) );
}
Ejemplo n.º 5
0
/*
 * This test checks if a port is created correctly for a new process.
 */
void test_ipc_1()
{
    test_reset();

    PORT new_port;
    new_port = create_process (test_ipc_1_process, 5, 0, "Receiver");
    kprintf("A new process with a port is created.");

    check_port(new_port, "Receiver", TRUE);
    if (test_result != 0)
       test_failed(test_result);
}
Ejemplo n.º 6
0
/*-------------------------------------------------------------------------------------*/
int get_port( Socket socket ) 

/*-------------------------------------------------------------------------------------*/
{
  // parameter check
  check_socket_ptr("get_port() failed", socket);
    
  MySocket *s = (MySocket *)socket;
  
  check_port("get_port() failed", s->port);

  return s->port;
}
Ejemplo n.º 7
0
int						main(int ac, const char **av)
{
	if (ac != 2 || !check_port(av[1]))
	{
		print_usage();
		return (EXIT_FAILURE);
	}
	init_server(av[1]);
	while (42)
	{
		ft_putendl("Server is now waiting...");
		accept_connection();
	}
	return (0);
}
Ejemplo n.º 8
0
int			connect_serv(char *port)
{
  t_serv		serv;

  time(&start);
  signal(SIGINT, disconnect);
  create_depot();
  serv.port = atoi(port);
  serv.proto = getprotobyname(TCP);
  if (check_port(serv.port) == EXIT_FAILURE)
    return (EXIT_FAILURE);
  if (init_serveur(&serv) == EXIT_FAILURE)
    return (EXIT_FAILURE);
  run_serveur(&serv);
  return (EXIT_SUCCESS);
}
Ejemplo n.º 9
0
/*-------------------------------------------------------------------------------------*/
Socket tcp_active_open( int remote_port, char *remote_ip ) 
/*-------------------------------------------------------------------------------------*/
{
  // parameter check                                                                                         
  check_port("tcp_open_client() failed", remote_port);
  check_ip_addr("tcp_open_client() failed", remote_ip);
    
  MySocket *client = (MySocket *)malloc( sizeof(MySocket) );
  if ( client == NULL ) 
    die("tcp_open_client() failed: mem alloc error");

  struct sockaddr_in addr;
  int length;
  char *p;

  client->sd = socket(PROTOCOLFAMILY, TYPE, PROTOCOL);
  check_sd("tcp_open_client() failed: socket creation error", client->sd);
    
  /* Construct the server address structure */
  memset(&addr, 0, sizeof(struct sockaddr_in));
  addr.sin_family = PROTOCOLFAMILY;
  if ( inet_aton(remote_ip, (struct in_addr *) &addr.sin_addr.s_addr) == 0 ) 
    die("tcp_open_client failed(): invalid ip address");

  addr.sin_port = htons(remote_port);

  if ( connect(client->sd, (struct sockaddr *) &addr, sizeof(addr) ) < 0 )
    die("tcp_open_client failed(): connect () failed");

  memset(&addr, 0, sizeof(struct sockaddr_in));
  length = sizeof(addr);
  if ( getsockname(client->sd, (struct sockaddr *)&addr, (socklen_t *)&length) != 0 )
    die("tcp_open_client failed(): getsockname() failed");
  
  p = inet_ntoa(addr.sin_addr);  //returns addr to statically allocated buffer
  
  client->ip_addr = (char *)malloc( sizeof(char)*CHAR_IP_ADDR_LENGTH);
  if ( client->ip_addr == NULL )
 	die("tcp_open_client failed(): mem alloc error");
  client->ip_addr = strcpy( client->ip_addr, p );
  client->port = ntohs(addr.sin_port);

  return (Socket)client;
}
Ejemplo n.º 10
0
void check(void)
{
  int exit=FALSE;
  RESULT svar;
  do
  {
    svar=form_dialog();
    switch(svar.type)
    {
      case MENU_CLICKED:
        exit=!handle_menu(svar);
        break;
      case DIALOG_CLICKED:
      case WINDOW_CLICKED:
        exit=!handle_window(svar);
        break;
      case KEY_CLICKED:
        exit=!handle_key(svar);
        break;
      case BUTTON_CLICKED:
        exit=!handle_button(svar);
        break;
      case TIMER_EXIT:
        check_port();
        break;
      default:
        switch(svar.data[0])
        {
          char temp[MAXSTRING];
          case 0x400:                        /* ACC_ID           */
          case 0x4700:                       /* AV_PROTOKOLL     */
          case 0x4724:                       /* VA_ACCWINDOPEN   */
          case 0x4726:                       /* AV_ACCWINDCLOSED */
            break;
          default:
            sprintf(temp,"[1][ Message %#lx|From %d|%d,%d,%d,%d,%d][ NEXT ]",svar.data[0],svar.data[1],
              (unsigned short)svar.data[3],(unsigned short)svar.data[4],(unsigned short)svar.data[5],(unsigned short)svar.data[6],(unsigned short)svar.data[7]);
            alertbox(1,temp);
            break;
        }
    }
  }while(!exit);
}
Ejemplo n.º 11
0
/* let's go... */
int main(int argc, char *argv[])
{
    int c = 0;
    ctrl_t *ctrl = NULL;


    /* banner is very important */
    banner();
    check_argc(argc);
    ctrl = alloc_structs();
    ctrl = set_ctrl_defaults(ctrl);

    while ((c = getopt(argc, argv, "h:t:s:m:p:vVH")) != -1) {
        switch (c) {
        case 'h':
            check_host(optarg);
            ctrl->packet->host = convert_host(optarg);
            break;
        case 't':
            check_pkt_type(ctrl, optarg);
            ctrl->packet->type = (unsigned char) ATOI(optarg);
            break;
        case 's':
            check_shell_mode(ctrl, optarg);
            ctrl->shell->mode = (unsigned char) ATOI(optarg);
            break;
        case 'm':
            ctrl->packet->payload = optarg;
            break;
        case 'p':
            check_port(ctrl, ATOI(optarg));
            ctrl->packet->port = (uint16_t) ATOI(optarg);
            break;
        case 'v':
            ctrl->verbose = VERBOSE;
            break;
        case 'V':
            puts(VERSION);
            __EXIT_SUCCESS;
            break;
        case 'H':
            usage();
            __EXIT_SUCCESS;
            break;
        default:
            __EXIT_FAILURE;
        }
    }

    /* few checks before we can go on */
    __VERBOSE_ARGS;
    check_args(ctrl);
    check_uid(ctrl);

    /* install signal handler */
    install_signals();

    /* let's go */
    start_trixd00r(ctrl);
    end_trixd00r(ctrl);

    return 0;
}
Ejemplo n.º 12
0
int afp_parse_url(struct afp_url * url, const char * toparse, int verbose)
{
	char firstpart[255],secondpart[2048];
	char *p, *q;
	int firstpartlen;
	int skip_earliestpart=0;
	int skip_secondpart=0;
	char * lastchar;
	int foundv6literal=0;

	if (verbose) printf("Parsing %s\n",toparse);

	url->username[0]='\0';
	url->servername[0]='\0';
	url->uamname[0]='\0';
	url->password[0]='\0';
	url->volumename[0]='\0';
	url->path[0]='\0';

	/* The most complex URL is:
 
	afp://user;AUTH=authType:password@server-name:port/volume-name/path 

	where the optional parms are user, password, AUTH and port, so the
	simplest is:

	afp://server-name/volume-name/path 

	*/

	/* if there is a ://, make sure it is preceeded by afp */

	if ((p=strstr(toparse,"://"))!=NULL) {
		q=p-3;
		if (p<toparse) {
			if (verbose) printf("URL does not start with afp://\n");
			return -1;
		}

		if (strncmp(q,"afp",3)!=0) {
			if (verbose) printf("URL does not start with afp://\n");
			return -1;
		}
		p+=3;
	} else {
		if (verbose) printf("This isn't a URL at all.\n");
		return -1;

	}
	if (p==NULL) p=(char *)toparse;

	/* Now split on the first / */
	if (sscanf(p,"%[^/]/%[^$]",

		firstpart, secondpart)!=2) {
		/* Okay, so there's no volume. */
		skip_secondpart=1;
	}

	firstpartlen=strlen(firstpart);

	lastchar=firstpart+firstpartlen-1;

	/* First part could be something like:
		user;AUTH=authType:password

	   We'll assume that the breakout is:
                user;  optional user name
	        AUTH=authtype:
	*/

	/* Let's see if there's a ';'.  q is the end of the username */

	if ((p=escape_strchr(firstpart,'@',"@"))) {
		*p='\0';
		p++; 
	} else {
		skip_earliestpart=1;
		p=firstpart;
	}
	/* p now points to the start of the server name*/

	/* square brackets denote a literal ipv6 address */
	if (*p == '[' && 
		(q=strchr(p,']'))) {
		foundv6literal = 1;
		p++;
		*q = '\0';
		q++;
	}

	/* see if we have a port number */

	if ((foundv6literal && (q=strchr(q,':'))) ||
			(!foundv6literal && (q=strchr(p,':'))) ) {
		*q='\0';
		q++;
		if (check_port(q)) return -1;
		if ((url->port=atoi(q))==0) {
			if (verbose) printf("Port appears to be zero\n");
			return -1;
		}
	}

	snprintf(url->servername,strlen(p)+1,"%s", p);
	if (check_servername(url->servername)) {
			if (verbose) printf("This isn't a valid servername\n");
			return -1;
	}

	if ((p==NULL) || ((strlen(p)+p-1)==lastchar)) {
		/* afp://server */
	}

	if ((q) && ((strlen(q)+q-1)==lastchar)) {
		/* afp://server:port */
	}


	/* Earliest part */

	if (skip_earliestpart) {
		p+=strlen(p);
		goto parse_secondpart;
	}
	p=firstpart;

	/* Now we're left with something like user[;AUTH=uamname][:password] */

	/* Look for :password */

	if ((q=escape_strrchr(p,':',":"))) {
		*q='\0';
		q++;
		snprintf(url->password,strlen(q)+1, "%s", q);
		if (check_password(url->password)) {
			if (verbose) printf("This isn't a valid passwd\n");
			return -1;
		}
	}

	/* Now we're down to user[;AUTH=uamname] */
	p=firstpart;

	if ((q=strstr(p,";AUTH="))) {
		*q='\0';
		q+=6;
		snprintf(url->uamname,strlen(q)+1,"%s", q);
		if (check_uamname(url->uamname)) {
			if (verbose) printf("This isn't a valid uamname\n");
			return -1;
		}
	}

	if (strlen(p)>0) {
		snprintf(url->username,strlen(p)+1,"%s", p);
		if (check_username(url->username)) {
			if (verbose) printf("This isn't a valid username\n");
			return -1;
		}
	}


parse_secondpart:
	if (skip_secondpart) goto done;
	if (strlen(secondpart)==0) goto done;

	if (secondpart[strlen(secondpart)]=='/') 
		secondpart[strlen(secondpart)]='\0';

	p=secondpart;
	if ((q=strchr(p,'/'))) {
		*q='\0';
		q++;
	}
	snprintf(url->volumename,strlen(p)+1,"%s", p);


	if (q) {
		url->path[0]='/';
		snprintf(url->path+1,strlen(q)+1, "%s", q);
	}

done:
	escape_url(url);
	if (verbose) printf("Successful parsing of URL\n");
	return 0;
}
Ejemplo n.º 13
0
static bool finalize_join(void) {
	char *name = xstrdup(get_value(data, "Name"));
	if(!name) {
		fprintf(stderr, "No Name found in invitation!\n");
		return false;
	}

	if(!check_id(name)) {
		fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
		return false;
	}

	if(!netname)
		netname = grep(data, "NetName");

	bool ask_netname = false;
	char temp_netname[32];

make_names:
	if(!confbasegiven) {
		free(confbase);
		confbase = NULL;
	}

	make_names(false);

	free(tinc_conf);
	free(hosts_dir);

	xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
	xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);

	if(!access(tinc_conf, F_OK)) {
		fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
		if(confbasegiven)
			return false;

		// Generate a random netname, ask for a better one later.
		ask_netname = true;
		snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
		netname = temp_netname;
		goto make_names;
	}	

	if(mkdir(confbase, 0777) && errno != EEXIST) {
		fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
		return false;
	}

	if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
		fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
		return false;
	}

	FILE *f = fopen(tinc_conf, "w");
	if(!f) {
		fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
		return false;
	}

	fprintf(f, "Name = %s\n", name);

	char filename[PATH_MAX];
	snprintf(filename, sizeof filename, "%s" SLASH "%s", hosts_dir, name);
	FILE *fh = fopen(filename, "w");
	if(!fh) {
		fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
		fclose(f);
		return false;
	}

	// Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
	// Other chunks go unfiltered to their respective host config files
	const char *p = data;
	char *l, *value;

	while((l = get_line(&p))) {
		// Ignore comments
		if(*l == '#')
			continue;

		// Split line into variable and value
		int len = strcspn(l, "\t =");
		value = l + len;
		value += strspn(value, "\t ");
		if(*value == '=') {
			value++;
			value += strspn(value, "\t ");
		}
		l[len] = 0;

		// Is it a Name?
		if(!strcasecmp(l, "Name"))
			if(strcmp(value, name))
				break;
			else
				continue;
		else if(!strcasecmp(l, "NetName"))
			continue;

		// Check the list of known variables
		bool found = false;
		int i;
		for(i = 0; variables[i].name; i++) {
			if(strcasecmp(l, variables[i].name))
				continue;
			found = true;
			break;
		}

		// Ignore unknown and unsafe variables
		if(!found) {
			fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
			continue;
		} else if(!(variables[i].type & VAR_SAFE)) {
			fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
			continue;
		}

		// Copy the safe variable to the right config file
		fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
	}

	fclose(f);

	while(l && !strcasecmp(l, "Name")) {
		if(!check_id(value)) {
			fprintf(stderr, "Invalid Name found in invitation.\n");
			return false;
		}

		if(!strcmp(value, name)) {
			fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
			return false;
		}

		snprintf(filename, sizeof filename, "%s" SLASH "%s", hosts_dir, value);
		f = fopen(filename, "w");

		if(!f) {
			fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
			return false;
		}

		while((l = get_line(&p))) {
			if(!strcmp(l, "#---------------------------------------------------------------#"))
				continue;
			int len = strcspn(l, "\t =");
			if(len == 4 && !strncasecmp(l, "Name", 4)) {
				value = l + len;
				value += strspn(value, "\t ");
				if(*value == '=') {
					value++;
					value += strspn(value, "\t ");
				}
				l[len] = 0;
				break;
			}

			fputs(l, f);
			fputc('\n', f);
		}

		fclose(f);
	}

	// Generate our key and send a copy to the server
	ecdsa_t *key = ecdsa_generate();
	if(!key)
		return false;

	char *b64key = ecdsa_get_base64_public_key(key);
	if(!b64key)
		return false;

	snprintf(filename, sizeof filename, "%s" SLASH "ed25519_key.priv", confbase);
	f = fopenmask(filename, "w", 0600);
	if(!f)
		return false;

	if(!ecdsa_write_pem_private_key(key, f)) {
		fprintf(stderr, "Error writing private key!\n");
		ecdsa_free(key);
		fclose(f);
		return false;
	}

	fclose(f);

	fprintf(fh, "Ed25519PublicKey = %s\n", b64key);

	sptps_send_record(&sptps, 1, b64key, strlen(b64key));
	free(b64key);
	ecdsa_free(key);

	check_port(name);

ask_netname:
	if(ask_netname && tty) {
		fprintf(stderr, "Enter a new netname: ");
		if(!fgets(line, sizeof line, stdin)) {
			fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
			return false;
		}
		if(!*line || *line == '\n')
			goto ask_netname;

		line[strlen(line) - 1] = 0;

		char newbase[PATH_MAX];
		snprintf(newbase, sizeof newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
		if(rename(confbase, newbase)) {
			fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
			goto ask_netname;
		}

		netname = line;
		make_names(false);
	}

	fprintf(stderr, "Configuration stored in: %s\n", confbase);

	return true;
}
Ejemplo n.º 14
0
void port_checker::do_checks(char* loc, int loc_size, bool check_defaults)
{
    char* old_loc = loc + strlen(loc);
//  std::cout << "Checking Ports: \"" << loc << "\"..." << std::endl;


    rtosc_arg_val_t query_args[2];
    query_args[0].type = query_args[1].type = 's';
    query_args[0].val.s = loc;
    query_args[1].val.s = "";
    send_msg("/path-search", 2, query_args);
    std::vector<rtosc_arg_val_t> args;
    std::vector<char> strbuf;

    int res = sender.wait_for_reply(&strbuf, &args, "/paths");
    if(!res)
        throw std::runtime_error("no reply from path-search");
    if(args.size() % 2)
        throw std::runtime_error("bad reply from path-search");

    bool self_disabled = false; // disabled by an rSelf() ?
    size_t port_max = args.size() >> 1;
    // std::cout << "found " << port_max << " subports" << std::endl;
    for(size_t port_no = 0; port_no < port_max; ++port_no)
    {
        if(args[port_no << 1].type != 's' ||
                args[(port_no << 1) + 1].type != 'b')
            throw std::runtime_error("Invalid \"paths\" reply: bad types");

        if(!strncmp(args[port_no << 1].val.s, "self:", 5)) {
            rtosc_blob_t& blob = args[(port_no << 1) + 1].val.b;
            const char* metadata = (const char*)blob.data;
            if(!port_is_enabled(loc, args[port_no << 1].val.s, metadata))
                self_disabled = true;
        }
    }
    if(self_disabled)
        m_skipped.insert("/" + std::string(loc));
    else
        ++ports_checked;

    std::map<std::string, unsigned> port_count;

    if(!self_disabled)
    for(size_t port_no = 0; port_no < port_max; ++port_no)
    {
        const char* portname = args[port_no << 1].val.s;
        int portlen = strlen(portname);
        rtosc_blob_t& blob = args[(port_no << 1) + 1].val.b;
        const char* metadata = (const char*)blob.data;
        int32_t meta_len = blob.len;
        if(!metadata)
            metadata = "";
        bool has_subports = portname[portlen-1] == '/';
/*      std::cout << "port /" << loc << portname
                  << " (" << port_no << "/" << port_max
                  << "), has subports: " << std::boolalpha << has_subports
                  << std::endl;*/

        if(port_is_enabled(loc, portname, metadata))
        {
            Port::MetaContainer meta(metadata);

            if(meta.find("parameter") != meta.end())
            {
                std::string portname_noargs = portname;
                portname_noargs.resize(portname_noargs.find(':'));
                ++port_count[portname_noargs];
            }

            if(has_subports)
            {
                // statistics: port may still be disabled, see above
                if(loc_size > portlen)
                {
                    strcpy(old_loc, portname);
                    char* hashsign = strchr(old_loc, '#');
                    if(hashsign)
                    {
                        // #16\0 => 0\0
                        *hashsign = '0';
                        *++hashsign = '/';
                        *++hashsign = 0;
                    }

                    bool next_check_defaults =
                       (meta.find("no defaults") == meta.end());

                    do_checks(loc, loc_size - portlen, next_check_defaults);
                }
                else
                    throw std::runtime_error("portname too long");
            }
            else {
                ++ports_checked;
                check_port(loc, portname, metadata, meta_len, check_defaults);
            }
        }
        else
            m_skipped.insert("/" + std::string(loc) + portname);
        *old_loc = 0;
    }

    for(const auto& pr : port_count)
    {
        if(pr.second > 1)
            m_issues.emplace(issue::duplicate_parameter,
                             "/" + std::string(loc) + pr.first);
    }
}
Ejemplo n.º 15
0
void rgb_led_config(int argc, char** argv)
{
    FRESULT f_res;
    FIL fil;
    char f_name[4];
    uint8_t pattern_size = sizeof(ha_host_ns::rgb_config_pattern);

    int8_t ep_id = -1;
    uint8_t dev_type = (uint8_t) ha_ns::RGB_LED;

    char Rport = '0';
    uint16_t Rpin = 0;
    uint16_t Rtimer_x = 0;
    uint16_t Rchannel = 0;

    char Gport = '0';
    uint16_t Gpin = 0;
    uint16_t Gtimer_x = 0;
    uint16_t Gchannel = 0;

    char Bport = '0';
    uint16_t Bpin = 0;
    uint16_t Btimer_x = 0;
    uint16_t Bchannel = 0;

    uint16_t red_at_wp = 0;
    uint16_t green_at_wp = 0;
    uint16_t blue_at_wp = 0;

    char config_str[pattern_size];

    if (argc <= 1) {
        printf("ERR: too few argument. Try -h to get help.\n");
        return;
    }

    /* Read all configuration from shell */
    for (uint8_t count = 1; count < argc; count++) {
        if (argv[count][0] == '-') {
            switch (argv[count][1]) {
            case 'h': //get help
                printf(rgb_usage);
                return;
            case 'e': //set endpoint id
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                /* save endpoint id */
                ep_id = atoi(argv[count]);
                if (ep_id < 0 || ep_id > ha_host_ns::max_end_point) {
                    printf("ERR: invalid endpoint id value\n");
                    return;
                }
                snprintf(f_name, sizeof(f_name), "%x", ep_id);
                f_res = f_open(&fil, f_name, FA_READ | FA_OPEN_ALWAYS);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    return;
                }
                f_sync(&fil);
                UINT byte_read;
                f_res = f_read(&fil, config_str, pattern_size, &byte_read);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    return;
                }
                f_close(&fil);
                sscanf(config_str, ha_host_ns::rgb_config_pattern, &Rport,
                        &Rpin, &Rtimer_x, &Rchannel, &Gport, &Gpin, &Gtimer_x,
                        &Gchannel, &Bport, &Bpin, &Btimer_x, &Bchannel,
                        &red_at_wp, &green_at_wp, &blue_at_wp);
                break;
            case 'R': //configure Red channel
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &Rport)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Rpin = atoi(argv[count]);
                if (Rpin < 0 || Rpin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Rtimer_x = atoi(argv[count]);
                if (Rtimer_x < 0 || Rtimer_x > 8 || Rtimer_x == 6
                        || Rtimer_x == 7) {
                    printf("ERR: invalid timer value for pwm\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Rchannel = atoi(argv[count]);
                if (Rchannel < 0 || Rchannel > 15) {
                    printf("ERR: invalid timer value\n");
                    return;
                }
                break;
            case 'G': //configure Green channel
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &Gport)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Gpin = atoi(argv[count]);
                if (Rpin < 0 || Rpin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Gtimer_x = atoi(argv[count]);
                if (Gtimer_x < 0 || Gtimer_x > 8 || Gtimer_x == 6
                        || Gtimer_x == 7) {
                    printf("ERR: invalid timer value for pwm\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Gchannel = atoi(argv[count]);
                if (Gchannel < 0 || Gchannel > 15) {
                    printf("ERR: invalid timer value\n");
                    return;
                }
                break;
            case 'B': //configure Blue channel
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &Bport)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Bpin = atoi(argv[count]);
                if (Rpin < 0 || Rpin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Btimer_x = atoi(argv[count]);
                if (Btimer_x < 0 || Btimer_x > 8 || Btimer_x == 6
                        || Btimer_x == 7) {
                    printf("ERR: invalid timer value for pwm\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Bchannel = atoi(argv[count]);
                if (Bchannel < 0 || Bchannel > 15) {
                    printf("ERR: invalid timer value\n");
                    return;
                }
                break;
            case 'C': //set calibrating factor
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                red_at_wp = atoi(argv[count]);
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                green_at_wp = atoi(argv[count]);
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                blue_at_wp = atoi(argv[count]);
                if (red_at_wp > 100 || green_at_wp > 100 || blue_at_wp > 100) {
                    printf(
                            "ERR: invalid calibrating factor. Try -h to get help.\n");
                    return;
                }
                break;
            default:
                printf("Unknown option.\n");
                return;
            }
        } else {
            printf("Unknown option.\n");
            return;
        }
    }

    if (ep_id < 0) {
        printf("ERR: missing -e option.\n");
        return;
    }

    /* Write configurations to file */
    f_res = f_open(&fil, f_name, FA_WRITE | FA_CREATE_ALWAYS);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);

    snprintf(config_str, pattern_size, ha_host_ns::rgb_config_pattern, Rport,
            Rpin, Rtimer_x, Rchannel, Gport, Gpin, Gtimer_x, Gchannel, Bport,
            Bpin, Btimer_x, Bchannel, red_at_wp, green_at_wp, blue_at_wp);

    UINT byte_written;
    f_res = f_write(&fil, config_str, pattern_size, &byte_written);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        f_close(&fil);
        return;
    }
    f_close(&fil);

    /* read back */
    f_res = f_open(&fil, f_name, FA_READ);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);
    while (f_gets(config_str, sizeof(config_str), &fil)) {
        printf("%s", config_str);
    }
    f_close(&fil);

    /* modify device list file */
    modify_dev_list_file(ep_id, dev_type);

    return;
}
Ejemplo n.º 16
0
static int __init init(void)
{
	int i, ret=0;
	u_int16_t port;

	/* nornamlize the input */
	normalize();

	for (i=0;i<MAXPT_PORTS;i++)
	     memset(&pt[i], 0, sizeof(struct ip_conntrack_helper));

	for (i = 0; i < entries && registered_port < MAXPT_PORTS; i++) {
	    for (port = pt_record[i].outport[0]; port <= pt_record[i].outport[1]; port++ ) {

	        pt[registered_port].max_expected = PTMAXEXPECTED;
 //               pt[registered_port].timeout = 0;
//                pt[registered_port].flags = IP_CT_HELPER_F_REUSE_EXPECT;
                //pt[registered_port].me = ip_conntrack_pt;
	        pt[registered_port].help = help;

		if ( pt_record[i].outproto == 1 ) {
		  pt[registered_port].tuple.src.u.tcp.port = htons(port);
		  pt[registered_port].tuple.dst.protonum = IPPROTO_TCP;
		  pt[registered_port].mask.src.u.tcp.port = 0xFFFF;
		  pt[registered_port].mask.dst.protonum = 0xFFFF;
		}
		else if ( pt_record[i].outproto == 2 ) {
		  pt[registered_port].tuple.src.u.udp.port = htons(port);
		  pt[registered_port].tuple.dst.protonum = IPPROTO_UDP;
		  pt[registered_port].mask.src.u.udp.port = 0xFFFF;
		  pt[registered_port].mask.dst.protonum = 0xFFFF;
		}
		else {
		  pt[registered_port].tuple.src.u.all = htons(port);
		  pt[registered_port].mask.src.u.all = 0xFFFF;
		  pt[registered_port].mask.dst.protonum = 0;
		}
	    	DEBUGP("ip_conntrack_pt: registering helper for port %d\n",port);
		if ( check_port(port) )
	    	    printk("ip_conntrack_pt: cannot register port %d (already registered by other module)\n",port);
		else
	    	    ret = ip_conntrack_helper_register(&pt[registered_port++]);

		if( registered_port >= MAXPT_PORTS ) {
			printk( "Conntrack port forwarding table is full.  Remaining entries are not processed.\n" );
			pt_record[i].outport[1] = port;
			entries = i + 1;
			break;
		}

	    	if (ret) {
		   failed_port = port;
	           printk("ip_conntrack_pt: port %d register FAILED,port already registered  \n",port); 
	           fini();
	           return ret;
	    	}
	    }
	}

	return 0;
}
Ejemplo n.º 17
0
void adc_sensor_config(int argc, char** argv)
{
    FRESULT f_res;
    FIL fil;
    char f_name[4];
    uint8_t pattern_size = sizeof(ha_host_ns::adc_sensor_config_pattern);
    uint8_t first_equa_type = 0;
    uint8_t first_params = 0;
    uint16_t num_params = 0;
    uint16_t num_equation = 0;

    int8_t ep_id = -1;
    int8_t specified_subtype = -1;

    char port = '0';
    uint16_t pin = 0;
    uint16_t adc_x = 0;
    uint16_t channel = 0;

    int filter_thres = 0;
    int under_thres = 0;
    int over_thres = 0;

    char config_str[pattern_size];

    if (argc <= 1) {
        printf("ERR: too few argument. Try -h to get help.\n");
        return;
    }

    /* Read all configuration from shell */
    for (uint8_t count = 1; count < argc; count++) {
        if (argv[count][0] == '-') {
            switch (argv[count][1]) {
            case 'h': //get help
                printf(adc_sensor_usage);
                return;
            case 's':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                specified_subtype = atoi(argv[count]);
                break;
            case 'e': //set endpoint id
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                /* save endpoint id */
                ep_id = atoi(argv[count]);
                if (ep_id < 0 || ep_id > ha_host_ns::max_end_point) {
                    printf("ERR: invalid endpoint id value\n");
                    return;
                }
                snprintf(f_name, sizeof(f_name), "%x", ep_id);
                f_res = f_open(&fil, f_name, FA_READ | FA_OPEN_ALWAYS);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    return;
                }
                f_sync(&fil);

                UINT byte_read;
                f_res = f_read(&fil, config_str, pattern_size, &byte_read);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    f_close(&fil);
                    return;
                }
                f_close(&fil);
                sscanf(config_str, ha_host_ns::adc_sensor_config_pattern, &port,
                        &pin, &adc_x, &channel, &filter_thres, &under_thres,
                        &over_thres, &num_equation, &num_params);
                break;
            case 'p': //set port
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &port)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                break;
            case 'n': //set pin
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                pin = atoi(argv[count]);
                if (pin < 0 || pin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                break;
            case 'a': //set adc
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                adc_x = atoi(argv[count]);
                if (adc_x < 0 || adc_x > 3) {
                    printf("ERR: invalid adc value\n");
                    return;
                }
                break;
            case 'c': //set channel
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                channel = atoi(argv[count]);
                if (channel < 0 || channel > 15) {
                    printf("ERR: invalid channel value\n");
                    return;
                }
                break;
            case 't': //get equation type
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                first_equa_type = count;
                num_equation = 0;
                while (count < argc && argv[count][0] != '-') {
                    num_equation++;
                    count++;
                }
                if (num_equation == 0) {
                    printf("ERR: missing parameters in -t option.\n");
                    return;
                }
                count--;
                break;
            case 'P':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                first_params = count;
                num_params = 0;
                while (count < argc) {
                    if (argv[count][0] == '-') {
                        if (!isdigit(argv[count][1])) {
                            break;
                        }
                    }
                    num_params++;
                    count++;
                }
                count--;
                break;
            case 'f':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                filter_thres = atoi(argv[count]);
                break;
            case 'u':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                under_thres = atoi(argv[count]);
                break;
            case 'o':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                over_thres = atoi(argv[count]);
                break;
            default:
                printf("Unknown option.\n");
                return;
            }
        } else {
            printf("Unknown option.\n");
            return;
        }
    }

    if (ep_id < 0) {
        printf("ERR: missing -e option.\n");
        return;
    }

    if (specified_subtype < 0) {
        printf("ERR: missing -s option.\n");
        return;
    }

    if (first_equa_type == 0 || first_params == 0) {
        printf("ERR: missing -t or -P option.\n");
        return;
    }

    f_res = f_unlink(f_name);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }

    /* Write configurations to file */
    f_res = f_open(&fil, f_name, FA_WRITE | FA_CREATE_ALWAYS);
    if (f_res != FR_OK) {
        printf("Error on opening file to write configuration\n");
        return;
    }
    f_sync(&fil);

    snprintf(config_str, pattern_size, ha_host_ns::adc_sensor_config_pattern,
            port, pin, adc_x, channel, filter_thres, under_thres, over_thres,
            num_equation, num_params);
    f_puts(config_str, &fil);
    f_sync(&fil);

    for (uint8_t count = first_equa_type;
            count < first_equa_type + num_equation; count++) {
        snprintf(config_str, pattern_size, ha_host_ns::sensor_equa_type,
                argv[count][0]);
        f_puts(config_str, &fil);
        f_sync(&fil);
    }

    float param = 0.0f;
    for (uint8_t count = first_params; count < first_params + num_params;
            count++) {
        param = strtof(argv[count], NULL);
        snprintf(config_str, pattern_size, ha_host_ns::sensor_equa_params,
                param);
        f_puts(config_str, &fil);
        f_sync(&fil);
    }
    f_close(&fil);

    /* read back */
    f_res = f_open(&fil, f_name, FA_READ);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);
    while (f_gets(config_str, sizeof(config_str), &fil)) {
        printf("%s", config_str);
    }
    f_close(&fil);

    /* modify device list file */
    modify_dev_list_file(ep_id,
            combine_dev_type(ha_ns::ADC_SENSOR, (uint8_t) specified_subtype));

    return;
}
Ejemplo n.º 18
0
static void adc_common_config(int argc, char** argv, int8_t *endpoint_id)
{
    FRESULT f_res;
    FIL fil;
    uint8_t pattern_size = sizeof(ha_host_ns::adc_dev_config_pattern);
    char f_name[4];

    *endpoint_id = -1;
    char port = '0';
    uint16_t pin = 0;
    uint16_t adc_x = 0;
    uint16_t channel = 0;

    char config_str[pattern_size];

    if (argc <= 1) {
        printf("ERR: too few argument. Try -h to get help.\n");
        return;
    }

    /* Read all configuration from shell */
    for (uint8_t count = 1; count < argc; count++) {
        if (argv[count][0] == '-') {
            switch (argv[count][1]) {
            case 'h': //get help
                printf(adc_usage, argv[0]);
                return;
            case 'e': //set endpoint id
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                /* save endpoint id */
                *endpoint_id = atoi(argv[count]);
                if (*endpoint_id < 0
                        || *endpoint_id > ha_host_ns::max_end_point) {
                    printf("ERR: invalid endpoint id value\n");
                    return;
                }
                /* get file name from ep id */
                snprintf(f_name, sizeof(f_name), "%x", *endpoint_id);
                /* open "ep id" file */
                f_res = f_open(&fil, f_name, FA_READ | FA_OPEN_ALWAYS);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    return;
                }
                f_sync(&fil);
                UINT byte_read;
                f_res = f_read(&fil, config_str, pattern_size, &byte_read);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    f_close(&fil);
                    return;
                }
                f_close(&fil);
                sscanf(config_str, ha_host_ns::adc_dev_config_pattern, &port,
                        &pin, &adc_x, &channel);
                break;
            case 'p':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &port)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                break;
            case 'n':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                pin = atoi(argv[count]);
                if (pin < 0 || pin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                break;
            case 'a':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                adc_x = atoi(argv[count]);
                if (adc_x < 0 || adc_x > 3) {
                    printf("ERR: invalid adc value\n");
                    return;
                }
                break;
            case 'c':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                channel = atoi(argv[count]);
                if (channel < 0 || channel > 15) {
                    printf("ERR: invalid channel value\n");
                    return;
                }
                break;
            default:
                printf("Unknown option.\n");
                return;
            }
        } else {
            printf("Unknown option.\n");
            return;
        }
    }

    if (*endpoint_id < 0) {
        printf("ERR: missing -e option.\n");
        return;
    }

    /* Write configurations to file */
    f_res = f_open(&fil, f_name, FA_WRITE | FA_CREATE_ALWAYS);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);

    snprintf(config_str, pattern_size, ha_host_ns::adc_dev_config_pattern, port,
            pin, adc_x, channel);

    UINT byte_written;
    f_res = f_write(&fil, config_str, pattern_size, &byte_written);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        f_close(&fil);
        return;
    }
    f_close(&fil);

    /* read back */
    f_res = f_open(&fil, f_name, FA_READ);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);
    while (f_gets(config_str, sizeof(config_str), &fil)) {
        printf("%s", config_str);
    }
    f_close(&fil);

    return;
}
Ejemplo n.º 19
0
Archivo: piano.c Proyecto: eriser/Synth
int main() {
    uint8_t i, id;
    uint8_t timing[19]; // This controller control 18 keys
    uint8_t cnt[19]; // This controller control 18 keys
    uint32_t status[19]; // This controller control 18 keys
    
    // program setup
    discharge_ports();
    SREG = 0; // No interrupts
    
    DDRD |= _BV(PIND0); // NOTE: Only output pin is number 0
    PORTD0_SBI;

    for (i = 0; i < 19; i++) {
        timing[i] = 0;
        cnt[i]    = 0;
        status[i] = 0;
    }
    
    // main loop
    while(1) {
        // first step: check wether a key was pressed or not
        for (i = 0; i < 19; i++) {
            id = i + 1;
            if (check_port(id)) {
                if (!(status[i] & 0x80000000L)) // wasting a 0
                    cnt[i]++; // added one 1
                // else // wasting 1, cnt does not change
                status[i] <<= 1; // shift
                status[i] |= 1; // last added is 1
                
                if (cnt[i] > THRESHOLD) {
                    if (timing[i]) // key was already pressed
                        timing[i] = SUST;
                    else
                        timing[i] = SUST + 1;
                }
            } else {
                if (status[i] & 0x80000000L) // wasting a 1
                    cnt[i]--; // removed one 1
                // else // wasting 1, cnt does not change
                status[i] <<= 1; // shift, last byte is already 1
                
                if (timing[i])
                    timing[i]--;
            }
        }
        
        discharge_ports(); // after reading discharges ports for the next reading
        
        // second step: if some messages are true then send data to the synth
        for (i = 0; i < 19; i++)
            if (timing[i] == SUST + 1) {
                send_message(0x80 | GET_NOTE(i));
            } else if (timing[i] == 1) {
                send_message(0x00 | GET_NOTE(i));
            }

        //_delay_us(100); // wait some time
    }
    
    return 0;
}
Ejemplo n.º 20
0
void test_ipc_6_receiver(PROCESS self, PARAM param)
{
   PORT port1;
   PORT port2;
   PORT port3;
   PROCESS sender_1;
   PROCESS sender_2;
   PROCESS sender_3;
   int second_sender;
   int *data1;
   int *data2;
   int *data3;

   check_sum += 1;

   port1 = self->first_port;
   kprintf("%s: creating port 3 and port 2...\n", self->name);
   port3 = create_port();
   port2 = create_port(); 
   kprintf("%s: closing port 3 and port 2...\n", self->name);
   close_port(port2);
   close_port(port3);

   check_port(port1, self->name, TRUE);
   check_port(port2, self->name, FALSE);
   check_port(port3, self->name, FALSE);
   if (test_result != 0)
      test_failed(test_result);

   create_process(test_ipc_6_sender_process_3, 5, (PARAM) port3, "Sender 3");
   create_process(test_ipc_6_sender_process_2, 5, (PARAM) port2, "Sender 2");
   create_process(test_ipc_6_sender_process_1, 4, (PARAM) port1, "Sender 1");

   /*
    * receive first message
    */
   kprintf("%s: receiving first message...\n", self->name);
   data1 = (int*) receive(&sender_1);
   kprintf("\n%s: received a message from %s, parameter = %d.\n",
           self->name, sender_1->name, * data1);

   if (string_compare(sender_1->name, "Sender 2") == 1)
       test_failed(60);
   if (string_compare(sender_1->name, "Sender 3") == 1)
       test_failed(60);
   if (string_compare(sender_1->name, "Sender 1") != 1)
       test_failed(58);
    
   check_process("Sender 3", STATE_MESSAGE_BLOCKED, FALSE); 
   check_process("Sender 2", STATE_MESSAGE_BLOCKED, FALSE); 
   check_process("Sender 1", STATE_REPLY_BLOCKED, FALSE); 
   if (test_result != 0) {
       print_all_processes(kernel_window);
       test_failed(test_result);
   }
  
   /*
    * receive second message
    */
   kprintf("%s: opening port 2 and port 3...\n", self->name);
   open_port(port2);
   open_port(port3);

   check_sum += 2; // to check that first message is receiverd.

   kprintf("%s: receiving second message...\n", self->name);
   data2 = (int*) receive (&sender_2); 
   kprintf("%s: received a message from %s, parameter = %d.\n",
           self->name, sender_2->name, * data2);

   // second message can be from either sender 2 or sender 3, depending
   // on implementation of create_port(). 
   second_sender = 0;
   if (string_compare(sender_2->name, "Sender 2") == 1) {
       check_process("Sender 2", STATE_READY, TRUE); 
       check_process("Sender 3", STATE_MESSAGE_BLOCKED, FALSE); 
       second_sender = 2;
   } else if (string_compare(sender_2->name, "Sender 3") == 1) {
       check_process("Sender 3", STATE_READY, TRUE); 
       check_process("Sender 2", STATE_MESSAGE_BLOCKED, FALSE); 
       second_sender = 3;
   } else
       test_failed(44);
    
   check_sum += 4; // to check that second message is received.

   /* 
    * receive third message
    */
   kprintf("%s: receiving third message...\n", self->name);
   data3 = (int*) receive(&sender_3); 
   kprintf("%s: received a message from %s, parameter = %d.\n",
           self->name, sender_3->name, * data3);

   if (string_compare(sender_3->name, "Sender 1") == 1)
       test_failed(44);

   if (second_sender == 2) {
       if (string_compare(sender_3->name, "Sender 2") == 1)
	   test_failed(44);
       if (string_compare(sender_3->name, "Sender 3") != 1)
	   test_failed(58);
   } else {
       if (string_compare(sender_3->name, "Sender 3") == 1)
	   test_failed(44);
       if (string_compare(sender_3->name, "Sender 2") != 1)
	   test_failed(58);
   }
 
   check_process("Sender 3", STATE_READY, TRUE); 
   check_process("Sender 2", STATE_READY, TRUE); 
   check_process("Sender 1", STATE_REPLY_BLOCKED, FALSE); 
   if (test_result != 0) {
       print_all_processes(kernel_window);
       test_failed(test_result);
   }

   check_sum += 8; // to check that third message is received.

   return_to_boot();
}    
Ejemplo n.º 21
0
int main(int argc, const char *const *argv) {
	bool is_server = false;
	bool is_client = false;
	std::string ip_str;
	int port;
	// Parse command options
	po::options_description options_desc("Allowed Options");
	options_desc.add_options()
		("help", "produce help message")
		("listen_ip", po::value<std::string>(), "if starts like a server,need a listen ip and port")
		("listen_port", po::value<int>(), "if starts like a server,need a listen port and ip")
		("conn_ip", po::value<std::string>(), "connect server ip")
		("conn_port", po::value<int>(), "connect server port");

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, options_desc), vm);
	po::notify(vm);

	if (argc <= 1 || vm.count("help")) {
		usage();
		std::cout << options_desc << std::endl;
		return OK;
	}

	if (vm.count("listen_ip")) {
		ip_str = vm["listen_ip"].as<std::string>();
		if (!check_ip(ip_str)) {
			std::cout << "IP ERROR" << std::endl;
			return -1;
		}
		is_server = true;
	}

	if (vm.count("listen_port")) {
		port = vm["listen_port"].as<int>();
		if (!check_port(port)) {
			std::cout << "PORT ERROR" << std::endl;
			return -1;
		}

		if (vm.count("conn_ip")) {
			is_client = true;
		}

		if (!is_server) {
			std::cout << "HAS NO LISTEN IP!" << std::endl;
		}
	}

	// starts a server
	boost::shared_ptr<CTcpServer> server_ptr = NULL;
	boost::shared_ptr<CUdpServer> udp_server_ptr = NULL;
	if (is_server) {
		boost::asio::ip::address ip_addr = boost::asio::ip::make_address(ip_str);
		server_ptr = boost::make_shared<CTcpServer>(ip_addr, static_cast<unsigned short>(port));
		server_ptr->run();

		udp_server_ptr = boost::make_shared<CUdpServer>(ip_addr, static_cast<unsigned short>(port));
		udp_server_ptr->run();
	}

	// starts a client
	boost::shared_ptr<CTcpClient> client_ptr = NULL;
	if (is_client) {
		std::string client_ip_str(vm["conn_ip"].as<std::string>());
		client_ptr = boost::make_shared<CTcpClient>(client_ip_str, vm["conn_port"].as<int>());
		client_ptr->async_connect();
	}

	common_io_context.run();

	return OK;
}
Ejemplo n.º 22
0
int main(void) {

	int32_t	nready;
	uint8_t index_to;
	struct timeval timeout;

	/* settaggio della connessione TCP con l'applicazine fissa */
	to_app = setup_conn(SOCK_STREAM, AF_INET, LOCAL_LISTEN_PORT, (int8_t*) "INADDR_ANY", 0, 0, 1);
	/* accettazione della connessione proveniente dall'applicazione fissa */
	new_app_fd = listen_accept(to_app, &app_side);
	/* settaggio della connessione UDP con il monitor */
	udp_gate = setup_conn(SOCK_DGRAM, AF_INET, LOCAL_UDP_PORT, (int8_t*) "INADDR_ANY", 0, 0, 0);
	
	/* inizializzazione strutture */
	make_list(&port_list);
	clear_buffer(down_packets);
	clear_buffer(up_packets);
	udp_clear_buffer(to_app_packets);
	srand(getpid());
	/* inizializzazioni di default */
	last_uploaded = ID_START;
	actual_zero.tv_usec = actual_zero.tv_sec = 0;
	us_zero.tv_usec = us_zero.tv_sec = 0;
	index_to = BUFF_PACK_SIZE;	/* no timeout inizialmente */
	m_id_ports.type = 'C';
	m_id_ports.message = 0;
	last_notify = last_seq = 0;
	good_percentual = GOOD_P;

	FD_ZERO(&readfds);
	FD_ZERO(&writefds);
	FD_ZERO(&s_readfds);
	FD_ZERO(&s_writefds);

	FD_SET(new_app_fd, &readfds);	/* tanto prima aspetta un pacchetto da noi */
	FD_SET(udp_gate, &readfds);
	maxfds = (udp_gate > new_app_fd ? udp_gate : new_app_fd);

	for (;;) {

		s_readfds = readfds;
		s_writefds = writefds;
		nready = select(maxfds + 1, &s_readfds, &s_writefds, NULL, (index_to == BUFF_PACK_SIZE ? NULL : (&timeout)));
		if ((nready == ERROR) && (errno != EINTR)) {
			fprintf(stderr, "fatal error performing select. errno %s\n", strerror(errno));
			exit(EXIT_FAILURE);
		}
		if (FD_ISSET(new_app_fd, &s_readfds)) {
			uint8_t oldestpack, index;

			/* buffering dei pacchetti provenienti dall' applicazione */
			drop_expired(down_packets);
			safe_read(new_app_fd, DATA_BUFF_SIZE, data_app_fixed);
			/* evitiamo il possibile traboccamento di down_packets */
			if ((index = index_free_pack(down_packets)) == BUFF_PACK_SIZE) {
				oldestpack = oldest_pack(down_packets);
				clear_pack(down_packets, oldestpack);
				index = oldestpack;
			}
			memcpy(&(down_packets[index].udp_data.id_packet), data_app_fixed, sizeof(uint32_t));
			memcpy(&(down_packets[index].udp_data.data), &(data_app_fixed[4]), DATA_BUFF_SIZE - sizeof(uint32_t));
			down_packets[index].udp_data.type_packet = STANDARD;
			gettimeofday(&(down_packets[index].arrived), NULL);
			if (s_2_i(&us_zero) == 0)
				us_zero = down_packets[index].arrived;
			down_packets[index].udp_data.the_mighty_fix = s_2_i(&(down_packets[index].arrived)) - (s_2_i(&us_zero) + (INTER_PACKET * (down_packets[index].udp_data.id_packet - ID_FIRST_SENT)));
			down_packets[index].flag_to_send = NEW_ENTRY_FLAG;
			FD_SET(udp_gate, &writefds);
		}
		if (FD_ISSET(udp_gate, &s_writefds)) {
			uint8_t	index;
			struct errno_port ep;
			double rand_n;

			if ((index = first_pack_to_send(down_packets)) != BUFF_PACK_SIZE) {
				/* spedizione del pacchetto verso il monitor */
				ep.type_errno = EXIT_FAILURE;
				while ((ep.type_errno != EXIT_SUCCESS) && (ep.type_errno != EAGAIN) && (port_list != NULL)) {
					gettimeofday(&(down_packets[index].time_last_send), NULL);
					down_packets[index].udp_data.time_buffered = BUFFERED_TIME(down_packets[index]);
					ep = send_the_pack((int32_t*) &(down_packets[index]), STANDARD, udp_gate, port_list);
				/*	printf("utilizzato porta id: %u\n", ep.id_port); */
				}
			#ifdef O_DEBUG
				if (ep.type_errno == EXIT_SUCCESS) {
					printf("spedito il pacchetto con id %d\n", down_packets[index].udp_data.id_packet);
				}
			#endif
				RANDOM_N(rand_n);
				if ((rand_n > (good_percentual - 0)) && (down_packets[index].n_resending > 0)) {
					down_packets[index].flag_to_send = NACK_FLAG;	/* forza la riconsiderazione del pacchetto */
					down_packets[index].n_resending--;
				}
				if ((index = first_pack_to_send(down_packets)) == BUFF_PACK_SIZE)
					FD_CLR(udp_gate, &writefds);
			}
			else {
				FD_CLR(udp_gate, &writefds);
			}
		}
		if (FD_ISSET(udp_gate, &s_readfds)) {
			udp_packet tmp;
			struct sockaddr_in mon_side;
			
			/* ricezione dei dal monitor */
			general_recvfrom((int32_t *) &(tmp), sizeof(udp_packet), udp_gate, &mon_side);

			if (check_port(port_list, ntohs(mon_side.sin_port)) == FALSE) /* inserimento di una, forse, nuova porta monitor */
				insert_port(&port_list, ntohs(mon_side.sin_port));
			switch (tmp.type_packet) {
				case STANDARD: {
				#ifdef O_DEBUG
					printf("id pacchetto ricevuto: %d\n", tmp.id_packet);
				#endif
					up_packets[BUFF_PACK_SIZE - 1].udp_data = tmp;	/* speranza che sia vuoto per la legge di Gigio */
					gettimeofday(&(up_packets[BUFF_PACK_SIZE - 1].delivered), NULL);
					if ((actual_zero.tv_usec == 0) && (actual_zero.tv_sec == 0))	/* nuovo zero dell'opposto balancer */
						i_2_s(s_2_i(&(up_packets[BUFF_PACK_SIZE - 1].delivered)) - (INTER_PACKET * tmp.id_packet), &actual_zero);
					mighty_f_revenge(up_packets, BUFF_PACK_SIZE - 1, &actual_zero, 0);
					if (tmp.id_packet == (last_uploaded + 1)) {	/* e' il successivo */
						clear_pack(up_packets, BUFF_PACK_SIZE - 1);
						to_app_packets[index_udpfree_pack(to_app_packets)] = tmp;
						last_uploaded = tmp.id_packet;	/* aggiorno ultimo upload */
						check_inline_pack(up_packets, to_app_packets, &last_uploaded, tmp.id_packet);
						FD_SET(new_app_fd, &writefds);
					}
					else {
						if (tmp.id_packet > last_uploaded) {
							sort_buffer(up_packets);
						}
						else	/* in ritado abissale, drop */
							clear_pack(up_packets, BUFF_PACK_SIZE - 1);
					}
					break;
				}
				default : {		/* pacchetto di notifica */
					port_monitoring *ptmp = NULL;
					stat_notify *trick = (stat_notify*) &tmp;
				#ifdef O_DEBUG_N
					printf("pacchetto id: %d\n", tmp.id_packet);
					printf("pacchetto di notifica con porta id: %d\n", trick->id_port);
				#endif
				
					if ((last_notify < trick->id_notify) || (last_seq == trick->id_sequence)) { /* non e' in ritardo abissale */
						if ((trick->id_sequence < last_seq) || (trick->id_sequence > last_seq)) { /* nuova sequenza di notifiche */
							m_id_ports.message = trick->type_packet - NOTIFY_F;
							last_seq = trick->id_sequence;
						}
						last_notify = trick->id_notify;
						m_id_ports.message--; /* nuova notifica della stessa sequenza, decrementa contatore */
						m_id_ports.ports[m_id_ports.message] = trick->id_port + 1000;
						ptmp = find_port(port_list, trick->id_port + 1000); /* abbiamo spedito ID lato mobile, vogliamo quello fixed */
						if (ptmp == NULL) { /* porta di cui il fixed non era a conoscenza */
							if (m_id_ports.message == 0) {
							/* non ci sono piu' pacchetti di notifica, costruzione della lista delle porte aperte
							 * e reset-default per la prossima volta */
								m_id_ports.message = trick->type_packet - NOTIFY_F; /* lunghezza lista porte del mobile */
								build_act_ports(&port_list, &m_id_ports);
								m_id_ports.message = 0; /* reset per la prossima notifica */
								break;
							}
							insert_port(&port_list, trick->id_port + 1000);
							break; /* esce forzatamente dallo switch */
						}
						ptmp->not_to_fixed = *trick;	/* aggiorna la notifica */
						ptmp->last_tot_packets = ptmp->tot_packets - ptmp->medium_tot_packets;
						good_percentual = partial_pp_lost(port_list);
						ptmp->ack_packets += ptmp->not_to_fixed.n_received;
						ptmp->nack_packets = ptmp->tot_packets - ptmp->ack_packets;
						ptmp->medium_tot_packets = ptmp->tot_packets;
						mighty_f_ports(&port_list); /* calcolo performance delle porte */
						if (m_id_ports.message == 0) {
						/* non ci sono piu' pacchetti di notifica, costruzione della lista delle porte aperte
						* e reset-default per la prossima volta */
							m_id_ports.message = trick->type_packet - NOTIFY_F; /* lunghezza lista porte del mobile */
							build_act_ports(&port_list, &m_id_ports);
							m_id_ports.message = 0; /* reset per la prossima notifica */
						}
					}
				}
			}
		}
		if (FD_ISSET(new_app_fd, &s_writefds)) {
			memcpy(data_app_fixed, &(to_app_packets[0].id_packet), sizeof(uint32_t));
			memcpy(&(data_app_fixed[4]), &(to_app_packets[0].data), DATA_BUFF_SIZE - sizeof(uint32_t));
			safe_write(new_app_fd, DATA_BUFF_SIZE, data_app_fixed);
			udp_shift_pack(to_app_packets, 0);	/* clear e shift */
			if (to_app_packets[0].type_packet == FALSE)	/* non ce ne sono piu' */
				FD_CLR(new_app_fd, &writefds);
		}
		if (nready == 0) {	/* timeout espirato, nessun fd pronto */
			if (check_inline_pack(up_packets, to_app_packets, &last_uploaded, up_packets[0].udp_data.id_packet - 1))
				FD_SET(new_app_fd, &writefds);
		}
		index_to = BUFF_PACK_SIZE;
		timeout.tv_sec = timeout.tv_usec = 0;
		index_to = manage_timeout(up_packets, &timeout);
	}

	return 0;
}