/* clientpacket.c
 *
 * Packet generation and dispatching functions for the DHCP client.
 *
 * Russ Dill <Russ.Dill@asu.edu> July 2001
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <string.h>
#include <sys/socket.h>
#include <features.h>
#if __GLIBC__ >=2 && __GLIBC_MINOR >= 1
#include <netpacket/packet.h>
#include <net/ethernet.h>
#else
#include <asm/types.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#endif
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>

#include "dhcpd.h"
#include "packet.h"
#include "options.h"
#include "dhcpc.h"
#include "debug.h"


/* Create a random xid */
unsigned long random_xid(void)
{
    struct timeval  tv;

	static int initialized;
	if (!initialized) {
        #if 0 /* wuyun, 2009-09-01, 修改随机数种子的生成算法，现在跟MAC地址和时间有关 */
		srand(time(0));
        #else
        gettimeofday(&tv, NULL);
        srand(((client_config.arp[4] * client_config.arp[4] + client_config.arp[5]* client_config.arp[5]) << 16) + tv.tv_usec);
        #endif
		initialized++;
	}
	return rand();
}

/* 如果 */
static void init_packet_dis(struct dhcpMessage *packet, char type)
{
	struct vendor  {
		char vendor, length;
		char str[sizeof("udhcp "VERSION)];
	} vendor_id = { DHCP_VENDOR,  sizeof("udhcp "VERSION) - 1, "udhcp "VERSION};
	
	init_header(packet, type);
	memcpy(packet->chaddr, client_config.arp, 6);
	add_option_string(packet->options, client_config.clientid);
	if (client_config.hostname) add_option_string(packet->options, client_config.hostname);
	add_option_string(packet->options, (unsigned char *) &vendor_id);
#ifdef CONFIG_RTL865X_KLD
	if (client_config.broadcast_flag) packet->flags |= BROADCAST_FLAG;
#endif
}

/* initialize a packet with the proper defaults */
static void init_packet(struct dhcpMessage *packet, char type)
{
    /* change by yuanke for set vendor id */
#if 0
	struct vendor  {
		char vendor, length;
        char str[sizeof("udhcp "VERSION)];
	} vendor_id = { DHCP_VENDOR,  sizeof("udhcp "VERSION) - 1, "udhcp "VERSION};
#else
    typedef struct vendor  {
		char vendor, length;
	    char str[sizeof("udhcp "VERSION)];
	} t_ven;

    t_ven vendor_id;

    memset(&vendor_id, 0, sizeof(t_ven));

    vendor_id.vendor = DHCP_VENDOR;
    vendor_id.length = strlen(client_config.vendorid);
	strncpy(vendor_id.str, client_config.vendorid, sizeof("udhcp "VERSION));
#endif

	init_header(packet, type);
	memcpy(packet->chaddr, client_config.arp, 6);
	add_option_string(packet->options, client_config.clientid);
	if (client_config.hostname) add_option_string(packet->options, client_config.hostname);

	add_option_string(packet->options, (unsigned char *) &vendor_id);

    /* add by yuanke for MTU */
	if (client_config.mtu)
		add_option_string(packet->options, client_config.mtu);
}


/* Add a paramater request list for stubborn DHCP servers. Pull the data
 * from the struct in options.c. Don't do bounds checking here because it
 * goes towards the head of the packet. */
static void add_requests(struct dhcpMessage *packet)
{
	int end = end_option(packet->options);
	int i, len = 0;

	packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
	for (i = 0; options[i].code; i++)
		if (options[i].flags & OPTION_REQ)
			packet->options[end + OPT_DATA + len++] = options[i].code;
	packet->options[end + OPT_LEN] = len;
	packet->options[end + OPT_DATA + len] = DHCP_END;

}


/* send_discover_dis和init_packet_dis这两函数是专门为dhcpc-discovery.c生成udhcpc-discovery命令准备的，
	它避免了在dhcpc-discovery.c中调用send_discover进而调用init_packet造成的segment fault 
*/
int send_discover_dis(unsigned long xid, unsigned long requested)
{
	struct dhcpMessage packet;

	init_packet_dis(&packet, DHCPDISCOVER);
	packet.xid = xid;
	if (requested)
		add_simple_option(packet.options, DHCP_REQUESTED_IP, requested);

	add_requests(&packet);
	LOG(LOG_DEBUG, "Sending discover...");
	return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
				SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
}




/* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
int send_discover(unsigned long xid, unsigned long requested)
{
	struct dhcpMessage packet;

	init_packet(&packet, DHCPDISCOVER);
	packet.xid = xid;
	if (requested)
		add_simple_option(packet.options, DHCP_REQUESTED_IP, requested);

	add_requests(&packet);
	LOG(LOG_DEBUG, "Sending discover...");
	return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
				SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
}



/* Broadcasts a DHCP request message */
int send_selecting(unsigned long xid, unsigned long server, unsigned long requested)
{
	struct dhcpMessage packet;
	struct in_addr addr;

	init_packet(&packet, DHCPREQUEST);
	packet.xid = xid;

	add_simple_option(packet.options, DHCP_REQUESTED_IP, requested);
	add_simple_option(packet.options, DHCP_SERVER_ID, server);

	add_requests(&packet);
	addr.s_addr = requested;
	LOG(LOG_DEBUG, "Sending select for %s...", inet_ntoa(addr));
	return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
				SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
}


/* Unicasts or broadcasts a DHCP renew message */
/*
 * wuyun, 2009-09-19,
 * Always use raw socket to send dhcp renew packet to make sure packet can be always sent out,
 * even if in the case that arp can not be leanrt.
 */
#if 0
int send_renew(unsigned long xid, unsigned long server, unsigned long ciaddr)
{
	struct dhcpMessage packet;
	int ret = 0;

	init_packet(&packet, DHCPREQUEST);
	packet.xid = xid;
	packet.ciaddr = ciaddr;

	add_requests(&packet);
	LOG(LOG_DEBUG, "Sending renew...");
	if (server)
		ret = kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
	else ret = raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
				SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
	return ret;
}
#else
int send_renew(unsigned long xid, unsigned long server, unsigned long ciaddr, unsigned char dstmac[])
{
    struct dhcpMessage packet;
    int ret = 0;

    init_packet(&packet, DHCPREQUEST);
    packet.xid = xid;
    packet.ciaddr = ciaddr;

    add_requests(&packet);
    LOG(LOG_DEBUG, "Sending renew...");

    ret = raw_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT, dstmac, client_config.ifindex);
    return ret;
}
#endif

/* Unicasts a DHCP release message */
int send_release(unsigned long server, unsigned long ciaddr)
{
	struct dhcpMessage packet;

	init_packet(&packet, DHCPRELEASE);
	packet.xid = random_xid();
	packet.ciaddr = ciaddr;

	add_simple_option(packet.options, DHCP_REQUESTED_IP, ciaddr);
	add_simple_option(packet.options, DHCP_SERVER_ID, server);

	LOG(LOG_DEBUG, "Sending release...");
	return kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
}

#if 0 /* wuyun, 2009-09-21, return packet src mac, and verify packet more strictly */
int get_raw_packet(struct dhcpMessage *payload, int fd)
{
	int bytes;
	struct udp_dhcp_packet packet;
	u_int32_t source, dest;
	u_int16_t check;

	memset(&packet, 0, sizeof(struct udp_dhcp_packet));
	bytes = read(fd, &packet, sizeof(struct udp_dhcp_packet));
	if (bytes < 0) {
		DEBUG(LOG_INFO, "couldn't read on raw listening socket -- ignoring");
		usleep(500000); /* possible down interface, looping condition */
		return -1;
	}

	if (bytes < (int) (sizeof(struct iphdr) + sizeof(struct udphdr))) {
		DEBUG(LOG_INFO, "message too short, ignoring");
		return -1;
	}

	if (bytes < ntohs(packet.ip.tot_len)) {
		DEBUG(LOG_INFO, "Truncated packet");
		return -1;
	}

	/* ignore any extra garbage bytes */
	bytes = ntohs(packet.ip.tot_len);

	/* Make sure its the right packet for us, and that it passes sanity checks */
	if (packet.ip.protocol != IPPROTO_UDP || packet.ip.version != IPVERSION ||
	    packet.ip.ihl != sizeof(packet.ip) >> 2 || packet.udp.dest != htons(CLIENT_PORT) ||
	    bytes > (int) sizeof(struct udp_dhcp_packet) ||
	    ntohs(packet.udp.len) != (short) (bytes - sizeof(packet.ip))) {
	    	DEBUG(LOG_INFO, "unrelated/bogus packet");
	    	return -1;
	}

	/* check IP checksum */
	check = packet.ip.check;
	packet.ip.check = 0;
	if (check != checksum(&(packet.ip), sizeof(packet.ip))) {
		DEBUG(LOG_INFO, "bad IP header checksum, ignoring");
		return -1;
	}

	/* verify the UDP checksum by replacing the header with a psuedo header */
	source = packet.ip.saddr;
	dest = packet.ip.daddr;
	check = packet.udp.check;
	packet.udp.check = 0;
	memset(&packet.ip, 0, sizeof(packet.ip));

	packet.ip.protocol = IPPROTO_UDP;
	packet.ip.saddr = source;
	packet.ip.daddr = dest;
	packet.ip.tot_len = packet.udp.len; /* cheat on the psuedo-header */
	if (check && check != checksum(&packet, bytes)) {
		DEBUG(LOG_ERR, "packet with bad UDP checksum received, ignoring");
		return -1;
	}

	memcpy(payload, &(packet.data), bytes - (sizeof(packet.ip) + sizeof(packet.udp)));

	if (ntohl(payload->cookie) != DHCP_MAGIC) {
		LOG(LOG_ERR, "received bogus message (bad magic) -- ignoring");
		return -1;
	}
	DEBUG(LOG_INFO, "oooooh!!! got some!");
	return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
}
#else
int get_raw_packet(struct dhcpMessage *payload, int fd, u_char *srcmac)
{
	int bytes;
	u_int32_t source, dest;
	u_int16_t check;
    u_char   buffer[(0xF << 2) + sizeof(struct udphdr) + sizeof(struct dhcpMessage)];
    struct  sockaddr_ll sll;
    int     slllen;
	struct iphdr *ip;
	struct udphdr *udp;
	struct dhcphdr *dhcp;

    /* receive packet */

    memset(&sll, 0, sizeof(struct sockaddr_ll));
    slllen = sizeof(sll);
    bytes = recvfrom(fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&sll, &slllen);
    if (bytes < 0)
    {
        DEBUG(LOG_INFO, "couldn't read on raw listening socket -- ignoring");
        usleep(500000); /* possible down interface, looping condition */
        return -1;
	}

    /* check ip header */

    if (bytes < (int)sizeof(struct iphdr))
    {
        DEBUG(LOG_INFO, "message too short, ignoring");
        return -1;
    }

    ip = (struct iphdr *)buffer;

    if (ip->ihl << 2 != sizeof(struct iphdr))
    {
        DEBUG(LOG_INFO, "IP options may exist, ignoring");
        return -1;
    }

	if (ip->version != IPVERSION)
    {
        DEBUG(LOG_INFO, "bad ip version, ignoring");
        return -1;
	}

	if (ip->protocol != IPPROTO_UDP)
    {
        DEBUG(LOG_INFO, "not udp, ignoring");
        return -1;
	}

	if (ntohs(ip->tot_len) > bytes)
    {
        DEBUG(LOG_INFO, "bad IP total length, ignoring");
        return -1;
	}

	check = ip->check;
	ip->check = 0;
	if (check != checksum(ip, ip->ihl << 2))
    {
		DEBUG(LOG_INFO, "bad IP checksum, ignoring");
		return -1;
	}

    bytes = ntohs(ip->tot_len) - (ip->ihl << 2);

    /* check udp header */

    if (bytes < (int)sizeof(struct udphdr))
    {
        DEBUG(LOG_INFO, "message too short, ignoring");
        return -1;
    }

    udp = (struct udphdr *)((u_char *)ip + (ip->ihl << 2));

    if (   udp->source != htons(SERVER_PORT)
        || udp->dest != htons(CLIENT_PORT)
        || ntohs(udp->len) > bytes
       )
    {
        DEBUG(LOG_INFO, "unrelated/bogus packet");
        return -1;
    }

	/* verify the UDP checksum by replacing the header with a psuedo header */
    if (0 != udp->check)
    {
    	source = ip->saddr;
    	dest = ip->daddr;

        ip = (struct iphdr *)((u_char *)udp - sizeof(struct iphdr));
    	memset((void *)ip, 0, sizeof(struct iphdr));
    	ip->protocol = IPPROTO_UDP;
    	ip->saddr = source;
    	ip->daddr = dest;
    	ip->tot_len = udp->len; /* cheat on the psuedo-header */

        check = udp->check;
        udp->check = 0;
    	if (check != checksum((void *)ip, sizeof(struct iphdr) + bytes))
        {
    		DEBUG(LOG_ERR, "bad UDP checksum, ignoring");
    		return -1;
    	}
    }

    bytes -= sizeof(struct udphdr);

    /* check dhcp header */

    if (bytes < (int)sizeof(struct dhcphdr))
    {
        DEBUG(LOG_INFO, "message too short, ignoring");
        return -1;
    }

    dhcp = (struct dhcphdr *)(udp + 1);

	if (dhcp->cookie != htonl(DHCP_MAGIC))
    {
		LOG(LOG_ERR, "bad magic, ignoring");
		return -1;
	}

    /* return */
	memcpy((void *)payload, (void *)dhcp, bytes);
    memcpy((void *)srcmac, sll.sll_addr, ETH_ALEN);
	return bytes;
}
#endif

