/*
 *      idlescan
 *      Copyright (C) 1999 LiquidK <liquidk@superbofh.org>
 *
 */


#include "global.h"
#include "packet.h"
#include <libnet.h>


void send_syn(int sock, int source_ip, int dest_ip, int dest_port)
{

    char buf[LIBNET_TCP_H + LIBNET_IP_H];

    libnet_build_ip(LIBNET_TCP_H,
		    0,
		    libnet_get_prand(LIBNET_PRu16),
		    0,
		    64,
		    IPPROTO_TCP,
		    source_ip,
		    dest_ip,
		    NULL,
		    0,
		    buf);


    libnet_build_tcp(
		     1500,
		     dest_port,
		     1111,
		     1111,
		     TH_SYN,
		     1024,
		     0,
		     NULL,
		     0,
		     buf + LIBNET_IP_H);

    if (libnet_do_checksum(buf, IPPROTO_TCP, LIBNET_TCP_H) == -1) {
	fprintf(stderr, "Can't do checksum!\n");
    }

    libnet_write_ip(sock, buf, LIBNET_TCP_H + LIBNET_IP_H);

}


void packet_send_icmpecho(int sock, int source, int dest, int id, int seq)
{

    char buf[LIBNET_ICMP_ECHO_H + 30];

    libnet_build_ip(LIBNET_ICMP_ECHO_H,
		    0,
		    libnet_get_prand(LIBNET_PRu16), /* id */
		    0,
		    64,
		    IPPROTO_ICMP,
		    0,                              /* FIXME: no need for this now (source ip) */
		    dest,
		    NULL,
		    0,
		    buf);

    libnet_build_icmp_echo(ICMP_ECHO,          /* type */
			   0,                  /* code */
			   id,                 /* id   */
			   seq,                /* seq  */
			   NULL,               /* payload */
			   0,                  /* payload size*/
			   buf + LIBNET_IP_H); /* buffer */

    if (libnet_do_checksum(buf, IPPROTO_ICMP, LIBNET_ICMP_ECHO_H) == -1) {
	fprintf(stderr, "Can't do checksum!\n");
    }

    if(!libnet_write_ip(sock, buf, LIBNET_ICMP_ECHO_H + LIBNET_IP_H)) {
	fprintf(stderr, "libnet_write_ip returned 0\n");
    }

}


/* FIXME: should return the sequence number */
int packet_check_icmpecho(int sock, struct iphdr *ip, int size, int my_ip,int id)
{
    struct icmphdr *icmp;


    icmp = (struct icmphdr *)((char *)ip + ((int)ip->ihl << 2));

    if( ip->daddr == my_ip &&
	ip->protocol == IPPROTO_ICMP &&
	icmp->type == ICMP_ECHOREPLY &&
	ntohs(icmp->un.echo.id) == id) {
	return 1;
    }

    return 0;
}
