Debian Codegraph @

src/test/reader_unixsock.c

raw
1 #include <dnswire/writer.h>
2 #include <dnswire/reader.h>
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/socket.h>
9 #include <sys/un.h>
10 #include <sys/types.h>
11 #include <signal.h>
12 #include <sys/wait.h>
13
14 #include "print_dnstap.c"
15
16 int main(int argc, const char* argv[])
17 {
18 if (argc < 2) {
19 return 1;
20 }
21
22 struct sockaddr_un path;
23 memset(&path, 0, sizeof(struct sockaddr_un));
24 path.sun_family = AF_UNIX;
25 strncpy(path.sun_path, argv[1], sizeof(path.sun_path) - 1);
26
27 int readfd = socket(AF_UNIX, SOCK_STREAM, 0);
28 if (readfd == -1
29 || bind(readfd, (struct sockaddr*)&path, sizeof(struct sockaddr_un))
30 || listen(readfd, 1)) {
31 close(readfd);
32 return 1;
33 }
34 fprintf(stderr, "bind & listen\n");
35
36 int fd, ret = 1;
37 alarm(5);
38 if ((fd = accept(readfd, 0, 0))) {
39 fprintf(stderr, "accept\n");
40
41 struct dnswire_reader reader;
42 if (dnswire_reader_init(&reader) != dnswire_ok) {
43 return 1;
44 }
45 dnswire_reader_allow_bidirectional(&reader, true);
46
47 // force small buffers to trigger buf resizing
48 reader.write_size = 4;
49 reader.write_inc = 4;
50 if (dnswire_reader_set_bufsize(&reader, 4) != dnswire_ok) {
51 return 1;
52 }
53 if (dnswire_reader_set_bufinc(&reader, 4) != dnswire_ok) {
54 return 1;
55 }
56
57 int done = 0;
58
59 while (!done) {
60 switch (dnswire_reader_read(&reader, fd)) {
61 case dnswire_have_dnstap:
62 print_dnstap(dnswire_reader_dnstap(reader));
63 fflush(stdout);
64 break;
65 case dnswire_again:
66 case dnswire_need_more:
67 break;
68 case dnswire_endofdata:
69 done = 1;
70 break;
71 default:
72 fprintf(stderr, "dnswire_reader_read() error\n");
73 shutdown(fd, SHUT_RDWR);
74 close(fd);
75 close(readfd);
76 return 1;
77 }
78 }
79
80 dnswire_reader_destroy(reader);
81 shutdown(fd, SHUT_RDWR);
82 close(fd);
83 }
84 close(readfd);
85 return ret;
86 }