/* pcap-wrap - wrap file inside pcap capture envelope */
/* 2011 andrewl */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <endian.h>

/* for guint, etc. in wireshark includes */
#include <glib.h>

/* for wtap type */
#include <wtap.h>

/* for pcap header */
/* do not include this! 32/64-bit compilation will produce
 * different sized pcap_pkthdr due to long type */
//#include <pcap.h>

/* from <WIRESHARK>/wiretap/
 * guaranteed to have same size as what wireshark expects */
#include <libpcap.h>

/* */
#include <pcap/bpf.h>

/* for ethernet header */
#include <net/ethernet.h>

int main(int ac, char **av)
{
    int size_file=0;
    FILE *fp=0;
    char str_ofile[256];
    unsigned char *buf;
    struct pcap_hdr my_pcap_hdr;
    struct pcaprec_hdr my_pcaprec_hdr;
    struct ip_header;
    guint32 magic = PCAP_SWAPPED_MAGIC;

    // open file, record size
    fp = fopen(av[1], "r");
    fseek(fp, 0, SEEK_END);
    size_file = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    // read in file
    buf = (unsigned char *)malloc(size_file);
    fread(buf, 1, size_file, fp);
    fclose(fp);

    // tweak structs
    /* my_pcap_hdr.magic = 0xa1b2c3d4; */
    my_pcap_hdr.version_major = htobe16(2);
    my_pcap_hdr.version_minor = htobe16(4);
    my_pcap_hdr.thiszone = 0;
    my_pcap_hdr.sigfigs = 0;
    my_pcap_hdr.snaplen = htobe32(size_file);
    my_pcap_hdr.network = htobe32(DLT_USER0);

    /* */
    memset(&my_pcaprec_hdr, 0, sizeof(my_pcaprec_hdr)); /* set ts_sec, ts_usec */
    my_pcaprec_hdr.incl_len = htobe32(size_file);
    my_pcaprec_hdr.orig_len = htobe32(size_file);

    // create out file name (blah blah unsafe)
    strcpy(str_ofile, av[1]);
    strcat(str_ofile, ".pcap");

    // write file
    fp = fopen(str_ofile, "wb");
    printf("writing 4-sized magic\n");
    fwrite(&magic, 1, 4, fp);
    printf("writing %d-sized my_pcap_hdr\n", sizeof(my_pcap_hdr));
    fwrite(&my_pcap_hdr, 1, sizeof(my_pcap_hdr), fp);
    printf("writing %d-sized my_pcaprec_hdr\n", sizeof(my_pcaprec_hdr));
    fwrite(&my_pcaprec_hdr, 1, sizeof(my_pcaprec_hdr), fp);
    /* payload (file contents) */
    printf("writing %d-sized file (packet payload)\n", size_file);
    fwrite(buf, 1, size_file, fp);
    fclose(fp);

    return 0;
}

