/*
 * author: Darren Bounds <dbounds@intrusense.com>
 * copyright: Copyright (C) 2002 by Darren Bounds
 * license: This software is under GPL version 2 of license
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * packit official page at http://packit.sourceforge.net
 */

#include "../include/packit.h" 
#include "../include/inject.h"
#include "../include/error.h"

int 
retrieve_tcp_flags()
{
    int flags = 0;

#ifdef __DEBUG
    fprintf(stderr, "DEBUG: retrieve_tcp_flags()\n");
#endif

    if(thdr_o.th_urg)
        flags |= TH_URG;

    if(thdr_o.th_ack)
        flags |= TH_ACK;

    if(thdr_o.th_psh)
        flags |= TH_PUSH;

    if(thdr_o.th_rst)
        flags |= TH_RST;

    if(thdr_o.th_syn)
        flags |= TH_SYN;

    if(thdr_o.th_fin)
        flags |= TH_FIN;

    return flags;
}

libnet_t *
build_tcp_hdr(libnet_t *packet_d)
{
    int flags = 0;

#ifdef __DEBUG
    fprintf(stderr, "DEBUG: build_tcp_hdr()\n");
#endif

    header_len = PACKIT_TCP_H;

    if(rand_sport)
        sport =  libnet_get_prand(LIBNET_PRu16); 

    if((thdr_o.th_rand_seqn && thdr_o.th_syn) == 1)
        thdr_o.th_seqn =  libnet_get_prand(LIBNET_PRu32);

    flags = retrieve_tcp_flags(flags);

    if(libnet_build_tcp(
        sport, 
        dport, 
        thdr_o.th_seqn, 
        thdr_o.th_ackn, 
        flags, 
        thdr_o.th_win, 
        0, 
        thdr_o.th_urp, 
        header_len + payload_len, 
        payload, 
        payload_len, 
        packet_d, 
        0) == -1)
    {
        fprintf(stderr, "\nError: Unable to build TCP header: %s\n", libnet_geterror(packet_d)); 
        exit(FAILURE);
    } 

    return packet_d;
}

int
parse_port_range(char *rangestr)
{
    int i, range = 0; 
    int spread[10];
    char o_rangestr[11];
    char *ptr, *delim = ":";

#ifdef __DEBUG
    fprintf(stderr, "DEBUG: parse_port_range(): %s\n", rangestr);
#endif

    if(rangestr)
	strncpy(o_rangestr, rangestr, 11);

    for(i = 0, ptr = strtok(o_rangestr, delim);
        ptr;
        ptr = strtok(NULL, delim))
    {
	spread[i] = (int)atoi(ptr);

	if(spread[i] < 1 || spread[i] > 65535)
            return -1;

	i++;
    }

    rangestr = o_rangestr;
    range = spread[1] - spread[0] + 1;
    dport = spread[0];

    if(range < 1 || i != 2)
        return -1;

    return range;
}

