Write packets to files

This commit is contained in:
Quentin 2019-05-28 14:21:06 +02:00
parent 5be3a951af
commit 6b4a784171
2 changed files with 29 additions and 2 deletions

View file

@ -29,6 +29,10 @@ void dynbuf_append(struct dynbuf* db, char* ptr, size_t len) {
db->written += len;
}
void dynbuf_destroy(struct dynbuf* db) {
free(db->content);
}
void traffic_capture_init(struct capture_ctx* ctx, char* filename) {
ctx->activated = filename == NULL ? 0 : 1;
if (!ctx->activated) return;
@ -49,7 +53,7 @@ void traffic_capture_notify(struct capture_ctx* ctx, struct buffer_packet *bp, c
dynbuf_append (
strcmp(dest, "in") == 0 ? &ctx->in : &ctx->out,
(char*)&bp,
sizeof(struct buffer_packet) - sizeof(struct internet_packet) + bp->ip.ap.fmt.headers.size);
sizeof(struct buffer_packet));
}
void traffic_capture_stop(struct capture_ctx* ctx) {
@ -57,8 +61,29 @@ void traffic_capture_stop(struct capture_ctx* ctx) {
FILE* fd = NULL;
if ((fd = fopen(ctx->filename, "w")) == NULL) {
struct dynbuf *dbs[] = {&ctx->in, &ctx->out};
for (int i = 0; i < 2; i++) {
size_t written = 0, ack = 0;
char *out_file = NULL;
asprintf(&out_file, "%s.%d", ctx->filename, i);
if (out_file == NULL || (fd = fopen(out_file, "w")) == NULL) {
perror("failed to open file");
exit(EXIT_FAILURE);
}
free(out_file);
while (written < dbs[i]->written) {
ack = fwrite(dbs[i]->content+written, sizeof(char), dbs[i]->written, fd);
if (ack <= 0) {
perror("unable to write capture file");
exit(EXIT_FAILURE);
}
written += ack;
}
fclose(fd);
dynbuf_destroy (dbs[i]);
}
free(ctx->filename);

View file

@ -1,4 +1,6 @@
#pragma once
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>