fluffy

Network Archaeology tools for Unix
git clone https://git.woozle.org/neale/fluffy.git

Neale Pickett  ·  2020-09-21

pcap.c

  1#include <stdio.h>
  2#include <sysexits.h>
  3#include <string.h>
  4#include "pcap.h"
  5
  6int
  7pcap_open_in(struct pcap_file *ctx, FILE * f)
  8{
  9	struct pcap_file_header h;
 10
 11	if (1 != fread(&h, sizeof(h), 1, f)) {
 12		h.magic = 0;
 13	}
 14
 15	if (MAGIC == h.magic) {
 16		ctx->swap = 0;
 17	} else if (bswap32(MAGIC) == h.magic) {
 18		ctx->swap = 1;
 19	} else {
 20		return -1;
 21	}
 22	if ((h.version_major != 2) || (h.version_minor != 4)) {
 23		return -1;
 24	}
 25
 26	if (ctx->swap) {
 27		h.snaplen = bswap32(h.snaplen);
 28	}
 29	if (h.snaplen > MAXFRAME) {
 30		return -1;
 31	}
 32	ctx->linktype = h.linktype;
 33
 34	ctx->f = f;
 35	return 0;
 36}
 37
 38int
 39pcap_open_out(struct pcap_file *ctx, FILE * f)
 40{
 41	return pcap_open_out_linktype(ctx, f, 1);
 42}
 43
 44int
 45pcap_open_out_linktype(struct pcap_file *ctx, FILE *f, int32_t linktype) {
 46	struct pcap_file_header h = { MAGIC, 2, 4, 0, 0, MAXFRAME, linktype };
 47
 48	if (1 != fwrite(&h, sizeof(h), 1, f)) {
 49		return -1;
 50	}
 51	ctx->f = f;
 52	ctx->swap = 0;
 53
 54	return 0;
 55}
 56
 57int
 58pcap_read_pkthdr(struct pcap_file *ctx, struct pcap_pkthdr *hdr)
 59{
 60	if (1 != fread(hdr, sizeof(*hdr), 1, ctx->f)) {
 61		return -1;
 62	}
 63
 64	if (ctx->swap) {
 65		hdr->ts.tv_sec = bswap32(hdr->ts.tv_sec);
 66		hdr->ts.tv_usec = bswap32(hdr->ts.tv_usec);
 67		hdr->caplen = bswap32(hdr->caplen);
 68		hdr->len = bswap32(hdr->len);
 69	}
 70
 71	if (hdr->caplen > MAXFRAME) {
 72		return -1;
 73	}
 74
 75	return 0;
 76}
 77
 78int
 79pcap_write_pkthdr(struct pcap_file *ctx, struct pcap_pkthdr *hdr)
 80{
 81	if (ctx->swap) {
 82		struct pcap_pkthdr ohdr;
 83
 84		memcpy(&ohdr, hdr, sizeof(ohdr));
 85		hdr->ts.tv_sec = bswap32(hdr->ts.tv_sec);
 86		hdr->ts.tv_usec = bswap32(hdr->ts.tv_usec);
 87		hdr->caplen = bswap32(hdr->caplen);
 88		hdr->len = bswap32(hdr->len);
 89
 90		if (1 != fwrite(&ohdr, sizeof(ohdr), 1, ctx->f)) {
 91			return -1;
 92		}
 93	} else {
 94		if (1 != fwrite(hdr, sizeof(*hdr), 1, ctx->f)) {
 95			return -1;
 96		}
 97	}
 98
 99	return 0;
100}
101
102void
103pcap_close(struct pcap_file *ctx)
104{
105	fclose(ctx->f);
106}