1 /* $NetBSD: save_file.c,v 1.1.1.1 2012/03/23 21:20:10 christos Exp $ */
2
3 #include "ipf.h"
4 #include "ipmon.h"
5
6 static void *file_parse __P((char **));
7 static void file_destroy __P((void *));
8 static int file_send __P((void *, ipmon_msg_t *));
9 static void file_print __P((void *));
10 static int file_match __P((void *, void *));
11 static void *file_dup __P((void *));
12
13 typedef struct file_opts_s {
14 FILE *fp;
15 int raw;
16 char *path;
17 int ref;
18 } file_opts_t;
19
20 ipmon_saver_t filesaver = {
21 "file",
22 file_destroy,
23 file_dup,
24 file_match,
25 file_parse,
26 file_print,
27 file_send
28 };
29
30
31 static void *
file_parse(strings)32 file_parse(strings)
33 char **strings;
34 {
35 file_opts_t *ctx;
36
37 ctx = calloc(1, sizeof(*ctx));
38 if (ctx == NULL)
39 return NULL;
40
41 if (strings[0] != NULL && strings[0][0] != '\0') {
42 ctx->ref = 1;
43 if (!strncmp(strings[0], "raw://", 6)) {
44 ctx->raw = 1;
45 ctx->path = strdup(strings[0] + 6);
46 ctx->fp = fopen(ctx->path, "ab");
47 } else if (!strncmp(strings[0], "file://", 7)) {
48 ctx->path = strdup(strings[0] + 7);
49 ctx->fp = fopen(ctx->path, "a");
50 } else {
51 free(ctx);
52 ctx = NULL;
53 }
54 } else {
55 free(ctx);
56 ctx = NULL;
57 }
58
59 return ctx;
60 }
61
62
63 static int
file_match(ctx1,ctx2)64 file_match(ctx1, ctx2)
65 void *ctx1, *ctx2;
66 {
67 file_opts_t *f1 = ctx1, *f2 = ctx2;
68
69 if (f1->raw != f2->raw)
70 return 1;
71 if (strcmp(f1->path, f2->path))
72 return 1;
73 return 0;
74 }
75
76
77 static void *
file_dup(ctx)78 file_dup(ctx)
79 void *ctx;
80 {
81 file_opts_t *f = ctx;
82
83 f->ref++;
84 return f;
85 }
86
87
88 static void
file_print(ctx)89 file_print(ctx)
90 void *ctx;
91 {
92 file_opts_t *file = ctx;
93
94 if (file->raw)
95 printf("raw://");
96 else
97 printf("file://");
98 printf("%s", file->path);
99 }
100
101
102 static void
file_destroy(ctx)103 file_destroy(ctx)
104 void *ctx;
105 {
106 file_opts_t *file = ctx;
107
108 file->ref--;
109 if (file->ref > 0)
110 return;
111
112 if (file->path != NULL)
113 free(file->path);
114 free(file);
115 }
116
117
118 static int
file_send(ctx,msg)119 file_send(ctx, msg)
120 void *ctx;
121 ipmon_msg_t *msg;
122 {
123 file_opts_t *file = ctx;
124
125 if (file->raw) {
126 fwrite(msg->imm_data, msg->imm_dsize, 1, file->fp);
127 } else {
128 fprintf(file->fp, "%s", msg->imm_msg);
129 }
130 return 0;
131 }
132
133