#include "main.h"

/* creates a raw socket for the [devicename], returns the socket or -1 on error */
int rawsock_create(char *devicename)
{
	struct ifreq req;
	struct sockaddr_ll addr;
	int rawsock;
/*	int opts;*/

	if ((rawsock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
		fprintf(stderr, "Error - can't create raw socket on interface %s: %s \n", devicename, strerror(errno));
		return -1;
	}

	strncpy(req.ifr_name, devicename, IFNAMSIZ);

	if (ioctl(rawsock, SIOCGIFINDEX, &req) < 0 ) {
		fprintf(stderr, "Error - can't create raw socket (SIOCGIFINDEX) on interface %s: %s \n", devicename, strerror(errno));
		return -1;
	}

	addr.sll_family   = AF_PACKET;
	addr.sll_protocol = htons(ETH_P_ALL);
	addr.sll_ifindex  = req.ifr_ifindex;

	if (bind(rawsock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
		fprintf(stderr, "Error - can't bind raw socket on interface %s: %s \n", devicename, strerror(errno));
		close(rawsock);
		return -1;
	}

	/* make rawsock non blocking */
	/* TODO: setting this nonblocking is not a good idea ... */
/*	opts = fcntl(rawsock, F_GETFL, 0);
	if (fcntl(rawsock, F_SETFL, opts | O_NONBLOCK) < 0) {
		fprintf(stderr, "Error - set raw interface nonblocking %s: %s \n", devicename, strerror(errno));
		close(rawsock);
		return -1;
	}*/

	return rawsock;
}

int get_device_mac(char *devname, u8 *mac)
{
	int wlan_fd = -1;
	struct ifreq ifr_wlan;
	int ret = -1;

	memset(&ifr_wlan, 0, sizeof(ifr_wlan));
	strncpy(ifr_wlan.ifr_name, devname, IFNAMSIZ);

	wlan_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if (wlan_fd < 0) {
		fprintf(stderr, "Error - can't open wlan socket: %s \n", strerror(errno));
		goto error;
	}

/*	if (ioctl(wlan_fd, SIOCGIFINDEX, &ifr_wlan) == -1) {
		printf("ioctl() failed\n");
		return -1;
	} */

	if (ioctl(wlan_fd, SIOCGIFHWADDR, &ifr_wlan) < 0) {
		fprintf(stderr, "Error - can't get MAC address from %s: %s \n", strerror(errno), ifr_wlan.ifr_name);
		goto error;
	}

	memcpy(mac, ifr_wlan.ifr_hwaddr.sa_data, ETH_ALEN);
	fprintf(stderr, "Using MAC %s\n", print_addr(mac));
	ret = 0;

error:
	if (wlan_fd >= 0)
		close(wlan_fd);

	return ret;
}

