#include #include #include #include #include #include "log.h" #include "hexdump.h" #include "packet_dump.h" #include "packet_utils.h" #define PACKET_DUMP_LOG_ERROR(format, ...) LOG_ERROR("packet dump", format, ##__VA_ARGS__) struct pcap_pkt_hdr { unsigned int tv_sec; // time stamp unsigned int tv_usec; // time stamp unsigned int caplen; // length of portion present unsigned int len; // length this packet (off wire) }; struct pcap_file_hdr { unsigned int magic; unsigned short version_major; unsigned short version_minor; unsigned int thiszone; // gmt to local correction unsigned int sigfigs; // accuracy of timestamps unsigned int snaplen; // max length saved portion of each pkt unsigned int linktype; // data link type (LINKTYPE_*) }; // return 0: success // return -1: failed int packet_dump_pcap(const struct packet *pkt, const char *file) { const char *data = packet_get_raw_data(pkt); uint16_t len = packet_get_raw_len(pkt); struct pcap_pkt_hdr pkt_hdr = {}; struct pcap_file_hdr file_hdr = { .magic = 0xA1B2C3D4, .version_major = 0x0002, .version_minor = 0x0004, .thiszone = 0, .sigfigs = 0, .snaplen = 0xFFFF, .linktype = 1}; if (file == NULL || data == NULL || len == 0) { PACKET_DUMP_LOG_ERROR("invalid parameter, file: %p, data: %p, len: %d", file, data, len); return -1; } FILE *fp = fopen(file, "w+"); if (fp == NULL) { PACKET_DUMP_LOG_ERROR("fopen %s failed, %s", file, strerror(errno)); return -1; } struct timeval ts = {}; gettimeofday(&ts, NULL); pkt_hdr.tv_sec = ts.tv_sec; pkt_hdr.tv_usec = ts.tv_usec; pkt_hdr.caplen = len; pkt_hdr.len = len; fwrite(&file_hdr, sizeof(struct pcap_file_hdr), 1, fp); fwrite(&pkt_hdr, sizeof(struct pcap_pkt_hdr), 1, fp); fwrite(data, 1, len, fp); fflush(fp); fclose(fp); return 0; } void packet_dump_hex(const struct packet *pkt, int fd) { uint16_t len = packet_get_raw_len(pkt); const char *data = packet_get_raw_data(pkt); hexdump_to_fd(fd, data, len); }