Пример #1
0
// configure bridge structure
// - extract ip address and mask from the bridge interface
void net_configure_bridge(Bridge *br, char *dev_name) {
	assert(br);
	assert(dev_name);

	br->dev = dev_name;

	// check the bridge device exists
	char sysbridge[30 + strlen(br->dev)];
	sprintf(sysbridge, "/sys/class/net/%s/bridge", br->dev);
	struct stat s;
	int rv = stat(sysbridge, &s);
	if (rv == 0) {
		// this is a bridge device
		br->macvlan = 0;
	}
	else {
		// is this a regular Ethernet interface
		if (if_nametoindex(br->dev) > 0) {
			br->macvlan = 1;
			char *newname;
			if (asprintf(&newname, "%s-%u", br->devsandbox, getpid()) == -1)
				errExit("asprintf");
			br->devsandbox = newname;
		}			
		else {
			fprintf(stderr, "Error: cannot find network device %s\n", br->dev);
			exit(1);
		}
	}

	// allow unconfigured interfaces
	if (net_get_if_addr(br->dev, &br->ip, &br->mask, br->mac, &br->mtu)) {
		fprintf(stderr, "Warning: the network interface %s is not configured\n", br->dev);
		br->configured = 1;
		br->arg_ip_none = 1;
		return;
	}
	if (arg_debug) {
		if (br->macvlan == 0)
			printf("Bridge device %s at %d.%d.%d.%d/%d\n",
				br->dev, PRINT_IP(br->ip), mask2bits(br->mask));
		else
			printf("macvlan parent device %s at %d.%d.%d.%d/%d\n",
				br->dev, PRINT_IP(br->ip), mask2bits(br->mask));
	}
	
	uint32_t range = ~br->mask + 1;		  // the number of potential addresses
	// this software is not supported for /31 networks
	if (range < 4) {
		fprintf(stderr, "Error: the software is not supported for /31 networks\n");
		exit(1);
	}
	br->configured = 1;
}
Пример #2
0
static void print_br(FILE *fp, RcpInterface *intf) {
	ifcnt++;
	char ip[16];
	*ip = '\0';
	char mask[3];
	*mask = '\0';
	if (intf->ip) {
		sprintf(ip, "%d.%d.%d.%d", RCP_PRINT_IP(intf->ip));
		sprintf(mask, "%d", mask2bits(intf->mask));
	}
	char mtu[10];
	*mtu = '\0';
	if (intf->mtu == 0)
		strcpy(mtu, "1500");
	else
		sprintf(mtu, "%d", intf->mtu);

	fprintf(fp, strif1,
		intf->name, ifcnt, ifcnt, intf->name,
		ifcnt, ifcnt, "bridge", 
		ifcnt, ifcnt, ip,
		ifcnt, ifcnt, mask,
		ifcnt, ifcnt, mtu);

	char *cb = "checked";
	if (intf->admin_up)
		cb = "";
	fprintf(fp, strif2,
		ifcnt, ifcnt, cb);

	fprintf(fp, "%s", strif3);
}
Пример #3
0
void update_rt_summary(uint32_t area_id) {

	OspfArea *area = areaFind(area_id);
	if (area == NULL)
		return;
	
	// do everything else
	OspfLsa *lsa = lsadbGetList(area_id, LSA_TYPE_SUM_NET);
	while (lsa != NULL) {
		if (lsa->h.nexthop) {
			uint32_t mask = ntohl(lsa->u.net.mask);
			uint32_t ip = ntohl(lsa->header.link_state_id);
			ip &= mask;
			rcpLog(muxsock, RCP_PROC_OSPF, RLOG_DEBUG, RLOG_FC_OSPF_SPF,
				"adding inter-area route %d.%d.%d.%d/%d via %d.%d.%d.%d, cost %u, output interface %d.%d.%d.%d\n",
				RCP_PRINT_IP(ip),
				mask2bits(mask),
				RCP_PRINT_IP(lsa->h.nexthop),
				lsa->h.cost,
				RCP_PRINT_IP(lsa->h.outhop));

			RT *rt = route_add(ip, mask, 0, lsa->h.nexthop, lsa->h.cost, RT_OSPF_IA);
			if (rt != NULL) {
				rt->area_id = area_id;
				rt->ifip = lsa->h.outhop;
				rt->del_flag = 0;
			}
		}

		lsa = lsa->h.next;
	}
}
Пример #4
0
static void print_lo(FILE *fp, RcpInterface *intf) {
	ifcnt++;
	char ip[16];
	*ip = '\0';
	char mask[3];
	*mask = '\0';
	if (intf->ip) {
		sprintf(ip, "%d.%d.%d.%d", RCP_PRINT_IP(intf->ip));
		sprintf(mask, "%d", mask2bits(intf->mask));
	}
	char mtu[10];
	*mtu = '\0';
	if (intf->mtu == 0)
		strcpy(mtu, "16436");
	else
		sprintf(mtu, "%d", intf->mtu);

	char *vname = intf->name;
	if (rcpInterfaceVirtual(intf->name)) {
		vname = strchr(intf->name, ':');
		vname++;
	}
		
	fprintf(fp, strif1,
		intf->name, ifcnt, ifcnt, vname,
		ifcnt, ifcnt, "loopback", 
		ifcnt, ifcnt, ip,
		ifcnt, ifcnt, mask,
		ifcnt, ifcnt, mtu);
	fprintf(fp, "%s", strif3);
}
Пример #5
0
static void del_blackhole(uint32_t ip, uint32_t mask) {
	char cmd[100];
	sprintf(cmd, "ip route del blackhole %d.%d.%d.%d/%d",
		RCP_PRINT_IP(ip), mask2bits(mask));
	int v = system(cmd);
	if (v == -1)
		ASSERT(0);
}
Пример #6
0
static void print_ipv4(FILE *f, const struct tc_u32_key *key)
{
	char abuf[256];

	switch (key->off) {
	case 0:
		switch (ntohl(key->mask)) {
		case 0x0f000000:
			fprintf(f, "\n  match IP ihl %u",
				ntohl(key->val) >> 24);
			return;
		case 0x00ff0000:
			fprintf(f, "\n  match IP dsfield %#x",
				ntohl(key->val) >> 16);
			return;
		}
		break;
	case 8:
		if (ntohl(key->mask) == 0x00ff0000) {
			fprintf(f, "\n  match IP protocol %d",
				ntohl(key->val) >> 16);
			return;
		}
		break;
	case 12:
	case 16: {
			int bits = mask2bits(key->mask);

			if (bits >= 0) {
				fprintf(f, "\n  %s %s/%d",
					key->off == 12 ? "match IP src" : "match IP dst",
					inet_ntop(AF_INET, &key->val,
						  abuf, sizeof(abuf)),
					bits);
				return;
			}
		}
		break;

	case 20:
		switch (ntohl(key->mask)) {
		case 0x0000ffff:
			fprintf(f, "\n  match dport %u",
				ntohl(key->val) & 0xffff);
			return;
		case 0xffff0000:
			fprintf(f, "\n  match sport %u",
				ntohl(key->val) >> 16);
			return;
		case 0xffffffff:
			fprintf(f, "\n  match dport %u, match sport %u",
				ntohl(key->val) & 0xffff,
				ntohl(key->val) >> 16);

			return;
		}
		/* XXX: Default print_raw */
	}
Пример #7
0
bool video::init_window(int sizex, int sizey)
{
    assert(win_hInstance != 0);
    g_sizex = sizex; g_sizey = sizey;
    if( !WinInit(win_hInstance, win_iCmdShow, gWndClass, title, false) )
        return DisplayError("Unable to initialize the program's window.");
    running = true;
    if( !DDInit() ) {
        DestroyDDraw();
        goto fail;
    }
    if( !DDOverlayInit() || !DrawOverlay() ) {
        DestroyOverlay();
        DestroyDDraw();
        goto fail;
    }
    DDPIXELFORMAT PixelFormat; memset(&PixelFormat, 0, sizeof(PixelFormat)); PixelFormat.dwSize = sizeof(PixelFormat);
    g_pDDSOverlay->GetPixelFormat(&PixelFormat);
    mask2bits(PixelFormat.dwRBitMask, red_mask, red_shift);
    mask2bits(PixelFormat.dwGBitMask, green_mask, green_shift);
    mask2bits(PixelFormat.dwBBitMask, blue_mask, blue_shift);
    if(PixelFormat.dwFlags == DDPF_RGB)
         depth = char(PixelFormat.dwRGBBitCount);
    else depth = -char(PixelFormat.dwFourCC);
    for(int i = 0, e = sizex * sizey * PixelFormat.dwRGBBitCount / 32, c = get_color(0, 0, 0); i < e; i++)
        g_pImg[i] = c; // clear surface
    ShowWindow(g_hAppWnd, SW_SHOW);
    g_hVSync = CreateThread (
        NULL,          // LPSECURITY_ATTRIBUTES security_attrs
        0,             // SIZE_T stacksize
        (LPTHREAD_START_ROUTINE) thread_vsync,
        this,               // argument
        0, 0);
    SetPriorityClass(g_hVSync, IDLE_PRIORITY_CLASS); // questionable
    return true;
fail:
    g_pImg = new unsigned int[g_sizex * g_sizey];
    return false;
}
Пример #8
0
// assign a random IP address and check it
// the address needs to be in the range if it --iprange was specified
static uint32_t arp_random(const char *dev, Bridge *br) {
    assert(dev);
    assert(br);
    uint32_t ifip = br->ip;
    uint32_t ifmask = br->mask;
    assert(ifip);
    assert(ifmask);

    if (arg_debug)
        printf("ARP-scan %s, %d.%d.%d.%d/%d\n",
               dev, PRINT_IP(ifip), mask2bits(ifmask));

    // determine the range based on network address
    uint32_t range = ~ifmask + 1; // the number of potential addresses
    // this software is not supported for /31 networks
    if (range < 4)
        return 0; // the user will have to set the IP address manually
    range -= 2; // subtract the network address and the broadcast address
    uint32_t start = (ifip & ifmask) + 1;

    // adjust range based on --iprange params
    if (br->iprange_start && br->iprange_end) {
        start = br->iprange_start;
        range = br->iprange_end - br->iprange_start;
    }

    if (arg_debug)
        printf("IP address range from %d.%d.%d.%d to %d.%d.%d.%d\n",
               PRINT_IP(start), PRINT_IP(start + range));

    // generate a random address - 10 tries
    uint32_t dest = 0;
    int i = 0;
    for (i = 0; i < 10; i++) {
        dest = start + ((uint32_t) rand()) % range;
        if (dest == ifip)	// do not allow the interface address
            continue;		// try again

        // if we've made it up to here, we have a valid address
        break;
    }
    if (i == 10)	// we failed 10 times
        return 0;

    // check address
    uint32_t rv = arp_check(dev, dest, ifip);
    if (!rv)
        return dest;
    return 0;
}
Пример #9
0
void update_rt_connected(uint32_t area_id) {
	OspfArea *area = areaFind(area_id);
	if (area) {
		OspfNetwork *net = area->network;
		while (net != NULL) {
			uint32_t ip = net->ip & net->mask;
			rcpLog(muxsock, RCP_PROC_OSPF, RLOG_DEBUG, RLOG_FC_OSPF_SPF,
				"adding connected route %d.%d.%d.%d/%d via %d.%d.%d.%d, cost %u",
				RCP_PRINT_IP(ip),
				mask2bits(net->mask),
				RCP_PRINT_IP(net->ip),
				net->cost);
			route_add(net->ip & net->mask, net->mask, 0, net->ip, net->cost, RT_CONNECTED, area_id, net->ip);
			net = net->next;
		}
	}
}
Пример #10
0
static int get_netmask(unsigned *val, const char *arg, int base)
{
	inet_prefix addr;

	if (!get_unsigned(val, arg, base))
		return 0;

	/* try coverting dotted quad to CIDR */
	if (!get_addr_1(&addr, arg, AF_INET) && addr.family == AF_INET) {
		int b = mask2bits(addr.data[0]);
		
		if (b >= 0) {
			*val = b;
			return 0;
		}
	}

	return -1;
}
Пример #11
0
void rxneigh_update(void) {
	// update local neighbor list
	RipNeighbor *neigh = neighbors;
	while (neigh != NULL) {
		RipNeighbor *next = neigh->next;
		if (++neigh->rx_time > RIP_ROUTE_TIMEOUT)
			remove_neighbor(neigh);
		neigh = next;
	}

	// update shm neighbor list
	if (--shm_update_timeout <= 0) {
		shm_update_timeout = RIP_UPDATE_SHM_TIMEOUT;

		// lock http
		shm->stats.rip_active_locked = 1;
		neigh = neighbors;
		int i = 0;
		while (neigh != NULL) {
			RcpActiveNeighbor *an = &shm->stats.rip_active[i];
			an->valid = 0;
			an->area = 0;
			an->router_id = 0;
			RcpInterface *intf = rcpFindInterfaceByLPM(shm, neigh->ip);
			if (intf) {
				an->network = intf->ip & intf->mask;
				an->netmask_cnt = mask2bits(intf->mask);
				an->if_ip = intf->ip;
				an->ip = neigh->ip;
				an->valid = 1;
				i++;
			}
			neigh = neigh->next;
		}
		
		// clear remaining active neighbors
		for (; i < RCP_ACTIVE_NEIGHBOR_LIMIT; i++)
			shm->stats.rip_active[i].valid = 0;
	}
	shm->stats.rip_active_locked = 0;
}
Пример #12
0
static void print_route(const char *fname) {
	FILE *fp = fopen(fname, "r");
	if (!fp)
		return;
	
	printf("  Route table:\n");
	char buf[MAXBUF];
	while (fgets(buf, MAXBUF, fp)) {
		// remove blanks, \n
		char *ptr = buf;
		while (*ptr == ' ' || *ptr == '\t')
			ptr++;
		char *start = ptr;
		if (*start == '\0')
			continue;
		ptr = strchr(ptr, '\n');
		if (ptr)
			*ptr = '\0';

		// remove table header
		//Iface	Destination	Gateway 	Flags	RefCnt	Use	Metric	Mask		MTU	Window	IRTT
		if (strncmp(start, "Iface", 5) == 0)
			continue;

		// extract data
		char ifname[64];
		char destination[64];
		char gateway[64];
		char flags[64];
		char refcnt[64];
		char use[64];
		char metric[64];
		char mask[64];
		int rv = sscanf(start, "%s %s %s %s %s %s %s %s\n", ifname, destination, gateway, flags, refcnt, use, metric, mask);
		if (rv != 8)
			continue;
		
		// destination ip
		uint32_t destip;
		sscanf(destination, "%x", &destip);
		destip = ntohl(destip);
		uint32_t destmask;
		sscanf(mask, "%x", &destmask);
		destmask = ntohl(destmask);
		uint32_t gw;
		sscanf(gateway, "%x", &gw);
		gw = ntohl(gw);
		
//		printf("#%s# #%s# #%s# #%s# #%s# #%s# #%s# #%s#\n", ifname, destination, gateway, flags, refcnt, use, metric, mask);
		if (gw != 0)
			printf("     %u.%u.%u.%u/%u via %u.%u.%u.%u, dev %s, metric %s\n",
				PRINT_IP(destip), mask2bits(destmask),
				PRINT_IP(gw),
				ifname,
				metric);
		else { // this is an interface
			IfList *ifentry = list_find(destip, destmask);
			if (ifentry) {
				printf("     %u.%u.%u.%u/%u, dev %s, scope link src %d.%d.%d.%d\n",
					PRINT_IP(destip), mask2bits(destmask),
					ifname,
					PRINT_IP(ifentry->ip));
			}
		}
	}
	
	fclose(fp);

}
Пример #13
0
// remove all routes with del_flag set; this is done at the end of SPF cycle
static int callback_clear(PTN *ptn, void *arg) {
	ASSERT(ptn != NULL);

	int i;
	int deleted = 0;
	for (i = 0; i < RCP_OSPF_ECMP_LIMIT; i++) {
		RT *rt = &ptn->rt[i];
//printf("callback delete %d.%d.%d.%d/%d via %d.%d.%d.%d, cost %u, type %s, del_flag %u\n",	
//RCP_PRINT_IP(rt->ip),
//mask2bits(rt->mask),
//RCP_PRINT_IP(rt->gw),
//rt->cost,
//rcpRouteType(rt->type),
//rt->del_flag);
		if (rt->type == RT_NONE)
			break;
		if (!rt->del_flag)
			continue;

//printf("delete route %d.%d.%d.%d/%d via %d.%d.%d.%d, cost %u\n",	
//RCP_PRINT_IP(rt->ip),
//mask2bits(rt->mask),
//RCP_PRINT_IP(rt->gw),
//rt->cost);
		rcpLog(muxsock, RCP_PROC_OSPF, RLOG_DEBUG, RLOG_FC_OSPF_SPF,
			"deleting route %d.%d.%d.%d/%d via %d.%d.%d.%d, cost %u",
			RCP_PRINT_IP(rt->ip),
			mask2bits(rt->mask),
			RCP_PRINT_IP(rt->gw),
			rt->cost);
		ecmp_del(ptn);
		deleted = 1;
		
		memset(rt, 0, sizeof(RT));
		route_del_cnt++;
		
		// shift the rest of the array so we don't leave any holes
		if (i != (RCP_OSPF_ECMP_LIMIT - 1)) {
			memcpy(&ptn->rt[i], &ptn->rt[i + 1], (RCP_OSPF_ECMP_LIMIT - 1 - i) * sizeof(RT));
			memset(&ptn->rt[RCP_OSPF_ECMP_LIMIT - 1], 0, sizeof(RT));
		}
	}
	
	if (deleted) {
		ecmp_add(ptn);
	}
	
	// check retry flag, it is possible we have some more ecmp routes here
	if (ptn->retry_ecmp) {
		// count the number of ecmp routes installed
		int cnt = 0;
		for (i = 0; i < RCP_OSPF_ECMP_LIMIT; i++) {
			if (ptn->rt[i].type == RT_NONE)
				break;
			cnt++;
		}
		
		// if there is room to add more,
		if (cnt < RCP_OSPF_ECMP_LIMIT) {
			// trigger a new spf calculation
			spfTrigger();
		}
		ptn->retry_ecmp = 0;
	}
		
	return 0;
}
Пример #14
0
// scan interfaces in current namespace and print IP address/mask for each interface
void net_ifprint(void) {
	uint32_t ip;
	uint32_t mask;
	struct ifaddrs *ifaddr, *ifa;

	if (getifaddrs(&ifaddr) == -1)
		errExit("getifaddrs");

	printf("%-17.17s%-19.19s%-17.17s%-17.17s%-6.6s\n",
		"Interface", "MAC", "IP", "Mask", "Status");
	// walk through the linked list
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET) {
			struct sockaddr_in *si = (struct sockaddr_in *) ifa->ifa_netmask;
			mask = ntohl(si->sin_addr.s_addr);
			si = (struct sockaddr_in *) ifa->ifa_addr;
			ip = ntohl(si->sin_addr.s_addr);

			// interface status
			char *status;
			if (ifa->ifa_flags & IFF_RUNNING && ifa->ifa_flags & IFF_UP)
				status = "UP";
			else
				status = "DOWN";

			// ip address and mask
			char ipstr[30];
			sprintf(ipstr, "%d.%d.%d.%d", PRINT_IP(ip));
			char maskstr[30];
			sprintf(maskstr, "%d.%d.%d.%d", PRINT_IP(mask));
			
			// mac address
			unsigned char mac[6];
			net_get_mac(ifa->ifa_name, mac);
			char macstr[30];
			if (strcmp(ifa->ifa_name, "lo") == 0)
				macstr[0] = '\0';
			else
				sprintf(macstr, "%02x:%02x:%02x:%02x:%02x:%02x", PRINT_MAC(mac));

			// print				
			printf("%-17.17s%-19.19s%-17.17s%-17.17s%-6.6s\n",
				ifa->ifa_name, macstr, ipstr, maskstr, status);

			// network scanning
			if (!arg_scan)				// scanning disabled
				continue;
			if (strcmp(ifa->ifa_name, "lo") == 0)	// no loopbabck scanning
				continue;
			if (mask2bits(mask) < 16)		// not scanning large networks
				continue;
			if (!ip)					// if not configured
				continue;
			// only if the interface is up and running
			if (ifa->ifa_flags & IFF_RUNNING && ifa->ifa_flags & IFF_UP)
				arp_scan(ifa->ifa_name, ip, mask);
		}
	}
	freeifaddrs(ifaddr);
}
Пример #15
0
// standard ACL
int cliAclIcmpCmd(CliMode mode, int argc, char **argv) {
	char *data = (char *) pktout + sizeof(RcpPkt);
	*data = '\0';
	
	//
	// store incoming data in a temporary structure
	//
	RcpAclIcmp in;
	memset(&in, 0, sizeof(RcpAclIcmp));
	
	// no form
	int noform = 0;
	int index = 1;
	if (strcmp(argv[0], "no") == 0) {
		noform = 1;
		index++;
	}
		
	// list number
	uint8_t list_number = atoi(argv[index++]);
	
	// action
	uint8_t action;
	if (strcmp(argv[index++], "deny") == 0)
		action = RCPACL_ACTION_DENY;
	else
		action = RCPACL_ACTION_PERMIT;
	
	// mac address
	uint8_t mac[6];
	if (atomac(argv[index], mac) == 0) {
		memcpy(in.mac, mac, 6);
		index++;
	}
	else

	// skip "icmp"
	index++;

	// source address
	if (strcmp(argv[index], "any") == 0)
		;
	else {
		uint32_t ip;
		uint32_t mask;
		if (atocidr(argv[index], &ip, &mask)) {
			sprintf(data, "Error: invalid source IP address\n");
			return RCPERR;
		}
		uint8_t mask_bits = mask2bits(mask);
		in.ip = ip;
		in.mask_bits = mask_bits;
	}
	index++;
	
	// destination address/output interface
	if (strcmp(argv[index], "any") == 0)
		;
	else {
		uint32_t ip;
		uint32_t mask;
		if (atocidr(argv[index], &ip, &mask)) {
			sprintf(data, "Error: invalid destination IP address\n");
			return RCPERR;
		}
		uint8_t mask_bits = mask2bits(mask);
		in.dest_ip = ip;
		in.dest_mask_bits = mask_bits;
	}
	index++;

	// icmp type
	if ((argc - 1) == index)
		in.icmp_type = atoi(argv[index]);
	
	//
	// process acl
	//
	
	// find if this is an existing acl
	RcpAcl *found = acl_find(&in, RCP_ACL_TYPE_ICMP, action, list_number);
	
	// process command
	if (noform) {
		if (found == NULL)
			return 0;
			
		// remove acl
		found->valid = 0;
	}
	else {
		// already there?
		if (found != NULL)
			return 0;

		// allocate new acl
		RcpAcl *newacl = acl_find_empty();
		if (newacl == NULL) {
			strcpy(data, "Error: cannot configure ACL entry, limit reached");
			return RCPERR;
		}

		// copy the data
		memcpy(&newacl->u.icmp, &in, sizeof(RcpAclIcmp));
		newacl->valid = 1;
		newacl->type = RCP_ACL_TYPE_ICMP;
		newacl->action = action;
		newacl->list_number = list_number;
	}		
		
	// trigger netfilter configuration update
	netfilter_update = 2; 
	
	return 0;
}
Пример #16
0
// extended ACL
int cliAclCmd(CliMode mode, int argc, char **argv) {
	char *data = (char *) pktout + sizeof(RcpPkt);
	*data = '\0';
	
	//
	// store incoming data in a temporary structure
	//
	RcpAclExtended in;
	memset(&in, 0, sizeof(RcpAclExtended));
	
	// no form
	int noform = 0;
	int index = 1;
	if (strcmp(argv[0], "no") == 0) {
		noform = 1;
		index++;
	}
		
	// list number
	uint8_t list_number = atoi(argv[index++]);
	
	// action
	uint8_t action;
	if (strcmp(argv[index++], "deny") == 0)
		action = RCPACL_ACTION_DENY;
	else
		action = RCPACL_ACTION_PERMIT;
	

	// mac address
	uint8_t mac[6];
	if (atomac(argv[index], mac) == 0) {
		memcpy(in.mac, mac, 6);
		index++;
	}

	// protocol
	if (isnum(argv[index]))
		in.protocol = atoi(argv[index++]);
	else if (strcmp(argv[index], "tcp") == 0) {
		in.protocol = RCPACL_PROTOCOL_TCP;
		index++;
	}
	else if (strcmp(argv[index], "udp") == 0) {
		in.protocol = RCPACL_PROTOCOL_UDP;
		index++;
	}
	else
		in.protocol = RCPACL_PROTOCOL_ANY;
		
	// source address
	if (strcmp(argv[index], "any") == 0)
		;
	else {
		uint32_t ip;
		uint32_t mask;
		if (atocidr(argv[index], &ip, &mask)) {
			sprintf(data, "Error: invalid source IP address\n");
			return RCPERR;
		}
		uint8_t mask_bits = mask2bits(mask);
		in.ip = ip;
		in.mask_bits = mask_bits;
	}
	index++;
	
	// source port
	if (isnum(argv[index]))
		in.port = atoi(argv[index++]);
	
	// destination address/output interface
	if (strcmp(argv[index], "any") == 0)
		;
	else if (strcmp(argv[index], "out-interface") == 0) {
		strncpy(in.out_interface, argv[index + 1], RCP_MAX_IF_NAME);
		index++;
	}
	else {
		uint32_t ip;
		uint32_t mask;
		if (atocidr(argv[index], &ip, &mask)) {
			sprintf(data, "Error: invalid destination IP address\n");
			return RCPERR;
		}
		uint8_t mask_bits = mask2bits(mask);
		in.dest_ip = ip;
		in.dest_mask_bits = mask_bits;
	}
	index++;

	// destination port
	if (index < argc && isnum(argv[index]))
		in.dest_port = atoi(argv[index++]);
	
	// connection state
	if (index < argc) {
		// parsing
		char *str = argv[index];
		char *ptr = strtok(str, ",");
		in.constate = 0;
		while(ptr != NULL) {
			if (strcmp(ptr, "new") == 0)
				in.constate |= RCP_ACL_CONSTATE_NEW;
			else if (strcmp(ptr, "established") == 0)
				in.constate |= RCP_ACL_CONSTATE_ESTABLISHED;
			else if (strcmp(ptr, "related") == 0)
				in.constate |= RCP_ACL_CONSTATE_RELATED;
			else if (strcmp(ptr, "invalid") == 0)
				in.constate |= RCP_ACL_CONSTATE_INVALID;
			else {
				sprintf(data, "Error: invalid connecton state\n");
				return RCPERR;
			}
			
			ptr = strtok(NULL, ",");
		}
	} // this should be the last one, argv was modified by strtok


	//
	// process acl
	//
	
	// find if this is an existing acl
	RcpAcl *found = acl_find(&in, RCP_ACL_TYPE_EXTENDED, action, list_number);
	
	// process command
	if (noform) {
		if (found == NULL)
			return 0;
			
		// remove acl
		found->valid = 0;
	}
	else {
		// already there?
		if (found != NULL)
			return 0;

		// allocate new acl
		RcpAcl *newacl = acl_find_empty();
		if (newacl == NULL) {
			strcpy(data, "Error: cannot configure ACL entry, limit reached");
			return RCPERR;
		}

		// copy the data
		memcpy(&newacl->u.extended, &in, sizeof(RcpAclExtended));
		newacl->valid = 1;
		newacl->type = RCP_ACL_TYPE_EXTENDED;
		newacl->action = action;
		newacl->list_number = list_number;
	}		
		
	// trigger netfilter configuration update
	netfilter_update = 2; 
	
	return 0;
}
Пример #17
0
bool video::init_window(int xsize, int ysize)
{
    { //enclose local variables before fail label
    g_sizex = xsize; g_sizey = ysize;

    // Open the display
    if (!dpy) {
        dpy = XOpenDisplay(display_name);
        if (!dpy) {
            fprintf(stderr, "Can't open X11 display %s\n", XDisplayName(display_name));
            goto fail;
        }
    }
    int theScreen = DefaultScreen(dpy);
    scrn = ScreenOfDisplay(dpy, theScreen);
    dispdepth = DefaultDepth(dpy, theScreen);
    XVisualInfo vinfo;
    if (!( (dispdepth >= 15 && dispdepth <= 32 && XMatchVisualInfo(dpy, theScreen, dispdepth, TrueColor, &vinfo) )
        || XMatchVisualInfo(dpy, theScreen, 24, TrueColor, &vinfo)
        || XMatchVisualInfo(dpy, theScreen, 32, TrueColor, &vinfo)
        || XMatchVisualInfo(dpy, theScreen, 16, TrueColor, &vinfo)
        || XMatchVisualInfo(dpy, theScreen, 15, TrueColor, &vinfo)
        )) {
        fprintf(stderr, "Display has no appropriate True Color visual\n");
        goto fail;
    }
    vis = vinfo.visual;
    depth = dispdepth = vinfo.depth;
    mask2bits(vinfo.red_mask, red_mask, red_shift);
    mask2bits(vinfo.green_mask, green_mask, green_shift);
    mask2bits(vinfo.blue_mask, blue_mask, blue_shift);
    rootW = RootWindow(dpy, theScreen);
    cmap = XCreateColormap(dpy, rootW, vis, AllocNone);
    XSetWindowAttributes attrs;
    attrs.backing_store = Always;
    attrs.colormap = cmap;
    attrs.event_mask = StructureNotifyMask|KeyPressMask|ButtonPressMask|ButtonReleaseMask;
    attrs.background_pixel = BlackPixelOfScreen(scrn);
    attrs.border_pixel = WhitePixelOfScreen(scrn);
    win = XCreateWindow(dpy, rootW,
        0, 0, xsize, ysize, 2,
        dispdepth, InputOutput, vis,
        CWBackingStore | CWColormap | CWEventMask |
        CWBackPixel | CWBorderPixel,
        &attrs);
    if(!win) {
        fprintf(stderr, "Can't create the window\n");
        goto fail;
    }
    XSizeHints sh;
    sh.flags = PSize | PMinSize | PMaxSize;
    sh.width = sh.min_width = sh.max_width = xsize;
    sh.height = sh.min_height = sh.max_height = ysize;
    XSetStandardProperties( dpy, win, g_video->title, g_video->title, None, NULL, 0, &sh );
    _XA_WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", false);
    XSetWMProtocols(dpy, win, &_XA_WM_DELETE_WINDOW, 1);
    gc = XCreateGC(dpy, win, 0L, &xgcv);
    XMapRaised(dpy, win);
    XFlush(dpy);
#ifdef X_FULLSYNC
	XSynchronize(dpy, true);
#endif
    XSetErrorHandler(xerr_handler);

    int imgbytes = xsize*ysize*(dispdepth<=16?2:4);
    const char *vidstr;
#ifndef X_NOSHMEM
    int major, minor, pixmaps;
    if(XShmQueryExtension(dpy) &&
       XShmQueryVersion(dpy, &major, &minor, &pixmaps))
    { // Shared memory
        if(NULL!=getenv(NOSHMEM_env_var_name) && 0!=strcmp("0",getenv(NOSHMEM_env_var_name))) {
            goto generic;
        }
        shmseginfo.shmid = shmget(IPC_PRIVATE, imgbytes, IPC_CREAT|0777);
        if(shmseginfo.shmid < 0) {
            fprintf(stderr, "Warning: Can't get shared memory: %s\n", strerror(errno));
            goto generic;
        }
        g_pImg = (unsigned int*)(shmseginfo.shmaddr = (char*)shmat(shmseginfo.shmid, 0, 0));
        if(g_pImg == (unsigned int*)-1) {
            fprintf(stderr, "Warning: Can't attach to shared memory: %s\n", strerror(errno));
            shmctl(shmseginfo.shmid, IPC_RMID, NULL);
            goto generic;
        }
        shmseginfo.readOnly = false;
        if(!XShmAttach(dpy, &shmseginfo) || x_error) {
            char err[256]; XGetErrorText(dpy, x_error, err, 255);
            fprintf(stderr, "Warning: Can't attach shared memory to display: %s (%d)\n", err, x_error);
            shmdt(shmseginfo.shmaddr); shmctl(shmseginfo.shmid, IPC_RMID, NULL);
            goto generic;
        }
        already_called_X_ShmAttach = true;

#ifndef X_NOSHMPIX
        if(pixmaps && XShmPixmapFormat(dpy) == ZPixmap)
        { // Pixmaps
            vidtype = 2; vidstr = "X11 shared memory pixmap";
            pixmap = XShmCreatePixmap(dpy, win, (char*)g_pImg, &shmseginfo, xsize, ysize, dispdepth);
            XSetWindowBackgroundPixmap(dpy, win, pixmap);
        } else
#endif//!X_NOSHMPIX
        { // Standard
            vidtype = 1; vidstr = "X11 shared memory";
            ximage = XShmCreateImage(dpy, vis, dispdepth,
                ZPixmap, 0, &shmseginfo, xsize, ysize);
            if(!ximage) {
                fprintf(stderr, "Can't create the shared image\n");
                goto fail;
            }
            assert(ximage->bytes_per_line == xsize*(dispdepth<=16?2:4));
            ximage->data = shmseginfo.shmaddr;
        }
    } else
#endif
    {
#ifndef X_NOSHMEM
generic:
#endif
        vidtype = 0; vidstr = "generic X11";
        g_pImg = new unsigned int[imgbytes/sizeof(int)];
        ximage = XCreateImage(dpy, vis, dispdepth, ZPixmap, 0, (char*)g_pImg, xsize, ysize, 32, imgbytes/ysize);
        if(!ximage) {
            fprintf(stderr, "Can't create the image\n");
            goto fail;
        }
    }
    // Note: It may be more efficient to adopt the server's byte order
    //       and swap once per get_color() call instead of once per pixel.
    const uint32_t probe = 0x03020100;
    const bool big_endian = (((const char*)(&probe))[0]==0x03);
    ximage->byte_order = big_endian ? MSBFirst : LSBFirst;

    printf("Note: using %s with %s visual for %d-bit color depth\n", vidstr, vis==DefaultVisual(dpy, theScreen)?"default":"non-default", dispdepth);
    running = true;
    return true;
    } // end of enclosing local variables
fail:
    terminate(); init_console();
    return false;
}
Пример #18
0
static int read_routes(void)
{
	struct route_struct *route, *temp;
	char buffer[1023], iface[16], net_addr[64], gate_addr[64], mask_addr[64];
	int n, iflags, refcnt, use, metric, mss, window;
	struct in_addr address;
	unsigned long int netmask;
	unsigned long int network;
	FILE *fp;

	if (first_route != NULL) {
		route = first_route;
		
		while (route != NULL) {
			temp = route->next;
			free(route);
			route = temp;
		}

		first_route = NULL;
	}
	
	if ((fp = fopen(PROC_IP_ROUTE_FILE, "r")) == NULL) {
		if (logging)
			syslog(LOG_ERR, "error cannot open %s\n", PROC_IP_ROUTE_FILE);
		return FALSE;
	}

	while (fgets(buffer, 1023, fp) != NULL) {
		n = sscanf(buffer, "%s %s %s %X %d %d %d %s %d %d\n",
			iface, net_addr, gate_addr, &iflags, &refcnt, &use,
			&metric, mask_addr, &mss, &window);

		if (n != 10)
			continue;

		address.s_addr = htonl(hex2intrev(net_addr));
		netmask        = mask2bits(hex2intrev(mask_addr));

		network = inet_netof(address);
		
		if (network == 0 || network == 127) {
			if (debug && logging)
				syslog(LOG_DEBUG, "rejecting route to %s/%ld - should not be propogated\n", inet_ntoa(address), netmask);
			continue;
		}

		if (route_restrict) {
			if (inet_netof(address) != 44) {
				if (debug && logging)
					syslog(LOG_DEBUG, "rejecting route to %s/%ld - not ampr.org\n", inet_ntoa(address), netmask);
				continue;
			}
		}

		if ((route = malloc(sizeof(struct route_struct))) == NULL) {
			if (logging)
				syslog(LOG_ERR, "out of memory !\n");
			return FALSE;
		}

		route->addr   = address;
		route->bits   = netmask;
		route->metric = metric;
		route->action = (iflags & RTF_DYNAMIC) ? ORIG_ROUTE : FIXED_ROUTE;

		route->next = first_route;
		first_route = route;
	}
	
	fclose(fp);
	
	return TRUE;
}
Пример #19
0
// print IP addresses for all interfaces
static void net_ifprint(void) {
	uint32_t ip;
	uint32_t mask;
	struct ifaddrs *ifaddr, *ifa;

	if (getifaddrs(&ifaddr) == -1)
		errExit("getifaddrs");

	// walk through the linked list
	printf("  Link status:\n");
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		if (ifa->ifa_addr->sa_family == AF_PACKET) {
			if (ifa->ifa_flags & IFF_RUNNING && ifa->ifa_flags & IFF_UP) {
				if (ifa->ifa_data != NULL) {
					struct rtnl_link_stats *stats = ifa->ifa_data;
					printf("     %s UP - tx/rx: %u/%u packets,  %u/%u bytes\n",
						ifa->ifa_name, 
						stats->tx_packets, stats->rx_packets,
						stats->tx_bytes, stats->rx_bytes);
				}
			}
			else
				printf("     %s DOWN\n", ifa->ifa_name);
		}			
	}


	// walk through the linked list
	printf("  IPv4 status:\n");
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET) {
			struct sockaddr_in *si = (struct sockaddr_in *) ifa->ifa_netmask;
			mask = ntohl(si->sin_addr.s_addr);
			si = (struct sockaddr_in *) ifa->ifa_addr;
			ip = ntohl(si->sin_addr.s_addr);

			char *status;
			if (ifa->ifa_flags & IFF_RUNNING && ifa->ifa_flags & IFF_UP)
				status = "UP";
			else
				status = "DOWN";

			printf("     %s %s, %d.%d.%d.%d/%u\n",
				ifa->ifa_name, status, PRINT_IP(ip), mask2bits(mask));
		}
	}


	// walk through the linked list
	printf("  IPv6 status:\n");
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET6) {
			char host[NI_MAXHOST];
			int s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6),
				host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
			if (s == 0) {
				char *ptr;
				if ((ptr = strchr(host, '%')) != NULL)
					*ptr = '\0';
				char *status;
				if (ifa->ifa_flags & IFF_RUNNING && ifa->ifa_flags & IFF_UP)
					status = "UP";
				else
					status = "DOWN";

				printf("     %s %s, %s\n", ifa->ifa_name, status, host);
			}
		}
	}

	freeifaddrs(ifaddr);
}
Пример #20
0
int cliIpRouteCidrCmd(CliMode mode, int argc, char **argv) {
	char *data = (char *) pktout + sizeof(RcpPkt);
	*data = '\0';

	// extract data
	uint32_t ip;
	uint32_t mask;
	if (atocidr(argv[2], &ip, &mask)) {
		strcpy(data, "Error: invalid IP address\n");
		return RCPERR;
	}

	// this should be a network address
	if (ip & (~mask)) {
		strcpy(data, "Error: invalid IP address\n");
		return RCPERR;
	}

	uint32_t gw;
	if (atoip(argv[3], &gw)) {
		strcpy(data, "Error: invalid next hop address\n");
		return RCPERR;
	}
	
	uint32_t metric = 1;
	if (argc == 5)
		metric = atoi(argv[4]);

	// test RIP distance
	if (metric == RCP_ROUTE_DISTANCE_RIP) {
		sprintf(data, "Error: Administrative distance %d is reserved for RIP\n", RCP_ROUTE_DISTANCE_RIP);
		return RCPERR;
	}

	// test OSPF distance
	if (metric == RCP_ROUTE_DISTANCE_OSPF) {
		sprintf(data, "Error: Administrative distance %d is reserved for OSPF\n", RCP_ROUTE_DISTANCE_OSPF);
		return RCPERR;
	}

	// add the route
	RcpStaticRoute *rt;
	if ((rt  = shm_find_route_static(ip, mask, gw)) != NULL) {
		// a route is already present in the kernel with a different metric
		// delete the old route first
		rcpDelRoute(muxsock, ip, mask, gw);
		rcpLog(muxsock, RCP_PROC_ROUTER, RLOG_INFO, RLOG_FC_ROUTER,
			"static route %d.%d.%d.%d/%d gateway %d.%d.%d.%d deleted",
			RCP_PRINT_IP(ip), mask2bits(mask), RCP_PRINT_IP(gw));
		redistribute_route(SIOCDELRT, ip, mask, gw, rt->metric);
		rt->metric = metric;
		strcpy(data, "Warning: route replaced\n");
	}
	else if ((rt  = shm_find_route_static(ip, mask, 0)) != NULL && rt->metric == metric) {
		// we are in an equal cost multipath (ECMP) case - not supported yet!
		// delete the old route first
		rcpDelRoute(muxsock, rt->ip, rt->mask, rt->gw);
		rcpLog(muxsock, RCP_PROC_ROUTER, RLOG_INFO, RLOG_FC_ROUTER,
			"static route %d.%d.%d.%d/%d gateway %d.%d.%d.%d deleted",
			RCP_PRINT_IP(ip), mask2bits(mask), RCP_PRINT_IP(gw));
		redistribute_route(SIOCDELRT, ip, mask, gw, rt->metric);
		rt->gw = gw;
		strcpy(data, "Warning: existing route with a different destination deleted\n");
	}
	else {
		// create a new route
		rt = shm_find_route_empty();
		if (rt == NULL) {
			sprintf(data, "Error: cannot add route, limit reached\n");
			return RCPERR;
		}
		memset(rt, 0, sizeof(RcpStaticRoute));
		rt->ip = ip;
		rt->mask = mask;
		rt->gw = gw;
		rt->metric = metric;
		rt->valid = 1;
		rt->type = RCP_ROUTE_STATIC;
	}


	rcpAddRoute(muxsock, RCP_ROUTE_STATIC, ip, mask, gw, metric);
	redistribute_route(SIOCADDRT, ip, mask, gw, metric);

	return 0;
}
Пример #21
0
// print IP addresses for all interfaces
static void net_ifprint(void) {
	uint32_t ip;
	uint32_t mask;
	struct ifaddrs *ifaddr, *ifa;

	int fd;
	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		fprintf(stderr, "Error: cannot open AF_INET socket\n");
		exit(1);
	}

	if (getifaddrs(&ifaddr) == -1)
		errExit("getifaddrs");

	// walk through the linked list
	printf("  Link status:\n");
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		if (ifa->ifa_addr->sa_family == AF_PACKET) {
			if (ifa->ifa_flags & IFF_RUNNING && ifa->ifa_flags & IFF_UP) {
				if (ifa->ifa_data != NULL) {
					struct rtnl_link_stats *stats = ifa->ifa_data;

					// extract mac address
					struct ifreq ifr;
					memset(&ifr, 0, sizeof(ifr));
					strncpy(ifr.ifr_name,  ifa->ifa_name, IFNAMSIZ);
					int rv = ioctl (fd, SIOCGIFHWADDR, &ifr);
					
					if (rv == 0)
						printf("     %s UP, %02x:%02x:%02x:%02x:%02x:%02x\n",
							ifa->ifa_name, PRINT_MAC((unsigned char *) &ifr.ifr_hwaddr.sa_data));
					else
						printf("     %s UP\n", ifa->ifa_name);
					
					printf("          tx/rx: %u/%u packets,  %u/%u bytes\n",
						stats->tx_packets, stats->rx_packets,
						stats->tx_bytes, stats->rx_bytes);
				}
			}
			else
				printf("     %s DOWN\n", ifa->ifa_name);
		}			
	}


	// walk through the linked list
	printf("  IPv4 status:\n");
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET) {
			struct sockaddr_in *si = (struct sockaddr_in *) ifa->ifa_netmask;
			mask = ntohl(si->sin_addr.s_addr);
			si = (struct sockaddr_in *) ifa->ifa_addr;
			ip = ntohl(si->sin_addr.s_addr);

			char *status;
			if (ifa->ifa_flags & IFF_RUNNING && ifa->ifa_flags & IFF_UP)
				status = "UP";
			else
				status = "DOWN";

			printf("     %s %s, %d.%d.%d.%d/%u\n",
				ifa->ifa_name, status, PRINT_IP(ip), mask2bits(mask));
		}
	}


	// walk through the linked list
	printf("  IPv6 status:\n");
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET6) {
			char host[NI_MAXHOST];
			int s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6),
				host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
			if (s == 0) {
				char *ptr;
				if ((ptr = strchr(host, '%')) != NULL)
					*ptr = '\0';
				char *status;
				if (ifa->ifa_flags & IFF_RUNNING && ifa->ifa_flags & IFF_UP)
					status = "UP";
				else
					status = "DOWN";

				printf("     %s %s, %s\n", ifa->ifa_name, status, host);
			}
		}
	}

	freeifaddrs(ifaddr);
	close(fd);
}