Esempio n. 1
0
void route_listadd(char *name)
{
    FILE                *fp;
    int                 line = 0;
    int                 argc = 0;
    int                 ret;
    struct ether_addr   dev_addr;
    char                buf[100];
    char                *sp;
    char                *args[4];
    const char          space[] = " \t";


    /*** try to open file ***/
    fp = fopen(name, "r");
    if (!fp) {
        ret = errno;
        fprintf(stderr, "opening file %s", name);
        perror(NULL);
        exit(1);
    }

    /*** fill buffer from file and add route ***/
    while (fgets(buf, sizeof(buf), fp)) {
        line++;

        /* find newline char and make it end of string */
        sp = strchr(buf, '\n');
        if (sp)
            *sp = '\0';

        /* ignore comments and empty lines */
        if ((buf[0] == '#') || (buf[0] == '\0'))
            continue;

        /* split string into tokens */
        argc = 0;
        args[argc] = strtok(buf, space);
        do
            args[++argc] = strtok(NULL, space);
        while ((argc < 4) && args[argc]);

        /* wrong number of arguments? */
        if (argc != 3) {
            invalid_line_format(line, name);
            continue;
        }

        /*** check data ***/

        /* check MAC */
        if (ether_aton_r(args[1], &dev_addr) == NULL) {
            invalid_line_format(line, name);
            continue;
        }

        /* check IP */
        if (!inet_aton(args[0], &addr)) {
            invalid_line_format(line, name);
            continue;
        }

        /*** turn it all into a cmd for rtnet and execute ***/
        cmd.args.addhost.ip_addr = addr.s_addr;
        memcpy(cmd.args.addhost.dev_addr, dev_addr.ether_addr_octet,
               sizeof(dev_addr.ether_addr_octet));

        /* use device <dev> */
        strncpy(cmd.head.if_name, args[2], IFNAMSIZ);

        ret = ioctl(f, IOC_RT_HOST_ROUTE_ADD, &cmd);

        if (ret < 0) {
            perror("ioctl");
            exit(1);
        }

    }
    fclose(fp);

    exit(0);
}
Esempio n. 2
0
int ot_accept_client(int fd) {
	int tfd;
	int ret;
	int flags;
	struct sockaddr_in taddr;
	
	taddr.sin_family = AF_INET;
	taddr.sin_port = htons(otcfg_target_port);
	ret = inet_aton(otcfg_target_host, &taddr.sin_addr);
	if (ret == 0) {
		char* ipstr = NULL;

		OT_LOGI("Resolving domain name `%s'\n", otcfg_target_host);
		
		ipstr = dns_query(otcfg_target_host, NULL);
		if (ipstr == NULL) {
			OT_LOGW("Could not resolve domain `%s'\n", otcfg_target_host);
			shutdown(fd, SHUT_RDWR);
			close(fd); 
			exit(-3);
		}
		else {
			OT_LOGI("Resolved domain: %s --> %s\n", otcfg_target_host, ipstr);
		}
		
		inet_aton(ipstr, &taddr.sin_addr);
	}
	
	
	// 连接到目标服务器
	tfd = socket(AF_INET, SOCK_STREAM, 0);
	if (tfd <= 0) {
		perror("sub socket");
		shutdown(fd, SHUT_RDWR);
		close(fd); 
		exit(-1);
	}
	
	OT_LOGI("Connecting to %s:%d\n", inet_ntoa(taddr.sin_addr), ntohs(taddr.sin_port));
	ret = connect(tfd, (struct sockaddr*)&taddr, sizeof(taddr));
	if (ret < 0) {
		perror("sub connect");
		shutdown(fd, SHUT_RDWR);
		close(fd);
		close(tfd);
		exit(-2);
	}
	
	flags = fcntl(tfd, F_GETFL, 0);
	/*
	ret = fcntl(tfd, F_SETFL, flags | O_NONBLOCK);
	if (ret == -1) {
		perror("sub fcntl");
		shutdown(fd, SHUT_RDWR);
		shutdown(tfd, SHUT_RDWR);
		close(tfd);
		close(fd);
		exit(-1);
	}
	*/
	
	printf("Connected to target host %s:%d\n", otcfg_target_host, otcfg_target_port);
	
	/// 转发
	ot_tunneling_tcp(fd, tfd);
	
	shutdown(fd, SHUT_RDWR);
	shutdown(tfd, SHUT_RDWR);
	
	close(tfd);
	
	return 0;
}
Esempio n. 3
0
int main(int argc, char *argv[]) {
  unsigned char *pkt1 = NULL, buf2[6], buf3[1500];
  unsigned char *gateway6, *src6 = NULL, *dst6 = NULL, srcmac[16] = "", *mac = srcmac;
  int pkt1_len = 0, prefer = PREFER_GLOBAL, i, do_hop = 0, do_dst = 0, do_frag = 0, cnt, type = NXT_ICMP6, offset = 14;
  char *interface;
  int src4 = 0, dst4 = 0, port = -1;
  thc_ipv6_hdr *hdr;

  if (argc < 5 || strncmp(argv[1], "-h", 2) == 0)
    help(argv[0]);

  if (getenv("THC_IPV6_PPPOE") != NULL || getenv("THC_IPV6_6IN4") != NULL) printf("WARNING: %s is not working with injection!\n", argv[0]);

  while ((i = getopt(argc, argv, "DFHs:")) >= 0) {
    switch (i) {
    case 'F':
      do_frag++;
      break;
    case 'H':
      do_hop = 1;
      break;
    case 'D':
      do_dst = 1;
      break;
    case 's':
      if ((src6 = thc_resolve6(optarg)) == NULL) {
        fprintf(stderr, "Error: invalid IPv6 source address specified: %s\n", optarg);
      }
      break;
    default:
      fprintf(stderr, "Error: invalid option %c\n", i);
      exit(-1);
    }
  }

  if (argc - optind < 4)
    help(argv[0]);

  if (do_hdr_size)
    offset = do_hdr_size;
  interface = argv[optind];
  if ((gateway6 = thc_resolve6(argv[optind + 1])) == NULL) {
    fprintf(stderr, "Error: %s does not resolve to a valid IPv6 address\n", argv[optind + 1]);
    exit(-1);
  }
 
  // src ip4, dst ip4
  if (inet_aton(argv[optind + 2], (struct in_addr *)&src4) < 0) {
    fprintf(stderr, "Error: not a valid IPv4 address: %s\n", argv[optind + 2]);
    exit(-1);
  }
  if (inet_aton(argv[optind + 3], (struct in_addr *)&dst4) < 0) {
    fprintf(stderr, "Error: not a valid IPv4 address: %s\n", argv[optind + 3]);
    exit(-1);
  }

  if (argc - optind > 4)
    port = atoi(argv[optind + 4]);

  if ((mac = thc_get_own_mac(interface)) == NULL) {
    fprintf(stderr, "Error: invalid interface %s\n", interface);
    exit(-1);
  }

  if ((pkt1 = thc_create_ipv6_extended(interface, prefer, &pkt1_len, src6, gateway6, 0, 0, 0, 0, 0)) == NULL)
    return -1;
  if (do_hop) {
    type = NXT_HBH;
    if (thc_add_hdr_hopbyhop(pkt1, &pkt1_len, buf2, sizeof(buf2)) < 0)
      return -1;
  }
  if (do_frag) {
    if (type == NXT_ICMP6)
      type = NXT_FRAG;
    for (i = 0; i <= do_frag; i++)
      if (thc_add_hdr_oneshotfragment(pkt1, &pkt1_len, cnt++) < 0)
        return -1;
  }
  if (do_dst) {
    if (type == NXT_ICMP6)
      type = NXT_DST;
    if (thc_add_hdr_dst(pkt1, &pkt1_len, buf3, sizeof(buf3)) < 0)
      return -1;
  }
  if (thc_add_ipv4_rudimentary(pkt1, &pkt1_len, src4, dst4, port) < 0)
    return -1;
  if (thc_generate_pkt(interface, mac, NULL, pkt1, &pkt1_len) < 0) {
    fprintf(stderr, "Error: Can not generate packet, exiting ...\n");
    exit(-1);
  }

  printf("Sending IPv4 %s packet from %s to %s via 4to6 gateway %s\n", port == -1 ? "ICMPv4 ping" : "UDPv4", argv[optind + 2], argv[optind + 3], argv[optind + 1]);
  if (do_dst) {
    hdr = (thc_ipv6_hdr *) pkt1;
    thc_send_as_fragment6(interface, src6, dst6, type, hdr->pkt + 40 + offset, hdr->pkt_len - 40 - offset, 1240);
  } else {
    thc_send_pkt(interface, pkt1, &pkt1_len);
  }

  return 0;
}
Esempio n. 4
0
int
main(int argc, char **argv)
{
	
	
	struct sockaddr_un sa_dom_srv;
	struct sockaddr_un sa_dom;
	struct Nano_Board nano[4];
        ssize_t len;
	socklen_t sa_dom_len;
	fd_set rfds,rfd;
	int ret,maxfd,sd_in,sd_dom_srv,sd_dom,i,conn_boards=0;
	int conn_ctr[4];
	char buffer[ETH_FRAME_LEN];
	config_t conf;

	memset(&sa_dom,0,sizeof(sa_dom));
	memset(&sa_dom_len,0,sizeof(sa_dom_len));
	
	memset(nano,0,4*sizeof(struct Nano_Board));
	
	(void)signal(SIGINT,cleanup);
	(void)signal(SIGTERM,cleanup);
	
	config_init(&conf);
	
	if(CONFIG_FALSE == config_read_file(&conf,"carserver.cfg")){	
		fprintf(stderr,"Problem with reading Configuration in line %d:\n%s\n",
			config_error_line(&conf),
			config_error_text(&conf));
			config_destroy(&conf);
			return -1;
	}
	
	if (0 > config_lookup_int(&conf,"MIN_MSGS",&MIN_MSGS))
		{
			fprintf(stderr,"could not read MIN_MSGS\n");
			run = 0;
		}

	FD_ZERO(&rfds); //Initializes the descriptor to the null set.
	maxfd =-1;
	const char * addr;
	int port,led,W;
	int eCBC;
	config_setting_t *setting;
	setting = config_lookup(&conf, "Boards");
	if( 4 != config_setting_length(setting)){
		fprintf(stderr,"wrong number of boards configured");
		return -1;
	}
	run = 1;
	for(i = 0; i< 4&& run; i++){
		sd_in = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
		if(sd_in < 0){
			perror("opening Socket failed");
			run=0;
		}
		config_setting_t *board = config_setting_get_elem(setting, i);
		if(!(config_setting_lookup_string(board, "Address", &addr)&&
			config_setting_lookup_int(board, "Port", &port)&&
			config_setting_lookup_int(board, "led", &led)&&
			config_setting_lookup_int(board, "W", &W)&&
			config_setting_lookup_bool(board, "enConnBrokenCtr",&eCBC)))
		{
			fprintf(stderr,"Could not read ip-Address and Port of board %d\n",i);
			run=0;
		}
		nano[i].sa.sin_family = AF_INET;
		
		printf("ip address and port of board number %d: %s, %d \n",i, addr,port);
		inet_aton(addr,&(nano[i].sa.sin_addr)); //Converts IP Address from char* to struct in_addr
		
		nano[i].sa.sin_port = htons(port); //converts unsigned short int from host byte order to network byte order
		nano[i].indat.values.led = led;
		nano[i].indat.values.W = W;
		nano[i].indat.values.setEnMotorController = TRUE;
		nano[i].indat.values.enConnBrokenCtr =eCBC;
	
		if(0 > connect(sd_in, (struct sockaddr *)&(nano[i].sa),sizeof(struct sockaddr))){
			fprintf(stderr,"connect number %d failed\n",i);
			run=0;
		}
		nano[i].sd = sd_in;
			
		buffer[0]= 'I';
		ret = send(sd_in,buffer,1,MSG_DONTWAIT);
		if(0 >= ret){
			close(sd_in);
			printf("nano-board number %d did not receive."
				" closed connection.\n",i);
			run =0;
		}
		printf("sent I, this is %d byte\n",ret);
		nano[i].init = TRUE;
		FD_SET(sd_in,&rfds); //Adds the file descriptor sd_in to the set rfds
		maxfd = MAX(maxfd,sd_in);
		conn_boards |= 1<<i;
		conn_ctr[i] =0;
		// don't reconnect in the first 3 seconds:
		nano[i].last_conn_attempt = time(NULL)+3;
	}
	if (0 > config_lookup_string(&conf,"InitString",&nano_init))
	{
		fprintf(stderr,"could not read InitString\n");
		run = 0;
	}
	const char * str;
	if (config_lookup_string(&conf,"ClientSocket",&str)){
	  if (0 > (sd_dom_srv = open_dom(&sa_dom_srv,str))){
		fprintf(stderr,"open_dom() failed\n");
		return -1;
	  }
	} else {
		printf("Could not read ClientSocket from config file\n");
	}
	//init conn_timer 1sec in advance to make sure that there are enogh messages in the first second.
	time_t conn_timer = time(NULL)+1;
	struct timeval timeout;
	FD_SET(sd_dom_srv, &rfds);
	maxfd = MAX(maxfd,sd_dom_srv);
	timeout.tv_sec=1;
	timeout.tv_usec=0;
	sd_dom = -1;
	// battery power, battery compute , dist front, dist rear
	if(0 > init_car(nano,&conf,&conn_boards)){
		return -1;
	}
	
	/* Event loop: runs while run == 1 */
	while (run) {
		
		handle_car();
		// make sure that all nanoboards stay connected
		if(conn_timer< time(NULL)){
			for(i = 0; i< 4; i++){
				if(conn_ctr[i] < MIN_MSGS){
					conn_boards &= ~(1<<i);
					FD_CLR(nano[i].sd,&rfds);
					close(nano[i].sd);
					fprintf(stderr,"Board %d did not reach obligatory number of messages: only %d, not %d\n",i,conn_ctr[i],MIN_MSGS);
				}
				conn_ctr[i]=0;
				
			}
			conn_timer = time(NULL);
		}
		
			
		// if one board is disconnected, try to reconnect it
		for(i = 0; i<4;i++){
			if((conn_boards & 1<<i)==0 && nano[i].last_conn_attempt+1<time(NULL)){
			    nano[i].last_conn_attempt= time(NULL);
				nano[i].sd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
				if(nano[i].sd < 0){
					perror("opening Socket failed");
					continue;	
				}
				printf("reconnect board number %d\n",i);
				if(0 > (len = connect(nano[i].sd, (struct sockaddr *)&(nano[i].sa),sizeof(struct sockaddr)))){
						fprintf(stderr,"reconnect number %d failed error: %s\n",i,strerror(len));
						continue;
				}
				buffer[0]= 'I';
				ret = send(nano[i].sd,buffer,1,MSG_DONTWAIT);
				if(0 >= ret){
					printf("Was not able to send\n");
					close(nano[i].sd);
					continue;
				}
				nano[i].init = TRUE;
				FD_SET(nano[i].sd,&rfds);
				
				maxfd = MAX(maxfd,nano[i].sd);
				
			}
		}
		
		rfd = rfds;
		//printf("Waiting for incoming connections\n");
		ret = select(maxfd+1,&rfd,NULL,NULL,&timeout);
		if (0 > ret) {
			if (errno == EINTR)
				continue;
			perror("select() failed");
			run = 0;
		}
		
		/* Check the listening socket for incoming connections. */
		if (FD_ISSET(sd_dom_srv,&rfd)) {
			/* New client, accept() and add him. */
			sd_dom=accept(sd_dom_srv,(struct sockaddr*)&sa_dom,
					&sa_dom_len);
			if (0 > sd_dom) {
				perror("accept() failed");
				run = 0;
			}

			FD_SET(sd_dom,&rfds);
			maxfd = MAX(maxfd,sd_dom);

			fprintf(stdout,">> client connected to %s\n",
					sa_dom_srv.sun_path);
		}

		/* Read something from the client? */
		if (sd_dom != -1 && FD_ISSET(sd_dom,&rfd)) {
			printf("Read something from the Client.");
			len = recv(sd_dom,buffer,ETH_FRAME_LEN,0);
			if (0 >= len) {
				FD_CLR(sd_dom,&rfds);
				close(sd_dom);
				sd_dom = -1;

				fprintf(stdout,"client disconnected from %s\n",
						sa_dom_srv.sun_path);

				continue;
			}

			fprintf(stdout,">> received command from %s:\n",
					sa_dom_srv.sun_path);
			// read command and
			//int resp = read_command(buffer,len)
			//if (0 > resp)
			//	continue;
			len = parse_command(buffer); 
			/*sprintf(buffer,"X:%d, W:%d, AccX:%d, AccY:%d\n",nano[0].outdat.values.X,
				nano[0].outdat.values.W, nano[0].outdat.values.Acc.sum[0],
				nano[0].outdat.values.Acc.sum[1]);
			*/
			printf("response to command is:\n%s\n(len:%d)\n",buffer,len);
			ret = send(sd_dom,buffer,len,MSG_DONTWAIT);
			if (0 >= ret) {
				FD_CLR(sd_dom,&rfds);
				close(sd_dom);
				sd_dom = -1;

				fprintf(stdout,"client disconnected from %s\n",
						sa_dom_srv.sun_path);

				continue;
			}
		}
		/* Read from a NanoBoard. */
		for(i =0; i < 4 ; i++){
			if (FD_ISSET(nano[i].sd,&rfd)){
				conn_ctr[i]++;
				//printf("Received something from nanoboard #%d.\n",i);
				len = recv(nano[i].sd,buffer,ETH_FRAME_LEN,0);
				if(len < 0){
				printf("recv did not work. sd: %d ;error: %s\n",nano[i].sd,strerror(len));
				conn_boards &= ~(1<<i);
				FD_CLR(nano[i].sd,&rfds);
				close(nano[i].sd);
				continue;
				} else
				if(sizeof(outdata)+1!=len||buffer[0]!='R'){
					if(nano[i].init == TRUE){
						printf("Init frame received. Try to compare:\n");
						nano[i].init=FALSE;
                        buffer[len]='\0';
						if(strcmp(nano_init,buffer)!=0){
							printf("compared strings, but there is a"
								"fault:\nimx6:%sNano:%s\n",nano_init,buffer);
							printf("buffer[0] = %c, size of message: %d\n",buffer[0],len);
							if( buffer[0] == 'I' || buffer[0]== 'R'){
								printf("Ignore this character.\n");
								nano[i].init = TRUE;
								continue;
							}else
								run =0;
						}else{
							printf("string is the same, connected!\n");
							conn_boards |= (1<<i);
						}
					} else {
						FD_CLR(nano[i].sd,&rfds);
						close(nano[i].sd);
						fprintf(stderr,"nano-board number %d sent wrong data."
						 "\n length is %d, should be %d. first char in buffer"
 						 " is %c. \n closed connection.\n",
						 i,len,sizeof(outdata)+1,buffer[0]);
						conn_boards &= ~(1<<i);
						FD_CLR(nano[i].sd,&rfds);
				        close(nano[i].sd);
						if(conn_boards==0){
							printf("no more boards, stop running.\n");
							run =0;
						}
 						continue;
					}
				}else
				{
					memcpy(&(nano[i].outdat.serial),buffer+1,len-1);
				}
				// copy indat to buffer:
				memcpy(buffer+1,&(nano[i].indat.serial),sizeof(indata));
				buffer[0]='S';
				//printf("W: %d\n",nano[i].indat.values.W);
				ret = send(nano[i].sd,buffer,
					sizeof(indata)+1,MSG_DONTWAIT);
				if(0 >= ret){
					FD_CLR(sd_dom,&rfds);
					close(nano[i].sd);
					printf("nano-board number %d did not receive."
						" closed connection.\n",i);
					run = 0;
				}
			}
		}
	}
	for(i =0; i< 4; i++)
		if(conn_boards & 1<<i)
			close(nano[i].sd);	
		
	if (sd_dom > -1 && FD_ISSET(sd_dom,&rfds))
		close(sd_dom);
	close(sd_dom_srv);
	unlink(sa_dom_srv.sun_path);
	config_destroy(&conf);
	fprintf(stderr,"Shutdown complete.\n\n");

	return 0;
		
}
Esempio n. 5
0
void
ipfw_config_nat(int ac, char **av)
{
	struct cfg_nat *n;		/* Nat instance configuration. */
	int i, off, tok, ac1;
	char *id, *buf, **av1, *end;
	size_t len;

	av++;
	ac--;
	/* Nat id. */
	if (ac == 0)
		errx(EX_DATAERR, "missing nat id");
	id = *av;
	i = (int)strtol(id, &end, 0);
	if (i <= 0 || *end != '\0')
		errx(EX_DATAERR, "illegal nat id: %s", id);
	av++;
	ac--;
	if (ac == 0)
		errx(EX_DATAERR, "missing option");

	len = sizeof(struct cfg_nat);
	ac1 = ac;
	av1 = av;
	while (ac1 > 0) {
		tok = match_token(nat_params, *av1);
		ac1--;
		av1++;
		switch (tok) {
		case TOK_IP:
		case TOK_IF:
			ac1--;
			av1++;
			break;
		case TOK_ALOG:
		case TOK_DENY_INC:
		case TOK_SAME_PORTS:
		case TOK_SKIP_GLOBAL:
		case TOK_UNREG_ONLY:
		case TOK_RESET_ADDR:
		case TOK_ALIAS_REV:
		case TOK_PROXY_ONLY:
			break;
		case TOK_REDIR_ADDR:
			if (ac1 < 2)
				errx(EX_DATAERR, "redirect_addr: "
				    "not enough arguments");
			len += estimate_redir_addr(&ac1, &av1);
			av1 += 2;
			ac1 -= 2;
			break;
		case TOK_REDIR_PORT:
			if (ac1 < 3)
				errx(EX_DATAERR, "redirect_port: "
				    "not enough arguments");
			av1++;
			ac1--;
			len += estimate_redir_port(&ac1, &av1);
			av1 += 2;
			ac1 -= 2;
			/* Skip optional remoteIP/port */
			if (ac1 != 0 && isdigit(**av1)) {
				av1++;
				ac1--;
			}
			break;
		case TOK_REDIR_PROTO:
			if (ac1 < 2)
				errx(EX_DATAERR, "redirect_proto: "
				    "not enough arguments");
			len += sizeof(struct cfg_redir);
			av1 += 2;
			ac1 -= 2;
			/* Skip optional remoteIP/port */
			if (ac1 != 0 && isdigit(**av1)) {
				av1++;
				ac1--;
			}
			if (ac1 != 0 && isdigit(**av1)) {
				av1++;
				ac1--;
			}
			break;
		default:
			errx(EX_DATAERR, "unrecognised option ``%s''", av1[-1]);
		}
	}

	if ((buf = malloc(len)) == NULL)
		errx(EX_OSERR, "malloc failed");

	/* Offset in buf: save space for n at the beginning. */
	off = sizeof(*n);
	memset(buf, 0, len);
	n = (struct cfg_nat *)buf;
	n->id = i;

	while (ac > 0) {
		tok = match_token(nat_params, *av);
		ac--;
		av++;
		switch (tok) {
		case TOK_IP:
			if (ac == 0)
				errx(EX_DATAERR, "missing option");
			if (!inet_aton(av[0], &(n->ip)))
				errx(EX_DATAERR, "bad ip address ``%s''",
				    av[0]);
			ac--;
			av++;
			break;
		case TOK_IF:
			if (ac == 0)
				errx(EX_DATAERR, "missing option");
			set_addr_dynamic(av[0], n);
			ac--;
			av++;
			break;
		case TOK_ALOG:
			n->mode |= PKT_ALIAS_LOG;
			break;
		case TOK_DENY_INC:
			n->mode |= PKT_ALIAS_DENY_INCOMING;
			break;
		case TOK_SAME_PORTS:
			n->mode |= PKT_ALIAS_SAME_PORTS;
			break;
		case TOK_UNREG_ONLY:
			n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
			break;
		case TOK_SKIP_GLOBAL:
			n->mode |= PKT_ALIAS_SKIP_GLOBAL;
			break;
		case TOK_RESET_ADDR:
			n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
			break;
		case TOK_ALIAS_REV:
			n->mode |= PKT_ALIAS_REVERSE;
			break;
		case TOK_PROXY_ONLY:
			n->mode |= PKT_ALIAS_PROXY_ONLY;
			break;
			/*
			 * All the setup_redir_* functions work directly in
			 * the final buffer, see above for details.
			 */
		case TOK_REDIR_ADDR:
		case TOK_REDIR_PORT:
		case TOK_REDIR_PROTO:
			switch (tok) {
			case TOK_REDIR_ADDR:
				i = setup_redir_addr(&buf[off], &ac, &av);
				break;
			case TOK_REDIR_PORT:
				i = setup_redir_port(&buf[off], &ac, &av);
				break;
			case TOK_REDIR_PROTO:
				i = setup_redir_proto(&buf[off], &ac, &av);
				break;
			}
			n->redir_cnt++;
			off += i;
			break;
		}
	}

	i = do_cmd(IP_FW_NAT_CFG, buf, off);
	if (i)
		err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");

	if (!co.do_quiet) {
		/* After every modification, we show the resultant rule. */
		int _ac = 3;
		const char *_av[] = {"show", "config", id};
		ipfw_show_nat(_ac, (char **)(void *)_av);
	}
}
int main (int argc, char **argv)
{
    char                *dir;
    char                *host;
    char                *ports;
    int                 port;
    struct hostent      *h;
    int                 fstype;
    FILE                *mtabf;
    struct mntent       mnt =
    {
        0,
        0,
        NSD_FSTYPE,
        "soft,timeo=100,retrans=2",
        0,
        0,
    };

    if (argc != 4)
        usage ();

    dir = argv[1];
    host = argv[2];
    port = atoi ((ports = argv[3]));

    /* Prepare for host lookup. */
    memset ((void *) &sin, 0, sizeof (sin));
    sin.sin_family = 2;
    sin.sin_port = port;

    /* Look up the host. */
    if (inet_aton (host, &sin.sin_addr))
        ;
    else if ((h = gethostbyname (host)))
    {
        unsigned long   *l = (unsigned long *) *(h->h_addr_list);
        sin.sin_addr.s_addr = l[0];
    }
    else
    {
        fprintf (stderr, "Cannot resolve host %s.\n", host);
        return 1;
    }

    /* Get filesystem type index for nsd filesystem type. */
    if ((fstype = sysfs (GETFSIND, NSD_FSTYPE)) < 0)
    {
        perror ("sysfs (" NSD_FSTYPE ")");
        return 1;
    }

    fprintf (stderr, "Mounting nsd " NSD_FSTYPE " fs from %s(%s):%d onto %s\n",
             host, inet_ntoa (sin.sin_addr), port, dir);

    /* These flags are documented in /usr/include/sys/mount.h. MS_DOXATTR
       means "tell server to trust us with attributes" and MS_DATA means
       "6-argument mount".

       MS_DOXATTR is a mount option in IRIX 6.4 and up. The attack doesn't
       seem to work without this option. So even though this program will
       compile on IRIX 6.2, you need to use an IRIX 6.4 or higher OS to
       attack nsd. */
    if (mount (dir, dir, MS_DOXATTR|MS_DATA, (char *) fstype, &nx, sizeof (nx))
            != 0)
    {
        perror ("mount");
        return 1;
    }

    /* Record mount point in /etc/mtab. */
    mnt.mnt_fsname = malloc (strlen (host) + sizeof (":nsd@") + strlen (ports) + 1);
    sprintf (mnt.mnt_fsname, "%s:nsd@%s", host, ports);
    mnt.mnt_dir = dir;
    if (!(mtabf = setmntent (MTAB_FILE, "r+")))
    {
        perror ("setmntent");
        return 1;
    }
    if (addmntent (mtabf, &mnt) < 0)
    {
        perror ("addmntent");
        return 1;
    }
    if (endmntent (mtabf) < 0)
    {
        perror ("endmntent");
        return 1;
    }

    return 0;
}
Esempio n. 7
0
int
ifconfig(const char *ifname, int flags, const char *addr, const char *mask)
{
	int sockfd, ret = 0;
	struct ifreq ifr;
	struct in_addr addr_in, mask_in;

	/* Open a socket to the kernel */
	if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
		return -1;

	/* Set interface name */
	memset(&ifr, 0, sizeof(ifr));
	strncpy(ifr.ifr_name, ifname, IFNAMSIZ);

	/* Get interface flags */
	if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
		ret = errno;
		goto err;
	}

	/* Set interface flags */
	if (!flags)
		ifr.ifr_flags &= ~(IFF_UP);
	else
		ifr.ifr_flags |= flags;

	if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
		ret = errno;
		goto err;
	}

	/* Set IP address */
	if (addr) {
		if (!inet_aton(addr, &addr_in))
			addr_in.s_addr = INADDR_ANY;
		sin_addr(&ifr.ifr_addr).s_addr = addr_in.s_addr;
		ifr.ifr_addr.sa_family = AF_INET;
		if (ioctl(sockfd, SIOCSIFADDR, &ifr) < 0) {
			ret = errno;
			goto err;
		}
	}

	/* Set IP netmask and broadcast */
	if (addr && mask) {
		if (!inet_aton(mask, &mask_in))
			mask_in.s_addr = INADDR_ANY;
		if (addr_in.s_addr != INADDR_ANY && mask_in.s_addr != INADDR_ANY) {
			sin_addr(&ifr.ifr_netmask).s_addr = mask_in.s_addr;
			ifr.ifr_netmask.sa_family = AF_INET;
			if (ioctl(sockfd, SIOCSIFNETMASK, &ifr) < 0) {
				ret = errno;
				goto err;
			}
			
			sin_addr(&ifr.ifr_broadaddr).s_addr = htonl((ntohl(addr_in.s_addr) & ntohl(mask_in.s_addr)) | ~(ntohl(mask_in.s_addr)));
			ifr.ifr_broadaddr.sa_family = AF_INET;
			if (ioctl(sockfd, SIOCSIFBRDADDR, &ifr) < 0) {
				ret = errno;
				goto err;
			}
		}
	}

err:
	close(sockfd);

	return ret;
}
Esempio n. 8
0
static void parse_opt_netmask(pingtun_t *handle, char *arg) {
	if (0 == inet_aton(arg, &handle->netmask)) {
		ERR("invalid netmask: %s", arg);
		usage();
	}
}
Esempio n. 9
0
static void parse_opt_address(pingtun_t *handle, char *arg) {
	if (0 == inet_aton(arg, &handle->address)) {
		ERR("invalid address: %s", arg);
		usage();
	}
}
Esempio n. 10
0
/*********************************************************************
 函 数 名  : ws__addRadiusSession
 功能描述  : 添加Radius会话保持配置
 输入参数  : soap        ---- web service执行环境
			 name        ---- radius会话保持名称
			 agetime     ---- 老化时间
             keeptype    ---- 保持属性
 输出参数  : ret         ---- 返回结果
 返 回 值  : WS_OK		 ---- 执行成功
 ===========================================================
 最近一次修改记录 :
 修改作者	: weiyuxia
 修改目的	: 新建
 修改日期	: 2012年3月9日
*****************************************************************************/
s32 ws__addRadiusSession(WS_ENV *soap, s8 *name, s32 agetime, s32 keeptype, s32 typelength, s8 *snatip,s32 relateswitch,s32 relateindex, s32 policyaction, s32 *ret)
{
    u32 count;
    u32 nodeid;
    s32 syscall_result;
	s32 sys_error_code = 0;    
    sqlite3 *db = NULL;
    sqlite3_res res = NULL;
    adx_radius_cfg_down_t cfg; 
    (void)ret;

    if(NULL == (db = sqlite3_open_ex(1, SESSION_TREE_DB)))
    {
        return ws_send_soap_error(soap,   "db open error!");
    }
    session_keep_generate_id(db, "tb_radius_session", "id", SESSION_KEEP_TYPE_RADIUS, &nodeid);   

    snprintf(g_sqlite_sql_buf, sizeof(g_sqlite_sql_buf),
            "SELECT COUNT(*) AS count FROM tb_radius_session where name='%s';", name);
    sqlite3_exec_query_ex(db, g_sqlite_sql_buf, &res);
    sqlite3_get_u32_ex(res, 0, "count", &count);
    sqlite3_res_free_ex(res);
	
    res = NULL;
    if(0 < count)
    {
        sqlite3_close_ex(db);
	    db = NULL;
		return ws_send_soap_error(soap, "keep_session policy already exist.");
    }
	
    cfg.radius_id = nodeid;
    cfg.age_time = agetime;
    cfg.keep_type = keeptype;
    cfg.typelength = typelength;
	cfg.relateswitch = relateswitch;
	cfg.relateindex = relateindex;
	cfg.policyaction = policyaction;
	cfg.index = ADX_RADIUS_MAX_PERSIS_CFG;
    inet_aton((s8 *)snatip, (struct in_addr *)&(cfg.snatip));
    if(ERROR_SUCCESS != conplat_syscall(MODULEID_ADX_VSLB, ADX_VSLB_ADD_RADIUS_PERSIS, &cfg, sizeof(adx_radius_cfg_down_t), &syscall_result))
    {
        goto label_ret;        
    }

    snprintf(g_sqlite_sql_buf, sizeof(g_sqlite_sql_buf),
		        "INSERT INTO tb_radius_session(id,name,agetime,keeptype, typelength, snatip, indexid, relateswitch, relateindex, policyaction) VALUES(%d,'%s',%d,%d, %d, '%s', %d, %d, %d, %d);", nodeid, name, agetime, keeptype, typelength, snatip, cfg.index,relateswitch,relateindex, policyaction);
	sqlite3_exec_ex(db, g_sqlite_sql_buf);
    add_session_tree_node(db, SESSION_KEEP_TYPE_RADIUS, nodeid, name);
	
    if(ERROR_SUCCESS != conplat_syscall(ADX_MODULEID_SLB|ADX_BOARD, ADX_VSLB_ADD_RADIUS_PERSIS, &cfg, sizeof(adx_radius_cfg_down_t), &syscall_result))
    {
        goto label_ret;        
    }
	
	
label_ret:   
    sqlite3_close_ex(db);
    db = NULL;
 	WEB_SEND_EX_OPERLOG_QUICK(sys_error_code, "add radius session persistence profile (name: %s)", name);   
    return WS_OK;  
}
Esempio n. 11
0
/*********************************************************************
 函 数 名  : ws__modRadiusSession
 功能描述  : 修改Radius会话保持配置
 输入参数  : soap        ---- web service执行环境
             id          ---- 树id
			 name        ---- radius会话保持名称
			 agetime     ---- 老化时间
			 keeptype    ---- 保持属性
 输出参数  : ret         ---- 返回结果
 返 回 值  : WS_OK		 ---- 执行成功
 ===========================================================
 最近一次修改记录 :
 修改作者	: weiyuxia
 修改目的	: 新建
 修改日期	: 2012年3月9日
*****************************************************************************/
s32 ws__modRadiusSession(WS_ENV *soap, s32 nodeid, s8 *name, s32 agetime, s32 keeptype, s32 typelength, s8 * snatip,s32 relateswitch, s32 relateindex, s32 policyaction, s32 *ret)
{
    u32 count;
    u32 oldindex;
	u32 old_relateswitch;
	u32 old_relateindex;
    s32 err_tmp;
    s32 syscall_result;
    sqlite3 *db = NULL;
    adx_radius_cfg_down_t cfg;
    (void)ret;
    sqlite3_res res = NULL;
	    
    if(NULL == (db = sqlite3_open_ex(1, SESSION_TREE_DB)))
    {
        return ws_send_soap_error(soap,   "db open error!");
    }

    snprintf(g_sqlite_sql_buf, sizeof(g_sqlite_sql_buf), 
             "SELECT COUNT(*) AS count FROM tb_radius_session WHERE id=%d;", nodeid);         
	sqlite3_exec_ex(db, g_sqlite_sql_buf);
    sqlite3_get_u32_ex(res, 0, "count", &count);
    sqlite3_res_free_ex(res);
    res = NULL;
    if(0 == count)
    {
        sqlite3_close_ex(db);
	    db = NULL;
		return ws_send_soap_error(soap, "policy not found!");
    }
    
    snprintf(g_sqlite_sql_buf, sizeof(g_sqlite_sql_buf), 
             "SELECT * FROM tb_radius_session WHERE id=%d;", nodeid); 
    sqlite3_exec_query_ex(db, g_sqlite_sql_buf, &res);
    sqlite3_get_u32_ex(res, 0, "indexid", &oldindex);
	sqlite3_get_u32_ex(res, 0, "relateswitch", &old_relateswitch);
	sqlite3_get_u32_ex(res, 0, "relateindex", &old_relateindex);
    sqlite3_res_free_ex(res);
    res = NULL;

    cfg.radius_id = nodeid;
    cfg.age_time = agetime;
    cfg.keep_type = keeptype;
    cfg.typelength = typelength;
    cfg.old_index = oldindex;
	cfg.relateswitch = relateswitch;
	cfg.relateindex = relateindex;
	cfg.policyaction = policyaction;
    cfg.index = ADX_RADIUS_MAX_PERSIS_CFG;
    cfg.vs_index = ADX_VSLB_INVALID_VS_INDEX;
    inet_aton((s8 *)snatip, (struct in_addr *)&(cfg.snatip));

    err_tmp = conplat_syscall(MODULEID_ADX_VSLB, ADX_VSLB_MODIFY_RADIUS_PERSIS, &cfg, sizeof(adx_radius_cfg_down_t), &syscall_result);
    if((ERROR_SUCCESS != err_tmp) || (ERROR_SUCCESS != syscall_result))
    {
        goto label_ret;        
    }

    snprintf(g_sqlite_sql_buf, sizeof(g_sqlite_sql_buf), 
             "UPDATE tb_radius_session SET name='%s', agetime=%d, keeptype=%d, typelength=%d, snatip='%s', indexid=%d, relateswitch=%d, relateindex=%d, policyaction=%d WHERE id=%d;",
             name, agetime, keeptype, typelength, snatip, cfg.index, relateswitch,relateindex,policyaction,nodeid);         
	sqlite3_exec_ex(db, g_sqlite_sql_buf);
	
    mod_session_tree_node(db, nodeid, name);
	
    conplat_syscall(ADX_MODULEID_SLB|ADX_BOARD, ADX_VSLB_MODIFY_RADIUS_PERSIS, &cfg, sizeof(adx_radius_cfg_down_t), &syscall_result);

label_ret:
    sqlite3_close_ex(db);
    db = NULL;  

    return WS_OK;   
}
int main(int argc,char *argv[])
{
    FILE *filehd;
    struct sockaddr_in server;
    int sock;
    int choice;
    char command[20];
    int k, size, status,ret,j=0;
    char usern[20],passwd[20],ip[15],shut[10],ch;
    struct stat obj;
    char filel[300],gfiln[20],pfnam[20],pfilc[1000],*f;
    int err[5],p,auth[5],csize;

    strcpy(ip,argv[1]);
    printf("ip:%s\n",ip);
    printf("enter username:\n");
    scanf("%s",usern);
    printf("enter password\n");
    scanf("%s",passwd);
    SSL_CTX *ctx;								//SSL pointers
    SSL *ssl;
    
    sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock == -1)
        {
            printf("socket creation failed\n");
            exit(1);
        }
		strcpy(password,"clpfile");
        SSL_library_init();								//SSL
		SSL_load_error_strings();

		const SSL_METHOD *meth=SSLv23_client_method();	//method
		
		ctx=SSL_CTX_new(meth);								//CTX Method
		if(ctx==NULL)
			{
				printf("ctx method creation failed\n");
				return -1;
			}
		
		load_certificate(ctx);					//load_certificate call
        server.sin_family=AF_INET;
        server.sin_port = htons(3000);
        inet_aton(ip,&(server.sin_addr));
        k = connect(sock,(struct sockaddr*)&server, sizeof(server));
        if(k == -1)
        {
            printf("Connect Error\n");
            exit(1);
        }
		  //int i = 1;
        ssl=SSL_new(ctx);							//SSL OBJECTS
        if(ctx==NULL)
        {
        printf("unable to create ssl object \n");
        return -1;
        }

		SSL_set_fd(ssl,sock);
		ret=SSL_connect(ssl);
			if(ret<0)
			{
				printf("error mapping ssl object\n");
				return -1;
			}
			
			/*strcpy(mss,"hello world");
			SSL_write(ssl,mss,sizeof(mss));*/
			
			SSL_write(ssl,usern,sizeof(usern));
			SSL_write(ssl,passwd,sizeof(passwd));
			SSL_read(ssl,auth,sizeof(auth));
			if(auth[0]!=0)
				{
					printf("invalid credentials!!\n");
					printf("server shutting down\n");
					SSL_shutdown(ssl);
					close(sock);
					exit(1);	
				}
while(1)
			    
    {
    printf("Enter a choice:\n1. get 2. put 3.ls 4. help 5. quit\n");
    scanf("%d", &choice);
    switch(choice)
    {
        case 1:
                strcpy(command,"get");
                SSL_write(ssl,command,sizeof(command));
                printf("enter file name\n");
                scanf("%s",gfiln);
                SSL_write(ssl,gfiln,sizeof(gfiln));
                //printf("file name sent\n");
                SSL_read(ssl,err,sizeof(err));
                if(err[0]==1)
                {
                    printf("file not found!!\n");
                    SSL_shutdown(ssl);
                    close(sock); //file not found
                    }
                else
                {
                    SSL_read(ssl,&csize,sizeof(int));
                    printf("file size=%d\n",csize);
                    f=malloc(csize);
                    SSL_read(ssl,f,csize);
                    getf(gfiln,f);
                    printf("file %s copied from server successfully !\n",gfiln);
                    //memset(f,'\0',csize);
                }
                break;
        case 2:
                strcpy(command,"put");
                SSL_write(ssl,command,sizeof(command));
                printf("enter file to be put:\n");
                scanf("%s",pfnam);
                filehd=fopen(pfnam,"r");
                stat(pfnam,&obj);
                csize = obj.st_size;
                printf("file size=%d\n",csize);
                if(filehd!=NULL)
                {
                    SSL_write(ssl,pfnam,sizeof(pfnam));
                    SSL_write(ssl,&csize,sizeof(int));
                    f=malloc(csize);
                    putf(pfnam,f);
                    SSL_write(ssl,f,csize);
                    printf("%s\n",f);
                    printf("file sent successfully !!\n");
                }
                else
                {
                    printf("file doesn't exsist !!\n");
                    SSL_shutdown(ssl);
                    close(sock);// close as file doesn't exsist
                }
                break;
        case 3:
                strcpy(command,"ls");
                SSL_write(ssl,command,sizeof(command));
                SSL_read(ssl,filel,sizeof(filel));
                printf("list of files :\n%s \n",filel);
                break;
        case 4:
                printf("command help! :\n");
                printf("> get : get command can be used to get files from the server onto the client's systsem.\n");
                printf("> put : put command can be used to put a file from client's system onto the server.\n");
                printf("> ls : ls command lists the files in the current directory of the server.\n");
                printf("> quit : terminates the connection \n");
						break;
										
        case 5:
                strcpy(command,"quit");
                SSL_write(ssl,command,sizeof(command));
                shut[0]=-1;
                SSL_write(ssl,shut,sizeof(shut));
                printf("Server closed\nQuitting..\n");
                SSL_shutdown(ssl);
                close(sock);
                exit(0);
                }
											
            }
        SSL_shutdown(ssl);
        close(sock);
        return 0;
}
Esempio n. 13
0
int main(int argc, char* argv[])
{
	int i, maxi, listenfd, connfd, sockfd,epfd,nfds, portnumber;
	ssize_t n;
	char line[MAXLINE];
	socklen_t clilen;

	if ( 2 == argc )
	{
		if( (portnumber = atoi(argv[1])) < 0 )
		{
			fprintf(stderr,"Usage:%s portnumber/a/n",argv[0]);
			return 1;
		}
	}
	else
	{
		fprintf(stderr,"Usage:%s portnumber/a/n",argv[0]);
		return 1;
	}

	//声明epoll_event结构体的变量,ev用于注册事件,数组用于回传要处理的事件
	struct epoll_event ev,events[20];
	//生成用于处理accept的epoll专用的文件描述符
	epfd=epoll_create(256);
	struct sockaddr_in clientaddr;
	struct sockaddr_in serveraddr;
	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	//把socket设置为非阻塞方式

	setnonblocking(listenfd);

	//设置与要处理的事件相关的文件描述符

	ev.data.fd=listenfd;
	//设置要处理的事件类型

	ev.events=EPOLLIN|EPOLLET;
	//ev.events=EPOLLIN;

	//注册epoll事件
	epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev);
	bzero(&serveraddr, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	char *local_addr="127.0.0.1";
	inet_aton(local_addr,&(serveraddr.sin_addr));//htons(portnumber);

	serveraddr.sin_port=htons(portnumber);
	bind(listenfd,(struct sockaddr *)&serveraddr, sizeof(serveraddr));
	listen(listenfd, LISTENQ);
	maxi = 0;
	for ( ; ; ) {
		//等待epoll事件的发生
		nfds=epoll_wait(epfd,events,20,500);

		//处理所发生的所有事件
		for(i=0;i<nfds;++i)
		{
			printf("nfds=%d\n", nfds);
			if(events[i].data.fd==listenfd)//如果新监测到一个SOCKET用户连接到了绑定的SOCKET端口,建立新的连接。
			{
				connfd = accept(listenfd,(struct sockaddr *)&clientaddr, &clilen);
				if(connfd<0){
					perror("connfd<0");
					exit(1);
				}
				//setnonblocking(connfd);

				char *str = inet_ntoa(clientaddr.sin_addr);
				printf("accapt a connection from %s, connfd=%d\n", str, connfd);
				//设置用于读操作的文件描述符
				ev.data.fd=connfd;
				//设置用于注册的读操作事件
				ev.events=EPOLLIN|EPOLLET;
				//ev.events=EPOLLIN;
				//注册ev
				epoll_ctl(epfd,EPOLL_CTL_ADD,connfd,&ev);
			}
			else if(events[i].events&EPOLLIN)//如果是已经连接的用户,并且收到数据,那么进行读入。
			{
				printf("EPOLLIN\n");
				if ( (sockfd = events[i].data.fd) < 0)
					continue;
				if ( (n = read(sockfd, line, MAXLINE)) < 0) {
					if (errno == ECONNRESET) {
						close(sockfd);
						events[i].data.fd = -1;
					} else
						printf("readline error\n");
				} else if (n == 0) {
					close(sockfd);
					events[i].data.fd = -1;
				}
				line[n] = '\0';
				printf("read:%s, fd=%d\n", line, sockfd);

				//设置用于写操作的文件描述符
				ev.data.fd=sockfd;
				//设置用于注册的写操作事件
				ev.events=EPOLLOUT|EPOLLET;
				//修改sockfd上要处理的事件为EPOLLOUT
				//epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev);
			}
			else if(events[i].events&EPOLLOUT) // 如果有数据发送
			{
				printf("EPOLLOUT\n");
				sockfd = events[i].data.fd;
				printf("write fd=%d\n", sockfd);
				write(sockfd, line, n);
				//设置用于读操作的文件描述符

				ev.data.fd=sockfd;
				//设置用于注测的读操作事件

				ev.events=EPOLLIN|EPOLLET;
				//修改sockfd上要处理的事件为EPOLIN
				epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev);
			}
		}
	}

	return 0;
}
Esempio n. 14
0
int main(int argc, char *argv[]) {

    int       conn_s;                /*  connection socket         */
    short int port;                  /*  port number               */
    struct    sockaddr_in servaddr;  /*  socket address structure  */
    char      buffer[MAX_LINE];      /*  character buffer          */
    char     *szAddress;             /*  Holds remote IP address   */
    char     *szPort;                /*  Holds remote port         */
    char     *endptr;                /*  for strtol()              */


    /*  Get command line arguments  */

    ParseCmdLine(argc, argv, &szAddress, &szPort);


    /*  Set the remote port  */

    port = strtol(szPort, &endptr, 0);
    if ( *endptr ) {
	printf("ECHOCLNT: Invalid port supplied.\n");
	exit(EXIT_FAILURE);
    }
	

    /*  Create the listening socket  */

    if ( (conn_s = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
	fprintf(stderr, "ECHOCLNT: Error creating listening socket.\n");
	exit(EXIT_FAILURE);
    }


    /*  Set all bytes in socket address structure to
        zero, and fill in the relevant data members   */

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_port        = htons(port);


    /*  Set the remote IP address  */

    if ( inet_aton(szAddress, &servaddr.sin_addr) <= 0 ) {
	printf("ECHOCLNT: Invalid remote IP address.\n");
	exit(EXIT_FAILURE);
    }

    
    /*  connect() to the remote echo server  */

    if ( connect(conn_s, (struct sockaddr *) &servaddr, sizeof(servaddr) ) < 0 ) {
	printf("ECHOCLNT: Error calling connect()\n");
	exit(EXIT_FAILURE);
    }


    /*  Get string to echo from user  */

    printf("Enter the string to echo: ");
    fgets(buffer, MAX_LINE, stdin);
    

    /*  Send string to echo server, and retrieve response  */

    Writeline(conn_s, buffer, strlen(buffer));
    Readline(conn_s, buffer, MAX_LINE-1);


    /*  Output echoed string  */

    printf("Echo response: %s\n", buffer);

    return EXIT_SUCCESS;
}
Esempio n. 15
0
void
ParseUPnPClient(char *location)
{
	char buf[8192];
	struct sockaddr_in dest;
	int s, n, do_headers = 0, nread = 0;
	struct timeval tv;
	char *addr, *path, *port_str;
	long port = 80;
	char *off = NULL, *p;
	int content_len = sizeof(buf);
	struct NameValueParserData xml;
	int client;
	enum client_types type = 0;
	uint32_t flags = 0;
	char *model, *serial, *name;

	if (strncmp(location, "http://", 7) != 0)
		return;
	path = location + 7;
	port_str = strsep(&path, "/");
	if (!path)
		return;
	addr = strsep(&port_str, ":");
	if (port_str)
	{
		port = strtol(port_str, NULL, 10);
		if (!port)
			port = 80;
	}

	memset(&dest, '\0', sizeof(dest));
	if (!inet_aton(addr, &dest.sin_addr))
		return;
	/* Check if the client is already in cache */
	dest.sin_family = AF_INET;
	dest.sin_port = htons(port);

	s = socket(PF_INET, SOCK_STREAM, 0);
	if( s < 0 )
		return;

	tv.tv_sec = 0;
	tv.tv_usec = 500000;
	setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
	setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));

	if( connect(s, (struct sockaddr*)&dest, sizeof(struct sockaddr_in)) < 0 )
		goto close;

	n = snprintf(buf, sizeof(buf), "GET /%s HTTP/1.0\r\n"
	                               "HOST: %s:%ld\r\n\r\n",
	                               path, addr, port);
	if( write(s, buf, n) < 1 )
		goto close;

	while( (n = read(s, buf+nread, sizeof(buf)-nread-1)) > 0 )
	{
		nread += n;
		buf[nread] = '\0';
		n = nread;
		p = buf;

		while( !off && n-- > 0 )
		{
			if(p[0]=='\r' && p[1]=='\n' && p[2]=='\r' && p[3]=='\n')
			{
				off = p + 4;
				do_headers = 1;
			}
			p++;
		}
		if( !off )
			continue;

		if( do_headers )
		{
			p = buf;
			if( strncmp(p, "HTTP/", 5) != 0 )
				goto close;
			while(*p != ' ' && *p != '\t') p++;
			/* If we don't get a 200 status, ignore it */
			if( strtol(p, NULL, 10) != 200 )
				goto close;
			if( (p = strcasestr(p, "Content-Length:")) )
				content_len = strtol(p+15, NULL, 10);
			do_headers = 0;
		}
		if( buf + nread - off >= content_len )
			break;
	}
close:
	close(s);
	if( !off )
		return;
	nread -= off - buf;
	ParseNameValue(off, nread, &xml);
	model = GetValueFromNameValueList(&xml, "modelName");
	serial = GetValueFromNameValueList(&xml, "serialNumber");
	name = GetValueFromNameValueList(&xml, "friendlyName");
	if( model )
	{
		DPRINTF(E_DEBUG, L_SSDP, "Model: %s\n", model);
		if( strstr(model, "Roku SoundBridge") )
		{
			type = ERokuSoundBridge;
			flags |= FLAG_MS_PFS;
			flags |= FLAG_AUDIO_ONLY;
			flags |= FLAG_MIME_WAV_WAV;
		}
		else if( strcmp(model, "Samsung DTV DMR") == 0 && serial )
		{
			DPRINTF(E_DEBUG, L_SSDP, "Serial: %s\n", serial);
			/* The Series B I saw was 20081224DMR.  Series A should be older than that. */
			if( atoi(serial) > 20081200 )
			{
				type = ESamsungSeriesB;
				flags |= FLAG_SAMSUNG;
				flags |= FLAG_DLNA;
				flags |= FLAG_NO_RESIZE;
			}
		}
		else
		{
			if( name && (strcmp(name, "marantz DMP") == 0) )
			{
				type = EMarantzDMP;
				flags |= FLAG_DLNA;
				flags |= FLAG_MIME_WAV_WAV;
			}
		}
	}
	ClearNameValueList(&xml);
	if( !type )
		return;
	/* Add this client to the cache if it's not there already. */
	client = SearchClientCache(dest.sin_addr, 1);
	if( client < 0 )
	{
		for( client=0; client<CLIENT_CACHE_SLOTS; client++ )
		{
			if( clients[client].addr.s_addr )
				continue;
			get_remote_mac(dest.sin_addr, clients[client].mac);
			clients[client].addr = dest.sin_addr;
			DPRINTF(E_DEBUG, L_SSDP, "Added client [%d/%s/%02X:%02X:%02X:%02X:%02X:%02X] to cache slot %d.\n",
			                         type, inet_ntoa(clients[client].addr),
			                         clients[client].mac[0], clients[client].mac[1], clients[client].mac[2],
			                         clients[client].mac[3], clients[client].mac[4], clients[client].mac[5], client);
			break;
		}
	}
	clients[client].type = type;
	clients[client].flags = flags;
	clients[client].age = time(NULL);
}
Esempio n. 16
0
int main(int argc, char *argv[]) {

	struct sockaddr_in si_other;
	int s, i, slen=sizeof(si_other);
	int n;
	int fd;
	int len;

	char buf[BUFLEN];
    	char *filebuf;
	struct stat fInfo;
	char *fIdx1,*fIdx2;

        if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) {
		printf("socket\n");
		return -1;
	}


	memset((char *) &si_other, 0, sizeof(si_other));
	si_other.sin_family = AF_INET;
        si_other.sin_port = htons(PORTIPHONE);
        
	if (inet_aton(IP, &si_other.sin_addr)==0) {
		printf("inet_aton() failed\n");
          	return -1;
        }


#ifdef FROM_FILE
	/* Open File */
	fd = open(FILENAME,O_RDONLY);
	fstat(fd,&fInfo);
	printf("Size: %d\n",(int) fInfo.st_size);
	
	filebuf = (char *) malloc(sizeof(char)*fInfo.st_size);
	read(fd,filebuf,fInfo.st_size);

//	printf("%s\n",filebuf);
/*
	printf("Create packet...\n");
	memset(buf,BUFLEN,'\0');
*/

	fIdx1=NULL;
	fIdx2=NULL;
	fIdx1=strstr(filebuf,"ACC");
//	printf("-------------\n%s\n",fIdx1);
	fIdx2=strstr(fIdx1+1,"ACC");
//	printf("-------------\n%s\n",fIdx2);

	len = fIdx2 -  fIdx1;
	printf("Len: %d\n",len);
	
	i=1;
	while (fIdx2!=NULL & fIdx1!=NULL) { 
		len =  fIdx2 -  fIdx1;
		printf("Len: %d\n",len);
		memset(buf,BUFLEN,'\0');
		strncpy(buf,fIdx1,len);
		n =sendto(s, buf, len, 0, (struct sockaddr *) &si_other, slen);
		printf("%s\n",buf);
		fIdx1=strstr(fIdx2+1,"ACC");
		fIdx2=strstr(fIdx1+1,"ACC");
		usleep(100000);
		//sleep(1);
		printf("%d\n",i);
		i++;
	};
	close(fd);       
	
#else
	n =sendto(s, DATA, strlen(DATA), 0, (struct sockaddr *) &si_other, slen);
	
	printf("Data %s\n",DATA);
	if ( n < 0)
            printf("sendto()\n");
  	else
	      printf("Sent %d bytes\n",n);	

#endif	
	
	close(s);
	return 0;
}
Esempio n. 17
0
File: tun.c Progetto: Churro/iodine
int
tun_setip(const char *ip, const char *other_ip, int netbits)
{
	char cmdline[512];
	int netmask;
	struct in_addr net;
	int i;
#ifndef LINUX
	int r;
#endif
#ifdef WINDOWS32
	DWORD status;
	DWORD ipdata[3];
	struct in_addr addr;
	DWORD len;
#endif

	netmask = 0;
	for (i = 0; i < netbits; i++) {
		netmask = (netmask << 1) | 1;
	}
	netmask <<= (32 - netbits);
	net.s_addr = htonl(netmask);

	if (inet_addr(ip) == INADDR_NONE) {
		fprintf(stderr, "Invalid IP: %s!\n", ip);
		return 1;
	}
#ifndef WINDOWS32
	snprintf(cmdline, sizeof(cmdline), 
			IFCONFIGPATH "ifconfig %s %s %s netmask %s",
			if_name,
			ip,
#ifdef FREEBSD
			other_ip, /* FreeBSD wants other IP as second IP */
#else
			ip,
#endif
			inet_ntoa(net));
	
	fprintf(stderr, "Setting IP of %s to %s\n", if_name, ip);
#ifndef LINUX
	struct in_addr netip;
	netip.s_addr = inet_addr(ip);
	netip.s_addr = netip.s_addr & net.s_addr;
	r = system(cmdline);
	if(r != 0) {
		return r;
	} else {
		
		snprintf(cmdline, sizeof(cmdline),
				"/sbin/route add %s/%d %s",
				inet_ntoa(netip), netbits, ip);
	}
	fprintf(stderr, "Adding route %s/%d to %s\n", inet_ntoa(netip), netbits, ip);
#endif
	return system(cmdline);
#else /* WINDOWS32 */

	/* Set device as connected */
	fprintf(stderr, "Enabling interface '%s'\n", if_name);
	status = 1;
	r = DeviceIoControl(dev_handle, TAP_IOCTL_SET_MEDIA_STATUS, &status, 
		sizeof(status), &status, sizeof(status), &len, NULL);
	if (!r) {
		fprintf(stderr, "Failed to enable interface\n");
		return -1;
	}
	
	if (inet_aton(ip, &addr)) {
		ipdata[0] = (DWORD) addr.s_addr;   /* local ip addr */
		ipdata[1] = net.s_addr & ipdata[0]; /* network addr */
		ipdata[2] = (DWORD) net.s_addr;    /* netmask */
	} else {
		return -1;
	}

	/* Tell ip/networkaddr/netmask to device for arp use */
	r = DeviceIoControl(dev_handle, TAP_IOCTL_CONFIG_TUN, &ipdata, 
		sizeof(ipdata), &ipdata, sizeof(ipdata), &len, NULL);
	if (!r) {
		fprintf(stderr, "Failed to set interface in TUN mode\n");
		return -1;
	}

	/* use netsh to set ip address */
	fprintf(stderr, "Setting IP of interface '%s' to %s (can take a few seconds)...\n", if_name, ip);
	snprintf(cmdline, sizeof(cmdline), "netsh interface ip set address \"%s\" static %s %s",
		if_name, ip, inet_ntoa(net));
	return system(cmdline);
#endif
}
Esempio n. 18
0
// 登陆邮件服务器,进行身份验证, added by interma@BMY 2005.5.12
// 返回值为1表示有效,0表示无效, -1表示和pop服务器连接出错
int test_mail_valid(char *user, char *pass, char *popip)
{
    char buffer[512]; 
    int sockfd;
    struct sockaddr_in server_addr; 
    struct hostent *host; 

	if (user[0] == ' ' || pass[0] == ' ')
		return 0;

    // 客户程序开始建立 sockfd描述符
    if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) 
    {  
        return -1;
    } 
    if (strcmp(user, "test")==0) {
	return -2;
    }
    int i;
    for ( i = 0; i < 8; i++)
    server_addr.sin_zero[i] = 0;
    server_addr.sin_family=AF_INET; 
    server_addr.sin_port=htons(110);
    // 202.117.1.22 == stu.xjtu.edu.cn 
    if(inet_aton(popip, &server_addr.sin_addr) == 0) 
    {  
        return -1;
    }

    // 客户程序发起连接请求
    if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1) 
    {  
        return -1; 
    } 

    if(read(sockfd,buffer,512) == -1 )
    {  
        return -1; 
    } 
    if (buffer[0] == '-')
        return -1;
    
    sprintf(buffer, "USER %s\r\n", user);
    if (write(sockfd, buffer, strlen(buffer)) == -1)
    { 
        return -1; 
    }   
     
    if(read(sockfd,buffer,512) == -1 )
    {  
        return -1; 
    } 
    if (buffer[0] == '-')
    {   
        return 0;
    }   
     
    sprintf(buffer, "PASS %s\r\n", pass);
    if (write(sockfd, buffer, strlen(buffer)) == -1)
    { 
        return -1; 
    }
     
    if(read(sockfd,buffer,512) == -1 )
    {  
        return -1; 
    } 
    if (buffer[0] == '-')
    {
        return 0;
    }
            
    write(sockfd, "QUIT\r\n", strlen("QUIT\r\n"));          
    return 1;
}    
Esempio n. 19
0
static int sendtoxymond(char *recipient, char *message, FILE *respfd, char **respstr, int fullresponse, int timeout)
{
	struct in_addr addr;
	struct sockaddr_in saddr;
	int	sockfd = -1;
	fd_set	readfds;
	fd_set	writefds;
	int	res, isconnected, wdone, rdone;
	struct timeval tmo;
	char *msgptr = message;
	char *p;
	char *rcptip = NULL;
	int rcptport = 0;
	int connretries = SENDRETRIES;
	char *httpmessage = NULL;
	char recvbuf[32768];
	int haveseenhttphdrs = 1;
	int respstrsz = 0;
	int respstrlen = 0;
	int result = XYMONSEND_OK;

	if (dontsendmessages && !respfd && !respstr) {
		fprintf(stdout, "%s\n", message);
		fflush(stdout);
		return XYMONSEND_OK;
	}

	setup_transport(recipient);

	dbgprintf("Recipient listed as '%s'\n", recipient);

	if (strncmp(recipient, "http://", strlen("http://")) != 0) {
		/* Standard communications, directly to Xymon daemon */
		rcptip = strdup(recipient);
		rcptport = xymondportnumber;
		p = strchr(rcptip, ':');
		if (p) {
			*p = '\0'; p++; rcptport = atoi(p);
		}
		dbgprintf("Standard protocol on port %d\n", rcptport);
	}
	else {
		char *bufp;
		char *posturl = NULL;
		char *posthost = NULL;

		if (xymonproxyhost == NULL) {
			char *p;

			/*
			 * No proxy. "recipient" is "http://host[:port]/url/for/post"
			 * Strip off "http://", and point "posturl" to the part after the hostname.
			 * If a portnumber is present, strip it off and update rcptport.
			 */
			rcptip = strdup(recipient+strlen("http://"));
			rcptport = xymondportnumber;

			p = strchr(rcptip, '/');
			if (p) {
				posturl = strdup(p);
				*p = '\0';
			}

			p = strchr(rcptip, ':');
			if (p) {
				*p = '\0';
				p++;
				rcptport = atoi(p);
			}

			posthost = strdup(rcptip);

			dbgprintf("HTTP protocol directly to host %s\n", posthost);
		}
		else {
			char *p;

			/*
			 * With proxy. The full "recipient" must be in the POST request.
			 */
			rcptip = strdup(xymonproxyhost);
			rcptport = xymonproxyport;

			posturl = strdup(recipient);

			p = strchr(recipient + strlen("http://"), '/');
			if (p) {
				*p = '\0';
				posthost = strdup(recipient + strlen("http://"));
				*p = '/';

				p = strchr(posthost, ':');
				if (p) *p = '\0';
			}

			dbgprintf("HTTP protocol via proxy to host %s\n", posthost);
		}

		if ((posturl == NULL) || (posthost == NULL)) {
			sprintf(errordetails + strlen(errordetails), "Unable to parse HTTP recipient");
			if (posturl) xfree(posturl);
			if (posthost) xfree(posthost);
			if (rcptip) xfree(rcptip);
			return XYMONSEND_EBADURL;
		}

		bufp = msgptr = httpmessage = malloc(strlen(message)+1024);
		bufp += sprintf(httpmessage, "POST %s HTTP/1.0\n", posturl);
		bufp += sprintf(bufp, "MIME-version: 1.0\n");
		bufp += sprintf(bufp, "Content-Type: application/octet-stream\n");
		bufp += sprintf(bufp, "Content-Length: %d\n", (int)strlen(message));
		bufp += sprintf(bufp, "Host: %s\n", posthost);
		bufp += sprintf(bufp, "\n%s", message);

		if (posturl) xfree(posturl);
		if (posthost) xfree(posthost);
		haveseenhttphdrs = 0;

		dbgprintf("HTTP message is:\n%s\n", httpmessage);
	}

	if (inet_aton(rcptip, &addr) == 0) {
		/* recipient is not an IP - do DNS lookup */

		struct hostent *hent;
		char hostip[IP_ADDR_STRLEN];

		hent = gethostbyname(rcptip);
		if (hent) {
			memcpy(&addr, *(hent->h_addr_list), sizeof(struct in_addr));
			strcpy(hostip, inet_ntoa(addr));

			if (inet_aton(hostip, &addr) == 0) {
				result = XYMONSEND_EBADIP;
				goto done;
			}
		}
		else {
			sprintf(errordetails+strlen(errordetails), "Cannot determine IP address of message recipient %s", rcptip);
			result = XYMONSEND_EIPUNKNOWN;
			goto done;
		}
	}

retry_connect:
	dbgprintf("Will connect to address %s port %d\n", rcptip, rcptport);

	memset(&saddr, 0, sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_addr.s_addr = addr.s_addr;
	saddr.sin_port = htons(rcptport);

	/* Get a non-blocking socket */
	sockfd = socket(PF_INET, SOCK_STREAM, 0);
	if (sockfd == -1) { result = XYMONSEND_ENOSOCKET; goto done; }
	res = fcntl(sockfd, F_SETFL, O_NONBLOCK);
	if (res != 0) { result = XYMONSEND_ECANNOTDONONBLOCK; goto done; }

	res = connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
	if ((res == -1) && (errno != EINPROGRESS)) {
		sprintf(errordetails+strlen(errordetails), "connect to Xymon daemon@%s:%d failed (%s)", rcptip, rcptport, strerror(errno));
		result = XYMONSEND_ECONNFAILED;
		goto done;
	}

	rdone = ((respfd == NULL) && (respstr == NULL));
	isconnected = wdone = 0;
	while (!wdone || !rdone) {
		FD_ZERO(&writefds);
		FD_ZERO(&readfds);
		if (!rdone) FD_SET(sockfd, &readfds);
		if (!wdone) FD_SET(sockfd, &writefds);
		tmo.tv_sec = timeout;  tmo.tv_usec = 0;
		res = select(sockfd+1, &readfds, &writefds, NULL, (timeout ? &tmo : NULL));
		if (res == -1) {
			sprintf(errordetails+strlen(errordetails), "Select failure while sending to Xymon daemon@%s:%d", rcptip, rcptport);
			result = XYMONSEND_ESELFAILED;
			goto done;
		}
		else if (res == 0) {
			/* Timeout! */
			shutdown(sockfd, SHUT_RDWR);
			close(sockfd);

			if (!isconnected && (connretries > 0)) {
				dbgprintf("Timeout while talking to Xymon daemon@%s:%d - retrying\n", rcptip, rcptport);
				connretries--;
				sleep(1);
				goto retry_connect;	/* Yuck! */
			}

			result = XYMONSEND_ETIMEOUT;
			goto done;
		}
		else {
			if (!isconnected) {
				/* Havent seen our connect() status yet - must be now */
				int connres;
				socklen_t connressize = sizeof(connres);

				res = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &connres, &connressize);
				dbgprintf("Connect status is %d\n", connres);
				isconnected = (connres == 0);
				if (!isconnected) {
					sprintf(errordetails+strlen(errordetails), "Could not connect to Xymon daemon@%s:%d (%s)", 
						  rcptip, rcptport, strerror(connres));
					result = XYMONSEND_ECONNFAILED;
					goto done;
				}
			}

			if (!rdone && FD_ISSET(sockfd, &readfds)) {
				char *outp;
				int n;

				n = recv(sockfd, recvbuf, sizeof(recvbuf)-1, 0);
				if (n > 0) {
					dbgprintf("Read %d bytes\n", n);
					recvbuf[n] = '\0';

					/*
					 * When running over a HTTP transport, we must strip
					 * off the HTTP headers we get back, so the response
					 * is consistent with what we get from the normal Xymon daemon
					 * transport.
					 * (Non-http transport sets "haveseenhttphdrs" to 1)
					 */
					if (!haveseenhttphdrs) {
						outp = strstr(recvbuf, "\r\n\r\n");
						if (outp) {
							outp += 4;
							n -= (outp - recvbuf);
							haveseenhttphdrs = 1;
						}
						else n = 0;
					}
					else outp = recvbuf;

					if (n > 0) {
						if (respfd) {
							fwrite(outp, n, 1, respfd);
						}
						else if (respstr) {
							char *respend;

							if (respstrsz == 0) {
								respstrsz = (n+sizeof(recvbuf));
								*respstr = (char *)malloc(respstrsz);
							}
							else if ((n+respstrlen) >= respstrsz) {
								respstrsz += (n+sizeof(recvbuf));
								*respstr = (char *)realloc(*respstr, respstrsz);
							}
							respend = (*respstr) + respstrlen;
							memcpy(respend, outp, n);
							*(respend + n) = '\0';
							respstrlen += n;
						}
						if (!fullresponse) {
							rdone = (strchr(outp, '\n') == NULL);
						}
					}
				}
				else rdone = 1;
				if (rdone) shutdown(sockfd, SHUT_RD);
			}

			if (!wdone && FD_ISSET(sockfd, &writefds)) {
				/* Send some data */
				res = write(sockfd, msgptr, strlen(msgptr));
				if (res == -1) {
					sprintf(errordetails+strlen(errordetails), "Write error while sending message to Xymon daemon@%s:%d", rcptip, rcptport);
					result = XYMONSEND_EWRITEERROR;
					goto done;
				}
				else {
					dbgprintf("Sent %d bytes\n", res);
					msgptr += res;
					wdone = (strlen(msgptr) == 0);
					if (wdone) shutdown(sockfd, SHUT_WR);
				}
			}
		}
	}

done:
	dbgprintf("Closing connection\n");
	shutdown(sockfd, SHUT_RDWR);
	if (sockfd > 0) close(sockfd);
	xfree(rcptip);
	if (httpmessage) xfree(httpmessage);
	return result;
}
Esempio n. 20
0
/*
 * init the ICMP REDIRECT attack
 */
static int dhcp_spoofing_start(char *args)
{
   struct in_addr ipaddr;
   char *p;
   int i = 1;
  
   DEBUG_MSG("dhcp_spoofing_start");

   if (!strcmp(args, ""))
      SEMIFATAL_ERROR("DHCP spoofing needs a parameter.\n");

   /*
    * Check to see if sniff has started - started automatically in text UI
    */
   if (GBL_UI->type != UI_TEXT && !GBL_SNIFF->active)
      SEMIFATAL_ERROR("DHCP spoofing requires sniffing to be active.\n");
   
   /* check the parameter:
    *
    * ip_pool/netmask/dns
    */
   for (p = strsep(&args, "/"); p != NULL; p = strsep(&args, "/")) {
      /* first parameter (the ip_pool) */
      if (i == 1) {
         char tmp[strlen(p)+4];

         /* add the / to be able to use the target parsing function */
         snprintf(tmp, strlen(p)+4, "/%s//", p);

         if (compile_target(tmp, &dhcp_ip_pool) != E_SUCCESS)
            break;
         
      /* second parameter (the netmask) */
      } else if (i == 2) {
         /* convert from string */
         if (inet_aton(p, &ipaddr) == 0)
            break;
         /* get the netmask */
         ip_addr_init(&dhcp_netmask, AF_INET, (u_char *)&ipaddr);
         
      /* third parameter (the dns server) */
      } else if (i == 3) {
         char tmp[MAX_ASCII_ADDR_LEN];

         /* convert from string */
         if (inet_aton(p, &ipaddr) == 0)
            break;
         /* get the netmask */
         ip_addr_init(&dhcp_dns, AF_INET, (u_char *)&ipaddr);
         
         /* all the parameters were parsed correctly... */
         USER_MSG("DHCP spoofing: using specified ip_pool, netmask %s", ip_addr_ntoa(&dhcp_netmask, tmp));
         USER_MSG(", dns %s\n", ip_addr_ntoa(&dhcp_dns, tmp));
         /* add the hookpoints */
         hook_add(HOOK_PROTO_DHCP_REQUEST, dhcp_spoofing_req);
         hook_add(HOOK_PROTO_DHCP_DISCOVER, dhcp_spoofing_disc);
         /* create the options */
         dhcp_setup_options();

         /* se the pointer to the first ip pool address */
         dhcp_free_ip = LIST_FIRST(&dhcp_ip_pool.ips);
         return E_SUCCESS;
      }
      
      i++;
   }

   /* error parsing the parameter */
   SEMIFATAL_ERROR("DHCP spoofing: parameter number %d is incorrect.\n", i);

   return -E_FATAL;
}
Esempio n. 21
0
void  my_Load_Nets( void ) {
	MYSQL_RES	*res;
	MYSQL_ROW	myrow;
	char		*qbuf, network[21], *mask;
	int		nmask, i = 0, n = 0;
	u_int32_t	nmask2;
	ConfigNets	tmp;
	struct in_addr	inp;
	static time_t	old_time = 0;
	time_t		new_time = 0;

	new_time = time( NULL );
	if ( new_time - old_time < 3600 && my_nets != NULL) return;	// reload every hour
	old_time = new_time;

	my_Clear_Nets();

	qbuf = "select nettype, cmts_ip, cmts_vlan, network, gateway, grant_flag, dynamic_flag, "
		"full_flag, range_min, range_max, lease_time, config_opt1, config_opt2, "
		"config_opt3 from config_nets order by nettype, cmts_ip, cmts_vlan, inet_aton(range_min)";
	SQL_QUERY_RET( qbuf );
	res = mysql_store_result( my_sock );
	if (res == NULL) return;
	num_nets = mysql_num_rows( res );
	if (num_nets == 0) return;
	my_nets = (ConfigNets *) calloc(num_nets +1, sizeof(ConfigNets) );

	while ( myrow = mysql_fetch_row( res ) ) {
		memset( &my_nets[i], 0, sizeof(ConfigNets) );
		strncpy( my_nets[i].s_nettype, (myrow)[0], 7 );
		if (my_nets[i].s_nettype[1] == 'M') my_nets[i].nettype = NET_TYPE_CM;
		if (my_nets[i].s_nettype[1] == 'P') my_nets[i].nettype = NET_TYPE_CPE;
		if (my_nets[i].s_nettype[1] == 'T') my_nets[i].nettype = NET_TYPE_MTA;

		if (cpe_net == 0 && my_nets[i].nettype == NET_TYPE_CPE) cpe_net = i;

		strncpy( my_nets[i].s_cmts_ip, (myrow)[1], 20 );
		inet_aton( (myrow)[1], &inp ); my_nets[i].cmts_ip = inp.s_addr;

		my_nets[i].cmts_vlan = strtoul( (myrow)[2], NULL, 10 );

		strncpy( my_nets[i].s_network, (myrow)[3], 20 );
		strncpy( network, (myrow)[3], 20 );
		nmask = 0;
		mask = network;
		while(*mask != 0) {
			if (*mask == '/') {
				*mask = 0;
				mask++;
				nmask = strtoul( mask, NULL, 10 );
				mask--;
			}
			mask++;
		}
		if (nmask <= 0 || nmask > 30) { nmask = 24; }
		nmask2 = 0xFFFFFFFF << (32 - nmask);

		inet_aton( network, &inp );    my_nets[i].network = inp.s_addr;

		my_nets[i].mask = htonl( nmask2 );

		inet_aton( (myrow)[4], &inp ); my_nets[i].gateway = inp.s_addr;

		if (((myrow)[5][0] & 0x5F) == 'Y') my_nets[i].grant_flag = 1;
		// fprintf(stderr, "grant_flag  %d  %d  %d \n", (myrow)[5][0], ((myrow)[5][0] & 0x5F), 'Y' );

		if (((myrow)[6][0] & 0x5F) == 'Y') my_nets[i].dynamic_flag = CPE_DYNAMIC;

		if (((myrow)[7][0] & 0x5F) == 'Y') my_nets[i].full_flag = 1;

		inet_aton( (myrow)[8], &inp ); my_nets[i].range_min = inp.s_addr;

		inet_aton( (myrow)[9], &inp ); my_nets[i].range_max = inp.s_addr;

		my_nets[i].lease_time = strtoull( (myrow)[10], NULL, 10 );
		my_nets[i].opt1 = strtoul( (myrow)[11], NULL, 10 );
		my_nets[i].opt2 = strtoul( (myrow)[12], NULL, 10 );
		my_nets[i].opt3 = strtoul( (myrow)[13], NULL, 10 );

		/* Check Ranges */
		tmp.network = ntohl( my_nets[i].network );
		tmp.mask = nmask2;
		tmp.gateway = ntohl( my_nets[i].gateway );
		tmp.range_min = ntohl( my_nets[i].range_min );
		tmp.range_max = ntohl( my_nets[i].range_max );

		/* Check Network Address */
		if ( (tmp.network & tmp.mask) != tmp.network) {
			my_syslog( MLOG_ERROR, "dhcp: Load_Nets: " \
				"network address does not match subnet mask (%s %s)",
				(myrow)[1], (myrow)[3] );
			continue;
		}

		/* Calculate Broadcast Address */
		tmp.broadcast = 0xFFFFFFFF;
		tmp.broadcast -= tmp.mask;
		tmp.broadcast += tmp.network;
		my_nets[i].broadcast = htonl( tmp.broadcast );

		/* Check Gateway is in the network */
		if (!((tmp.gateway > tmp.network) && (tmp.broadcast > tmp.gateway))) {
			my_syslog( MLOG_ERROR, "dhcp: Load_Nets: " \
				"gateway address is not in the network specified (%s %s %s)",
				(myrow)[1], (myrow)[3], (myrow)[4] );
			continue;
		}
		/* Check Range_MIN is in the network */
		if (!((tmp.range_min > tmp.network) && (tmp.broadcast > tmp.range_min))) {
			my_syslog( MLOG_ERROR, "dhcp: Load_Nets: " \
				"range_min address is not in the network specified (%s %s %s)",
				(myrow)[1], (myrow)[3], (myrow)[8] );
			continue;
		}
		/* Check Range_MAX is in the network */
		if (!((tmp.range_max > tmp.network) && (tmp.broadcast > tmp.range_max))) {
			my_syslog( MLOG_ERROR, "dhcp: Load_Nets: " \
				"range_max address is not in the network specified (%s %s %s)",
				(myrow)[1], (myrow)[3], (myrow)[9] );
			continue;
		}
		/* Check that the Gateway in not between range min and max */
		if ((tmp.range_min < tmp.gateway) && (tmp.range_max > tmp.gateway)) {
			my_syslog( MLOG_ERROR, "dhcp: Load_Nets: " \
				"gateway address is between range min and max (%s %s %s (%s %s))",
				(myrow)[1], (myrow)[3], (myrow)[4], (myrow)[8], (myrow)[9] );
			continue;
		}
		/* Check that the range max is greater than the range min */
		if (tmp.range_min > tmp.range_max) {
			my_syslog( MLOG_ERROR, "dhcp: Load_Nets: " \
				"range min is greater than range max (%s %s %s %s)",
				(myrow)[1], (myrow)[3], (myrow)[8], (myrow)[9] );
			continue;
		}

		if (my_nets[i].nettype == NET_TYPE_CM) {
			for (n=tmp.range_min; n < tmp.range_max; n++) {
				u_int32_t n_ord = htonl( n );
				if (my_CheckCM_IP( n_ord )) {
					my_nets[i].last_used_ip = n;
					n = tmp.range_max;
				}
			}
		}
                if (my_nets[i].nettype == NET_TYPE_MTA) {
                        for (n=tmp.range_min; n < tmp.range_max; n++) {
                                u_int32_t n_ord = htonl( n );
                                if (my_CheckCM_IP( n_ord )) {
                                        my_nets[i].last_used_ip = n;
                                        n = tmp.range_max;
                                }
                        }
                }
		if (my_nets[i].nettype == NET_TYPE_CPE) {
			for (n=tmp.range_min; n < tmp.range_max; n++) {
				u_int32_t n_ord = htonl( n );
				if (my_CheckCPE_IP( n_ord )) {
					my_nets[i].last_used_ip = n;
					n = tmp.range_max;
				}
			}
		}
		i++;
	}
	mysql_free_result(res);
}
Esempio n. 22
0
int
main (int argc, char *argv[]) {
  char *dictfile = DICT_FILE;
  FILE *dict;
  char word[MAX_WORD_LEN];
  int sock, ret;
  struct in_addr rcvr_addr;
  struct sockaddr_in name;
  struct ip_mreq mreq;
#if BEW
  struct sockaddr_in local;
#endif 
  program_type prog_type = unknown;
  sec_serv_t sec_servs = sec_serv_none;
  unsigned char ttl = 5;
  int c;
  char *input_key = NULL;
  char *address = NULL;
  char key[MAX_KEY_LEN];
  unsigned short port = 0;
  rtp_sender_t snd;
  srtp_policy_t policy;
  err_status_t status;
  int len;
  int do_list_mods = 0;
  uint32_t ssrc = 0xdeadbeef; /* ssrc value hardcoded for now */
#ifdef RTPW_USE_WINSOCK2
  WORD wVersionRequested = MAKEWORD(2, 0);
  WSADATA wsaData;

  ret = WSAStartup(wVersionRequested, &wsaData);
  if (ret != 0) {
    fprintf(stderr, "error: WSAStartup() failed: %d\n", ret);
    exit(1);
  }
#endif

  /* initialize srtp library */
  status = srtp_init();
  if (status) {
    printf("error: srtp initialization failed with error code %d\n", status);
    exit(1);
  }

  /* check args */
  while (1) {
    c = getopt(argc, argv, "k:rsaeld:");
    if (c == -1) {
      break;
    }
    switch (c) {
    case 'k':
      input_key = optarg;
      break;
    case 'e':
      sec_servs |= sec_serv_conf;
      break;
    case 'a':
      sec_servs |= sec_serv_auth;
      break;
    case 'r':
      prog_type = receiver;
      break;
    case 's':
      prog_type = sender;
      break;
    case 'd':
      status = crypto_kernel_set_debug_module(optarg, 1);
      if (status) {
        printf("error: set debug module (%s) failed\n", optarg);
        exit(1);
      }
      break;
    case 'l':
      do_list_mods = 1;
      break;
    default:
      usage(argv[0]);
    }
  }

  if (prog_type == unknown) {
    if (do_list_mods) {
      status = crypto_kernel_list_debug_modules();
      if (status) {
	printf("error: list of debug modules failed\n");
	exit(1);
      }
      return 0;
    } else {
      printf("error: neither sender [-s] nor receiver [-r] specified\n");
      usage(argv[0]);
    }
  }
   
  if ((sec_servs && !input_key) || (!sec_servs && input_key)) {
    /* 
     * a key must be provided if and only if security services have
     * been requested 
     */
    usage(argv[0]);
  }
    
  if (argc != optind + 2) {
    /* wrong number of arguments */
    usage(argv[0]);
  }

  /* get address from arg */
  address = argv[optind++];

  /* get port from arg */
  port = atoi(argv[optind++]);

  /* set address */
#ifdef HAVE_INET_ATON
  if (0 == inet_aton(address, &rcvr_addr)) {
    fprintf(stderr, "%s: cannot parse IP v4 address %s\n", argv[0], address);
    exit(1);
  }
  if (rcvr_addr.s_addr == INADDR_NONE) {
    fprintf(stderr, "%s: address error", argv[0]);
    exit(1);
  }
#else
  rcvr_addr.s_addr = inet_addr(address);
  if (0xffffffff == rcvr_addr.s_addr) {
    fprintf(stderr, "%s: cannot parse IP v4 address %s\n", argv[0], address);
    exit(1);
  }
#endif

  /* open socket */
  sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if (sock < 0) {
    int err;
#ifdef RTPW_USE_WINSOCK2
    err = WSAGetLastError();
#else
    err = errno;
#endif
    fprintf(stderr, "%s: couldn't open socket: %d\n", argv[0], err);
    exit(1);
  }

  name.sin_addr   = rcvr_addr;    
  name.sin_family = PF_INET;
  name.sin_port   = htons(port);
 
  if (ADDR_IS_MULTICAST(rcvr_addr.s_addr)) {
    if (prog_type == sender) {
      ret = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, 
  	               sizeof(ttl));
      if (ret < 0) {
	fprintf(stderr, "%s: Failed to set TTL for multicast group", argv[0]);
	perror("");
	exit(1);
      }
    }

    mreq.imr_multiaddr.s_addr = rcvr_addr.s_addr;
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    ret = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void*)&mreq,
		     sizeof(mreq));
    if (ret < 0) {
      fprintf(stderr, "%s: Failed to join multicast group", argv[0]);
      perror("");
      exit(1);
    }
  }

  /* report security services selected on the command line */
  printf("security services: ");
  if (sec_servs & sec_serv_conf)
    printf("confidentiality ");
  if (sec_servs & sec_serv_auth)
    printf("message authentication");
  if (sec_servs == sec_serv_none)
    printf("none");
  printf("\n");
  
  /* set up the srtp policy and master key */    
  if (sec_servs) {
    /* 
     * create policy structure, using the default mechanisms but 
     * with only the security services requested on the command line,
     * using the right SSRC value
     */
    switch (sec_servs) {
    case sec_serv_conf_and_auth:
      crypto_policy_set_rtp_default(&policy.rtp);
      crypto_policy_set_rtcp_default(&policy.rtcp);
      break;
    case sec_serv_conf:
      crypto_policy_set_aes_cm_128_null_auth(&policy.rtp);
      crypto_policy_set_rtcp_default(&policy.rtcp);      
      break;
    case sec_serv_auth:
      crypto_policy_set_null_cipher_hmac_sha1_80(&policy.rtp);
      crypto_policy_set_rtcp_default(&policy.rtcp);
      break;
    default:
      printf("error: unknown security service requested\n");
      return -1;
    } 
    policy.ssrc.type  = ssrc_specific;
    policy.ssrc.value = ssrc;
    policy.key  = (uint8_t *) key;
    policy.next = NULL;
    policy.rtp.sec_serv = sec_servs;
    policy.rtcp.sec_serv = sec_serv_none;  /* we don't do RTCP anyway */

    /*
     * read key from hexadecimal on command line into an octet string
     */
    len = hex_string_to_octet_string(key, input_key, MASTER_KEY_LEN*2);
    
    /* check that hex string is the right length */
    if (len < MASTER_KEY_LEN*2) {
      fprintf(stderr, 
	      "error: too few digits in key/salt "
	      "(should be %d hexadecimal digits, found %d)\n",
	      MASTER_KEY_LEN*2, len);
      exit(1);    
    } 
    if (strlen(input_key) > MASTER_KEY_LEN*2) {
      fprintf(stderr, 
	      "error: too many digits in key/salt "
	      "(should be %d hexadecimal digits, found %u)\n",
	      MASTER_KEY_LEN*2, (unsigned)strlen(input_key));
      exit(1);    
    }
    
    printf("set master key/salt to %s/", octet_string_hex_string(key, 16));
    printf("%s\n", octet_string_hex_string(key+16, 14));
  
  } else {
    /*
     * we're not providing security services, so set the policy to the
     * null policy
     *
     * Note that this policy does not conform to the SRTP
     * specification, since RTCP authentication is required.  However,
     * the effect of this policy is to turn off SRTP, so that this
     * application is now a vanilla-flavored RTP application.
     */
    policy.key                 = (uint8_t *)key;
    policy.ssrc.type           = ssrc_specific;
    policy.ssrc.value          = ssrc;
    policy.rtp.cipher_type     = NULL_CIPHER;
    policy.rtp.cipher_key_len  = 0; 
    policy.rtp.auth_type       = NULL_AUTH;
    policy.rtp.auth_key_len    = 0;
    policy.rtp.auth_tag_len    = 0;
    policy.rtp.sec_serv        = sec_serv_none;   
    policy.rtcp.cipher_type    = NULL_CIPHER;
    policy.rtcp.cipher_key_len = 0; 
    policy.rtcp.auth_type      = NULL_AUTH;
    policy.rtcp.auth_key_len   = 0;
    policy.rtcp.auth_tag_len   = 0;
    policy.rtcp.sec_serv       = sec_serv_none;   
    policy.next                = NULL;
  }

  if (prog_type == sender) {

#if BEW
    /* bind to local socket (to match crypto policy, if need be) */
    memset(&local, 0, sizeof(struct sockaddr_in));
    local.sin_addr.s_addr = htonl(INADDR_ANY);
    local.sin_port = htons(port);
    ret = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in));
    if (ret < 0) {
      fprintf(stderr, "%s: bind failed\n", argv[0]);
      perror("");
      exit(1); 
    }
#endif /* BEW */

    /* initialize sender's rtp and srtp contexts */
    rtp_sender_init(&snd, sock, name, ssrc); 
    status = srtp_create(&snd.srtp_ctx, &policy);
    if (status) {
      fprintf(stderr, 
	      "error: srtp_create() failed with code %d\n", 
	      status);
      exit(1);
    }
 
    /* open dictionary */
    dict = fopen (dictfile, "r");
    if (dict == NULL) {
      fprintf(stderr, "%s: couldn't open file %s\n", argv[0], dictfile);
      if (ADDR_IS_MULTICAST(rcvr_addr.s_addr)) {
  	leave_group(sock, mreq, argv[0]);
      }
      exit(1);
    }
          
    /* read words from dictionary, then send them off */
    while (fgets(word, MAX_WORD_LEN, dict) != NULL) { 
      len = strlen(word) + 1;  /* plus one for null */
      
      if (len > MAX_WORD_LEN) 
	printf("error: word %s too large to send\n", word);
      else {
	rtp_sendto(&snd, word, len);
        printf("sending word: %s", word);
      }
      usleep(USEC_RATE);
    }
    
  } else  { /* prog_type == receiver */
    rtp_receiver_t rcvr;
        
    if (bind(sock, (struct sockaddr *)&name, sizeof(name)) < 0) {
      close(sock);
      fprintf(stderr, "%s: socket bind error\n", argv[0]);
      perror(NULL);
      if (ADDR_IS_MULTICAST(rcvr_addr.s_addr)) {
    	leave_group(sock, mreq, argv[0]);
      }
      exit(1);
    }

    rtp_receiver_init(&rcvr, sock, name, ssrc);
    status = srtp_create(&rcvr.srtp_ctx, &policy);
    if (status) {
      fprintf(stderr, 
	      "error: srtp_create() failed with code %d\n", 
	      status);
      exit(1);
    }

    /* get next word and loop */
    while (1) {
      len = MAX_WORD_LEN;
      if (rtp_recvfrom(&rcvr, word, &len) > -1)
	printf("\tword: %s", word);
    }
      
  } 

  if (ADDR_IS_MULTICAST(rcvr_addr.s_addr)) {
    leave_group(sock, mreq, argv[0]);
  }

#ifdef RTPW_USE_WINSOCK2
  WSACleanup();
#endif

  return 0;
}
Esempio n. 23
0
int ifconfig_main(int argc, char **argv)
{
	struct ifreq ifr;
	struct sockaddr_in sai;
#ifdef BB_FEATURE_IFCONFIG_HW
	struct sockaddr sa;
#endif
	const struct arg1opt *a1op;
	const struct options *op;
	int sockfd;  /* socket fd we use to manipulate stuff with */
	int goterr;
	int selector;
	char *p;
	char host[128];
	unsigned char mask;
	unsigned char did_flags;

	goterr = 0;
	did_flags = 0;

	/* skip argv[0] */
	++argv;
	--argc;

#ifdef BB_FEATURE_IFCONFIG_STATUS
	if ((argc > 0) && (strcmp(*argv,"-a") == 0)) {
		interface_opt_a = 1;
		--argc;
		++argv;
	}
#endif

	if(argc <= 1) {
#ifdef BB_FEATURE_IFCONFIG_STATUS
		return display_interfaces(argc ? *argv : NULL);
#else
		error_msg_and_die( "ifconfig was not compiled with interface status display support.");
#endif
	}

	/* Create a channel to the NET kernel. */
	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror_msg_and_die("socket");
	}

	/* get interface name */
	safe_strncpy(ifr.ifr_name, *argv, IFNAMSIZ);

	/* Process the remaining arguments. */
	while (*++argv != (char *) NULL) {
		p = *argv;
		mask = N_MASK;
		if (*p == '-') {		/* If the arg starts with '-'... */
			++p;				/*    advance past it and */
			mask = M_MASK;		/*    set the appropriate mask. */
		}
		for (op = OptArray ; op->name ; op++) {	/* Find table entry. */
			if (strcmp(p,op->name) == 0) { /* If name matches... */
				if ((mask &= op->flags)) { /* set the mask and go. */
				    goto FOUND_ARG;;
				}
				/* If we get here, there was a valid arg with an */
				/* invalid '-' prefix. */
				++goterr;
				goto LOOP;
			}
		}
		
		/* We fell through, so treat as possible hostname. */
		a1op = Arg1Opt + (sizeof(Arg1Opt) / sizeof(Arg1Opt[0])) - 1;
		mask = op->arg_flags;
		goto HOSTNAME;

	FOUND_ARG:
		if (mask & ARG_MASK) {
			mask = op->arg_flags;
			a1op = Arg1Opt + (op - OptArray);
			if (mask & A_NETMASK & did_flags) {
				show_usage();
			}
			if (*++argv == NULL) {
				if (mask & A_ARG_REQ) {
					show_usage();
				} else {
					--argv;
					mask &= A_SET_AFTER; /* just for broadcast */
				}
			} else {			/* got an arg so process it */
			HOSTNAME:
				did_flags |= (mask & A_NETMASK);
				if (mask & A_CAST_HOST_COPY) {
#ifdef BB_FEATURE_IFCONFIG_HW
					if (mask & A_CAST_RESOLVE) {
#endif
						safe_strncpy(host, *argv, (sizeof host));
						sai.sin_family = AF_INET;
						sai.sin_port = 0;
						if (!strcmp(host, "default")) {
							/* Default is special, meaning 0.0.0.0. */
							sai.sin_addr.s_addr = INADDR_ANY;
						} else if (inet_aton(host, &sai.sin_addr) == 0) {
							/* It's not a dotted quad. */
							++goterr;
							continue;
						}
						p = (char *) &sai;
#ifdef BB_FEATURE_IFCONFIG_HW
					} else { /* A_CAST_HOST_COPY_IN_ETHER */
						/* This is the "hw" arg case. */
						if (strcmp("ether", *argv) || (*++argv == NULL)) {
							show_usage();
						}
						safe_strncpy(host, *argv, (sizeof host));
						if (in_ether(host, &sa)) {
							fprintf(stderr, "invalid hw-addr %s\n", host);
							++goterr;
							continue;
						}
						p = (char *) &sa;
					}
#endif
					memcpy((((char *)(&ifr)) + a1op->ifr_offset),
						   p, sizeof(struct sockaddr));
				} else {
					unsigned int i = strtoul(*argv,NULL,0);
					p = ((char *)(&ifr)) + a1op->ifr_offset;
#ifdef BB_FEATURE_IFCONFIG_MEMSTART_IOADDR_IRQ
					if (mask & A_MAP_TYPE) {
						if (ioctl(sockfd, SIOCGIFMAP, &ifr) < 0) {
							++goterr;
							continue;
						}
						if ((mask & A_MAP_UCHAR) == A_MAP_UCHAR) {
							*((unsigned char *) p) = i;
						} else if (mask & A_MAP_USHORT) {
							*((unsigned short *) p) = i;
						} else {
							*((unsigned long *) p) = i;
						}
					} else
#endif
					if (mask & A_CAST_CHAR_PTR) {
						*((caddr_t *) p) = (caddr_t) i;
					} else { /* A_CAST_INT */
						*((int *) p) = i;
					}
				}
						
				if (ioctl(sockfd, a1op->selector, &ifr) < 0) {
					perror(a1op->name);
					++goterr;
					continue;
				}

#ifdef QUESTIONABLE_ALIAS_CASE
				if (mask & A_COLON_CHK) {
					/*
					 * Don't do the set_flag() if the address is an alias with
					 * a - at the end, since it's deleted already! - Roman
					 *
					 * Should really use regex.h here, not sure though how well
					 * it'll go with the cross-platform support etc. 
					 */
					char *ptr;
					short int found_colon = 0;
					for (ptr = ifr.ifr_name; *ptr; ptr++ ) {
						if (*ptr == ':') {
							found_colon++;
						}
					}
			
					if (found_colon && *(ptr - 1) == '-') {
						continue;
					}
				}
#endif
			}
			if (!(mask & A_SET_AFTER)) {
				continue;
			}
			mask = N_SET;
		}

		if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
			perror("SIOCGIFFLAGS"); 
			++goterr;
		} else {
			selector = op->selector;
			if (mask & SET_MASK) {
				ifr.ifr_flags |= selector;
			} else {
				ifr.ifr_flags &= ~selector;
			}
			if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
				perror("SIOCSIFFLAGS"); 
				++goterr;
			}
		}
	LOOP:
	} /* end of while-loop */

	return goterr;
}

#ifdef BB_FEATURE_IFCONFIG_HW
/* Input an Ethernet address and convert to binary. */
static int
in_ether(char *bufp, struct sockaddr *sap)
{
	unsigned char *ptr;
	int i, j;
	unsigned char val;
	unsigned char c;
	
	sap->sa_family = ARPHRD_ETHER;
	ptr = sap->sa_data;
	
	for (i = 0 ; i < ETH_ALEN ; i++) {
		val = 0;

		/* We might get a semicolon here - not required. */
		if (i && (*bufp == ':')) {
			bufp++;
		}

		for (j=0 ; j<2 ; j++) {
			c = *bufp;
			if (c >= '0' && c <= '9') {
				c -= '0';
			} else if (c >= 'a' && c <= 'f') {
				c -= ('a' - 10);
			} else if (c >= 'A' && c <= 'F') {
				c -= ('A' - 10);
			} else if (j && (c == ':' || c == 0)) {
				break;
			} else {
				return -1;
			}
			++bufp;
			val <<= 4;
			val += c;
		}
		*ptr++ = val;
	}

	return (int) (*bufp);		/* Error if we don't end at end of string. */
}
Esempio n. 24
0
int main(int argc, char* argv[])
{
    struct sigaction action;
    action.sa_handler = handle_pipe;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    sigaction(SIGPIPE, &action, NULL);
    int sockconn;
    struct sockaddr_in servaddr;
    if ((sockconn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
        perror("socket failure");
        exit(EXIT_FAILURE);
    }

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(8888);
    if (inet_aton(argv[1], &servaddr.sin_addr) == 0)
    {
        perror("inet_aton error");
        exit(EXIT_FAILURE);
    }

    if (connect(sockconn, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
    {
        perror("connnect error");
        exit(EXIT_FAILURE);
    }
    char recvbuf[1024] = {0};
    char sendbuf[1024] = {0};
    while(1){
        memset(recvbuf, 0, sizeof(recvbuf));
        memset(sendbuf, 0, sizeof(sendbuf));
        char * tmp = fgets(sendbuf, sizeof(sendbuf), stdin); // 键入EOF时,fgets返回一个空指针
        //fputs("fget from stdin\n", stderr);
        if (tmp != NULL)
        {
            //fputs("write to socket\n", stderr);
            if (write(sockconn, sendbuf, 1) < 0)
            {
                perror("write to socket error");
                exit(EXIT_FAILURE);
            }
            if (write(sockconn, sendbuf + 1 , strlen(sendbuf) - 1) < 0)
            {
                perror("write to socket error");
                exit(EXIT_FAILURE);
            }
        }
        else // 键入EOF时也返回空指针
        {
            fputs("get EOF\n", stderr);
            break;
        }
        //fputs("read from connfd\n", stderr);
        int ret = read(sockconn, recvbuf, sizeof(recvbuf));
        if (ret != 0)
            fputs(recvbuf, stdout);
        else if (ret == 0) // 已经写往服务器了,所以应该收到数据,如果返回0,说明服务器已经过早终止了
        {
            perror("str_cli: server terminated prematurely");
            exit(EXIT_FAILURE);
        }
        else
        {
            perror("read error");
            exit(EXIT_FAILURE);
        }
    }
    close(sockconn); // 这里即使不close,在进程关闭的时候,仍然会会关闭
    return 0;
}
Esempio n. 25
0
int connect_server(char* ip, unsigned short port)
{
    int fd, rc;
    struct sockaddr_in addr = {0};
    msg_t* msg;
    int flag = 1;

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        perror("socket");
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    if (inet_aton(ip, &addr.sin_addr) == 0)
    {
        SYSLOG(LOG_ERR, "Convert ip address error!");
        close(fd);
        return -1;
    }

    rc = connect(fd, (struct sockaddr*)&addr, sizeof(addr));
    if (rc == -1)
    {
        perror("connect");
        close(fd);
        return -1;
    }

    if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag)) == -1)
    {
        perror("setsockopt");
    }

    msg = new_login_msg(this.localip, 0, 1);
    if (msg)
    {
        write_n(fd, msg, sizeof(msg_t) + msg_data_length(msg));
        pool_room_free(&this.pool, MSG_ROOM_IDX);
        if (read_msg_t(fd, &msg, 5) > 0)
        {
            unsigned int ip;
            unsigned char mask;
            if (msg->compress != this.compress || msg->encrypt != this.encrypt)
            {
                SYSLOG(LOG_ERR, "compress algorithm or encrypt algorithm is not same");
                pool_room_free(&this.pool, RECV_ROOM_IDX);
                goto end;
            }
            if (!parse_login_reply_msg(msg, &ip, &mask)) goto end;
            pool_room_free(&this.pool, RECV_ROOM_IDX);
            if (ip == 0)
            {
                SYSLOG(LOG_ERR, "Not enough ip address");
                goto end;
            }
            if (ip != this.localip)
            {
                struct in_addr a;
                char saddr[16], daddr[16];
                a.s_addr = this.localip;
                strcpy(saddr, inet_ntoa(a));
                a.s_addr = ip;
                strcpy(daddr, inet_ntoa(a));
                SYSLOG(LOG_ERR, "%s is inuse, but %s is not inuse", saddr, daddr);
                goto end;
            }
            this.netmask = mask;
            this.keepalive = time(NULL);
            return fd;
        }
        SYSLOG(LOG_ERR, "read sys_login_reply message timeouted");
        goto end;
    }
    SYSLOG(LOG_ERR, "Can not create login message");
end:
    close(fd);
    return -1;
}
Esempio n. 26
0
int ifconfig_main(int argc, char **argv)
{
	struct ifreq ifr;
	struct sockaddr_in sai;
#ifdef CONFIG_FEATURE_IPV6
	struct sockaddr_in6 sai6;
#endif
#ifdef CONFIG_FEATURE_IFCONFIG_HW
	struct sockaddr sa;
#endif
	const struct arg1opt *a1op;
	const struct options *op;
	int sockfd;			/* socket fd we use to manipulate stuff with */
	int goterr;
	int selector;
#ifdef CONFIG_FEATURE_IFCONFIG_BROADCAST_PLUS
	unsigned int mask;
	unsigned int did_flags;
	unsigned int sai_hostname, sai_netmask;
#else
	unsigned char mask;
	unsigned char did_flags;
#endif
	char *p;
	char host[128];

	goterr = 0;
	did_flags = 0;
#ifdef CONFIG_FEATURE_IFCONFIG_BROADCAST_PLUS
	sai_hostname = 0;
	sai_netmask = 0;
#endif

	/* skip argv[0] */
	++argv;
	--argc;

#ifdef CONFIG_FEATURE_IFCONFIG_STATUS
	if ((argc > 0) && (((*argv)[0] == '-') && ((*argv)[1] == 'a') && !(*argv)[2])) {
		interface_opt_a = 1;
		--argc;
		++argv;
	}
#endif

	if (argc <= 1) {
#ifdef CONFIG_FEATURE_IFCONFIG_STATUS
		return display_interfaces(argc ? *argv : NULL);
#else
		bb_error_msg_and_die
			("ifconfig was not compiled with interface status display support.");
#endif
	}

	/* Create a channel to the NET kernel. */
	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		bb_perror_msg_and_die("socket");
	}

	/* get interface name */
	safe_strncpy(ifr.ifr_name, *argv, IFNAMSIZ);

	/* Process the remaining arguments. */
	while (*++argv != (char *) NULL) {
		p = *argv;
		mask = N_MASK;
		if (*p == '-') {	/* If the arg starts with '-'... */
			++p;		/*    advance past it and */
			mask = M_MASK;	/*    set the appropriate mask. */
		}
		for (op = OptArray; op->name; op++) {	/* Find table entry. */
			if (strcmp(p, op->name) == 0) {	/* If name matches... */
				if ((mask &= op->flags)) {	/* set the mask and go. */
					goto FOUND_ARG;;
				}
				/* If we get here, there was a valid arg with an */
				/* invalid '-' prefix. */
				++goterr;
				goto LOOP;
			}
		}

		/* We fell through, so treat as possible hostname. */
		a1op = Arg1Opt + (sizeof(Arg1Opt) / sizeof(Arg1Opt[0])) - 1;
		mask = op->arg_flags;
		goto HOSTNAME;

	  FOUND_ARG:
		if (mask & ARG_MASK) {
			mask = op->arg_flags;
			a1op = Arg1Opt + (op - OptArray);
			if (mask & A_NETMASK & did_flags) {
				bb_show_usage();
			}
			if (*++argv == NULL) {
				if (mask & A_ARG_REQ) {
					bb_show_usage();
				} else {
					--argv;
					mask &= A_SET_AFTER;	/* just for broadcast */
				}
			} else {	/* got an arg so process it */
			  HOSTNAME:
				did_flags |= (mask & (A_NETMASK|A_HOSTNAME));
				if (mask & A_CAST_HOST_COPY) {
#ifdef CONFIG_FEATURE_IFCONFIG_HW
					if (mask & A_CAST_RESOLVE) {
#endif
#ifdef CONFIG_FEATURE_IPV6
						char *prefix;
						int prefix_len = 0;
#endif

						safe_strncpy(host, *argv, (sizeof host));
#ifdef CONFIG_FEATURE_IPV6
						if ((prefix = strchr(host, '/'))) {
							if (safe_strtoi(prefix + 1, &prefix_len) ||
								(prefix_len < 0) || (prefix_len > 128))
							{
								++goterr;
								goto LOOP;
							}
							*prefix = 0;
						}
#endif

						sai.sin_family = AF_INET;
						sai.sin_port = 0;
						if (!strcmp(host, bb_INET_default)) {
							/* Default is special, meaning 0.0.0.0. */
							sai.sin_addr.s_addr = INADDR_ANY;
#ifdef CONFIG_FEATURE_IFCONFIG_BROADCAST_PLUS
						} else if (((host[0] == '+') && !host[1]) && (mask & A_BROADCAST) &&
								   (did_flags & (A_NETMASK|A_HOSTNAME)) == (A_NETMASK|A_HOSTNAME)) {
							/* + is special, meaning broadcast is derived. */
							sai.sin_addr.s_addr = (~sai_netmask) | (sai_hostname & sai_netmask);
#endif
#ifdef CONFIG_FEATURE_IPV6
						} else if (inet_pton(AF_INET6, host, &sai6.sin6_addr) > 0) {
							int sockfd6;
							struct in6_ifreq ifr6;

							memcpy((char *) &ifr6.ifr6_addr,
								   (char *) &sai6.sin6_addr,
								   sizeof(struct in6_addr));

							/* Create a channel to the NET kernel. */
							if ((sockfd6 = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
								bb_perror_msg_and_die("socket6");
							}
							if (ioctl(sockfd6, SIOGIFINDEX, &ifr) < 0) {
								perror("SIOGIFINDEX");
								++goterr;
								continue;
							}
							ifr6.ifr6_ifindex = ifr.ifr_ifindex;
							ifr6.ifr6_prefixlen = prefix_len;
							if (ioctl(sockfd6, a1op->selector, &ifr6) < 0) {
								perror(a1op->name);
								++goterr;
							}
							continue;
#endif
						} else if (inet_aton(host, &sai.sin_addr) == 0) {
							/* It's not a dotted quad. */
							struct hostent *hp;
							if ((hp = gethostbyname(host)) == (struct hostent *)NULL) {
								++goterr;
								continue;
							}
							memcpy((char *) &sai.sin_addr, (char *) hp->h_addr_list[0],
							sizeof(struct in_addr));
						}
#ifdef CONFIG_FEATURE_IFCONFIG_BROADCAST_PLUS
						if (mask & A_HOSTNAME) {
							sai_hostname = sai.sin_addr.s_addr;
						}
						if (mask & A_NETMASK) {
							sai_netmask = sai.sin_addr.s_addr;
						}
#endif
						p = (char *) &sai;
#ifdef CONFIG_FEATURE_IFCONFIG_HW
					} else {	/* A_CAST_HOST_COPY_IN_ETHER */
						/* This is the "hw" arg case. */
						if (strcmp("ether", *argv) || (*++argv == NULL)) {
							bb_show_usage();
						}
						safe_strncpy(host, *argv, (sizeof host));
						if (in_ether(host, &sa)) {
							bb_error_msg("invalid hw-addr %s", host);
							++goterr;
							continue;
						}
						p = (char *) &sa;
					}
#endif
					memcpy((((char *) (&ifr)) + a1op->ifr_offset),
						   p, sizeof(struct sockaddr));
				} else {
					unsigned int i = strtoul(*argv, NULL, 0);

					p = ((char *) (&ifr)) + a1op->ifr_offset;
#ifdef CONFIG_FEATURE_IFCONFIG_MEMSTART_IOADDR_IRQ
					if (mask & A_MAP_TYPE) {
						if (ioctl(sockfd, SIOCGIFMAP, &ifr) < 0) {
							++goterr;
							continue;
						}
						if ((mask & A_MAP_UCHAR) == A_MAP_UCHAR) {
							*((unsigned char *) p) = i;
						} else if (mask & A_MAP_USHORT) {
							*((unsigned short *) p) = i;
						} else {
							*((unsigned long *) p) = i;
						}
					} else
#endif
					if (mask & A_CAST_CHAR_PTR) {
						*((caddr_t *) p) = (caddr_t) i;
					} else {	/* A_CAST_INT */
						*((int *) p) = i;
					}
				}

				if (ioctl(sockfd, a1op->selector, &ifr) < 0) {
					perror(a1op->name);
					++goterr;
					continue;
				}
#ifdef QUESTIONABLE_ALIAS_CASE
				if (mask & A_COLON_CHK) {
					/*
					 * Don't do the set_flag() if the address is an alias with
					 * a - at the end, since it's deleted already! - Roman
					 *
					 * Should really use regex.h here, not sure though how well
					 * it'll go with the cross-platform support etc.
					 */
					char *ptr;
					short int found_colon = 0;

					for (ptr = ifr.ifr_name; *ptr; ptr++) {
						if (*ptr == ':') {
							found_colon++;
						}
					}

					if (found_colon && *(ptr - 1) == '-') {
						continue;
					}
				}
#endif
			}
			if (!(mask & A_SET_AFTER)) {
				continue;
			}
			mask = N_SET;
		}

		if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
			perror("SIOCGIFFLAGS");
			++goterr;
		} else {
			selector = op->selector;
			if (mask & SET_MASK) {
				ifr.ifr_flags |= selector;
			} else {
				ifr.ifr_flags &= ~selector;
			}
			if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
				perror("SIOCSIFFLAGS");
				++goterr;
			}
		}
	  LOOP:
		continue;
	}					/* end of while-loop */

	return goterr;
}
Esempio n. 27
0
gint
g_inet_aton(char *buf, struct in_addr *a)
{
  return inet_aton(buf, a);
}
Esempio n. 28
0
/*
        Инициализируем структуру одного потока, обрабатывающего MAX_PTH_CLIENTS клиентов
*/
PTINF *InitPTINF()
{
        PTINF *pinf;
        SADDR **addr;
        int sock_d;
        int i;
        SADDR srv;
        socklen_t sl;
        int fl;
        
        sock_d = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if(sock_d <= 0){
                perror("Error to create socket");
                return NULL;
        }
        srv.sin_family = AF_INET;
        if(inet_aton(SERVER_IP, &srv.sin_addr) < 0){
                printf("Erro ip "SERVER_IP"\n");
                return NULL;
        }
        sl = SADDR_SIZE;
        /*
                Поиск свободного порта
                Перебираем порты от START_PORT + MAX_RERTY до START_PORT
        */
        fl = MAX_RERTY;
        while(fl >= 0){
                srv.sin_port = htons(START_PORT + fl);
                if(bind(sock_d, (struct sockaddr *) &srv, sl) < 0){
                        fl--;
                        continue;
                }
                fl = -5;                
        }       
        if(fl != -5){
                perror("Error of bind socket");
                return NULL;
        }     
        
        
        pinf = malloc(sizeof(PTINF));
        if(pinf == NULL){
                return NULL;
        }
        addr = malloc(sizeof(SADDR *) * MAX_PTH_CLIENTS);
        if(addr == NULL){
                free(pinf);
                return NULL;
        }
        for(i = 0; i < MAX_PTH_CLIENTS; i++){
                addr[i] = NULL;
                pinf->cqueu[i] = -1;
        }
        CopySADDR(srv, &pinf->srv);
        pinf->mfl = MFL_JOB;
        pinf->mfl_type = MFL_JOB;
        pinf->addr = addr;
        pinf->sock_d = sock_d;
        pinf->clients = 0;
        pinf->nclients = 0;
        
        return pinf;
}
Esempio n. 29
0
/****************************************************************************
 *
 * NAME:
 *
 * DESCRIPTION:
 *
 * PARAMETERS:      Name            RW  Usage
 * None.
 *
 * RETURNS:
 * None.
 *
 * NOTES:
 * None.
 ****************************************************************************/
 void connect_to_client()
 {
	
	unsigned char buf[1024];
	unsigned char r_server[40];
	unsigned char state;
	unsigned int  pingInterval=500, pingCount=0, timeCount=0;
	
	memset((char *) &remaddr, 0, sizeof(remaddr));
	remaddr.sin_family = AF_INET;
	remaddr.sin_port = htons(they.publicPORT);
	
	
	sprintf(r_server,"%d.%d.%d.%d",they.publicIP[0],they.publicIP[1],they.publicIP[2],they.publicIP[3]);
	
	if (inet_aton(r_server, &remaddr.sin_addr)==0) {
		fprintf(stderr, "inet_aton() failed\n");
		exit(1);
	}
	
	
	pthread_t thread_chat;
	pthread_create( &thread_chat, NULL, chat_read, NULL);
	
	
	while(1)
	{
		usleep(100);
		timeCount++;
		
		if(timeCount % pingInterval == 0)
		{
			
			memset(buf,0,sizeof(buf));
			buf[0] = PACKET_PING;
			sendto(fd, buf, 4, 0, (struct sockaddr *)&remaddr, slen);
			
			timeCount = 0;
			connection_timeout++;
			if(connection_timeout > 10)
			{
				printf("Connectin lost !!\n\r");
				exit(0);
			}
		}
				
		struct timeval t_v;
		t_v.tv_sec = 0;  t_v.tv_usec = 1; 
		setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&t_v,sizeof(struct timeval));
		
		recvlen = recvfrom(fd, buf, BUFLEN, 0,NULL,NULL);
        
        if (recvlen > 0) 
        {
			state = peer_parser(buf, recvlen);
			if(state == PACKET_PING)
			{
				memset(buf,0,sizeof(buf));
				buf[0] = PACKET_PONG;
				sendto(fd, buf, 4, 0, (struct sockaddr *)&remaddr, slen);
			}
			else if(state == PACKET_PONG)
			{
				connection_timeout = 0;
			}
			else if(state == PACKET_CHAT)
			{
				if(strncmp(&buf[4],"GET",3) == 0)
				{
					printf("Got File get command\n");
					struct stat finfo;
					char *filename = (char*) "sendfile.txt";
					struct file_property_t file_property;
					unsigned char *data_send = buf;
					if (-1 == stat(filename, &finfo))
					 	fprintf(stderr,"error stating file!\n");
					printf("File '%s' of size '%d' bytes opened and ready to send filename\n", filename, (int)finfo.st_size );
					memset(buf,0,sizeof(buf));
					
					buf[0] = PACKET_FILE;
					data_send = data_send + 4;
					data_send += snprintf(data_send,1,"%c",START_PACKET);
					file_property.size = (int)finfo.st_size;
					file_property.data_packet_size = 512;
					sprintf(file_property.file_name,"%s",filename);
					memcpy(data_send,&file_property,sizeof(struct file_property_t));
					data_send += sizeof(struct file_property_t);
					sendto(fd, buf, (int)(data_send - buf), 0, (struct sockaddr *)&remaddr, slen);
				}
				else
					printf("Friend: %s\n\r",&buf[4]);
			}
			else if(state == PACKET_FILE)
			{
				printf("Packet for File\n\r");
				file_parser_ret = file_packet_parser(&buf[PACKET_STATE_HEADER_BYTES], recvlen - PACKET_STATE_HEADER_BYTES);
				send_file_ack(buf,file_parser_ret,recvlen);
			}
			memset(buf,0,sizeof(buf));
        }
        
        
	}
 }
Esempio n. 30
0
int ifconfig(char *name, int flags, char *addr, char *netmask)
{
	// char *down="down";
	// if (flags == IFUP)
	// down = "up";
	cprintf("ifconfig %s = %s/%s\n", name, addr, netmask);
	if (!ifexists(name)) {
		cprintf("interface %s does not exists, ignoring\n", name);
		return -1;
	}
	// if (addr==NULL)
	// addr="0.0.0.0";
	// int ret;
	// if (netmask==NULL)
	// {
	// ret = eval("ifconfig",name,addr,down);
	// }else
	// {
	// ret = eval("ifconfig",name,addr,"netmask",netmask,down);
	// }
	int s;
	struct ifreq ifr;
	struct in_addr in_addr, in_netmask, in_broadaddr;

	cprintf("ifconfig(): name=[%s] flags=[%s] addr=[%s] netmask=[%s]\n",
		name, flags == IFUP ? "IFUP" : "0", addr, netmask);

	if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
		goto err;
	cprintf("ifconfig(): socket opened\n");

	strncpy(ifr.ifr_name, name, IFNAMSIZ);
	cprintf("ifconfig(): set interface name\n");
	if (flags) {
		ifr.ifr_flags = flags;
		if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0)
			goto err;
	}
	cprintf("ifconfig(): interface flags configured\n");
	if (addr) {
		inet_aton(addr, &in_addr);
		sin_addr(&ifr.ifr_addr).s_addr = in_addr.s_addr;
		ifr.ifr_addr.sa_family = AF_INET;
		if (ioctl(s, SIOCSIFADDR, &ifr) < 0)
			goto err;
	}
	cprintf("ifconfig() ip configured\n");

	if (addr && netmask) {
		inet_aton(netmask, &in_netmask);
		sin_addr(&ifr.ifr_netmask).s_addr = in_netmask.s_addr;
		ifr.ifr_netmask.sa_family = AF_INET;
		if (ioctl(s, SIOCSIFNETMASK, &ifr) < 0)
			goto err;

		in_broadaddr.s_addr =
		    (in_addr.s_addr & in_netmask.s_addr) | ~in_netmask.s_addr;
		sin_addr(&ifr.ifr_broadaddr).s_addr = in_broadaddr.s_addr;
		ifr.ifr_broadaddr.sa_family = AF_INET;
		if (ioctl(s, SIOCSIFBRDADDR, &ifr) < 0)
			goto err;
	}
	cprintf("ifconfig() mask configured\n");

	close(s);
	cprintf("ifconfig() done()\n");
	return 0;

err:
	cprintf("ifconfig() done with error\n");
	close(s);
#ifndef HAVE_SILENCE
	perror(name);
#endif
	return errno;
	// return ret;
}