fluffy/pcap.c

87 lines
1.7 KiB
C
Raw Normal View History

2011-04-21 16:12:01 -06:00
#include <stdio.h>
#include <sysexits.h>
2011-04-22 12:47:08 -06:00
#include <string.h>
2011-04-21 16:12:01 -06:00
#include "pcap.h"
int
2011-04-22 12:47:08 -06:00
pcap_open_in(struct pcap_file *ctx, FILE *f)
2011-04-21 16:12:01 -06:00
{
struct pcap_file_header h;
if (1 != fread(&h, sizeof(h), 1, f)) {
h.magic = 0;
}
if (MAGIC == h.magic) {
2011-04-22 12:47:08 -06:00
ctx->swap = 0;
2011-04-21 16:12:01 -06:00
} else if (bswap32(MAGIC) == h.magic) {
2011-04-22 12:47:08 -06:00
ctx->swap = 1;
2011-04-21 16:12:01 -06:00
} else {
return -1;
}
if ((h.version_major != 2) || (h.version_minor != 4)) return -1;
2011-04-22 12:47:08 -06:00
if (ctx->swap) h.snaplen = bswap32(h.snaplen);
2011-04-21 16:12:01 -06:00
if (h.snaplen > MAXFRAME) return -1;
2011-04-22 12:47:08 -06:00
ctx->f = f;
return 0;
2011-04-21 16:12:01 -06:00
}
int
2011-04-22 12:47:08 -06:00
pcap_open_out(struct pcap_file *ctx, FILE *f)
2011-04-21 16:12:01 -06:00
{
struct pcap_file_header h = { MAGIC, 2, 4, 0, 0, MAXFRAME, 1 };
2011-04-22 12:47:08 -06:00
if (1 != fwrite(&h, sizeof(h), 1, f)) return -1;
ctx->f = f;
ctx->swap = 0;
2011-04-21 16:12:01 -06:00
return 0;
}
int
2011-04-22 12:47:08 -06:00
pcap_read_pkthdr(struct pcap_file *ctx, struct pcap_pkthdr *hdr)
2011-04-21 16:12:01 -06:00
{
2011-04-22 12:47:08 -06:00
if (1 != fread(hdr, sizeof(*hdr), 1, ctx->f)) {
return -1;
}
2011-04-21 16:12:01 -06:00
2011-04-22 12:47:08 -06:00
if (ctx->swap) {
hdr->ts.tv_sec = bswap32(hdr->ts.tv_sec);
hdr->ts.tv_usec = bswap32(hdr->ts.tv_usec);
hdr->caplen = bswap32(hdr->caplen);
hdr->len = bswap32(hdr->len);
}
2011-04-21 16:12:01 -06:00
2011-07-14 18:55:41 -06:00
if (hdr->caplen > MAXFRAME) return -1;
2011-04-21 16:12:01 -06:00
return 0;
}
int
2011-04-22 12:47:08 -06:00
pcap_write_pkthdr(struct pcap_file *ctx, struct pcap_pkthdr *hdr)
2011-04-21 16:12:01 -06:00
{
if (ctx->swap) {
2011-04-22 12:47:08 -06:00
struct pcap_pkthdr ohdr;
memcpy(&ohdr, hdr, sizeof(ohdr));
2011-04-21 16:12:01 -06:00
hdr->ts.tv_sec = bswap32(hdr->ts.tv_sec);
hdr->ts.tv_usec = bswap32(hdr->ts.tv_usec);
hdr->caplen = bswap32(hdr->caplen);
hdr->len = bswap32(hdr->len);
2011-04-22 12:47:08 -06:00
if (1 != fwrite(&ohdr, sizeof(ohdr), 1, ctx->f)) return -1;
} else {
if (1 != fwrite(hdr, sizeof(*hdr), 1, ctx->f)) return -1;
2011-04-21 16:12:01 -06:00
}
return 0;
}
void
pcap_close(struct pcap_file *ctx)
{
fclose(ctx->f);
}