Debian Codegraph @

examples/writer.c

raw
1 #include <dnswire/writer.h>
2
3 #include <errno.h>
4 #include <stdio.h>
5 #include <string.h>
6
7 #include "create_dnstap.c"
8
9 int main(int argc, const char* argv[])
10 {
11 if (argc < 2) {
12 fprintf(stderr, "usage: writer <file>\n");
13 return 1;
14 }
15
16 /*
17 * We start by opening the output file for writing.
18 */
19
20 FILE* fp = fopen(argv[1], "w");
21 if (!fp) {
22 fprintf(stderr, "Unable to open %s: %s\n", argv[1], strerror(errno));
23 return 1;
24 }
25
26 /*
27 * We first initialize the writer and check that it can allocate the
28 * buffers it needs.
29 */
30
31 struct dnswire_writer writer;
32
33 if (dnswire_writer_init(&writer) != dnswire_ok) {
34 fprintf(stderr, "Unable to initialize dnswire writer\n");
35 return 1;
36 }
37
38 /*
39 * Now we create a DNSTAP message.
40 */
41
42 struct dnstap d = create_dnstap("writer");
43
44 /*
45 * We set the DNSTAP message the writer should write.
46 */
47
48 dnswire_writer_set_dnstap(writer, &d);
49
50 /*
51 * We now loop and wait for the DNSTAP message to be written.
52 */
53
54 int done = 0;
55
56 while (!done) {
57 switch (dnswire_writer_fwrite(&writer, fp)) {
58 case dnswire_ok:
59 /*
60 * The DNSTAP message was written successfully, we can now set
61 * a new DNSTAP message for the writer or stop the stream.
62 *
63 * This stops the stream, loop again until it's stopped.
64 */
65 dnswire_writer_stop(&writer);
66 break;
67 case dnswire_again:
68 break;
69 case dnswire_endofdata:
70 /*
71 * The stream is stopped, we're done!
72 */
73 done = 1;
74 break;
75 default:
76 fprintf(stderr, "dnswire_writer_fwrite() error\n");
77 done = 1;
78 }
79 }
80
81 dnswire_writer_destroy(writer);
82 fclose(fp);
83 return 0;
84 }