|
|
1.1 misho 1: /*
2: * Copyright (C) 2012 Martin Willi
3: * Copyright (C) 2012 revosec AG
4: *
5: * This program is free software; you can redistribute it and/or modify it
6: * under the terms of the GNU General Public License as published by the
7: * Free Software Foundation; either version 2 of the License, or (at your
8: * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9: *
10: * This program is distributed in the hope that it will be useful, but
11: * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12: * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13: * for more details.
14: */
15:
16: #include "error_notify_msg.h"
17:
18: #include <stdio.h>
19: #include <stdlib.h>
20: #include <stddef.h>
21: #include <unistd.h>
22: #include <sys/stat.h>
23: #include <sys/socket.h>
24: #include <sys/un.h>
25: #include <errno.h>
26: #include <arpa/inet.h>
27:
28: /**
29: * Connect to the daemon, return FD
30: */
31: static int make_connection()
32: {
33: union {
34: struct sockaddr_un un;
35: struct sockaddr_in in;
36: struct sockaddr sa;
37: } addr;
38: int fd, len;
39:
40: if (getenv("TCP_PORT"))
41: {
42: addr.in.sin_family = AF_INET;
43: addr.in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
44: addr.in.sin_port = htons(atoi(getenv("TCP_PORT")));
45: len = sizeof(addr.in);
46: }
47: else
48: {
49: addr.un.sun_family = AF_UNIX;
50: strcpy(addr.un.sun_path, ERROR_NOTIFY_SOCKET);
51:
52: len = offsetof(struct sockaddr_un, sun_path) + strlen(addr.un.sun_path);
53: }
54: fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
55: if (fd < 0)
56: {
57: fprintf(stderr, "opening socket failed: %s\n", strerror(errno));
58: return -1;
59: }
60: if (connect(fd, &addr.sa, len) < 0)
61: {
62: fprintf(stderr, "connecting failed: %s\n", strerror(errno));
63: close(fd);
64: return -1;
65: }
66: return fd;
67: }
68:
69: /**
70: * Example of a simple notification listener
71: */
72: int main(int argc, char *argv[])
73: {
74: error_notify_msg_t msg;
75: int s, len, total;
76: void *pos;
77:
78: s = make_connection();
79: if (s < 0)
80: {
81: return 1;
82: }
83: while (1)
84: {
85: total = 0;
86: pos = &msg;
87:
88: while (total < sizeof(msg))
89: {
90: len = read(s, pos, sizeof(msg) - total);
91: if (len < 0)
92: {
93: fprintf(stderr, "read failed: %s\n", strerror(errno));
94: close(s);
95: return 1;
96: }
97: total += len;
98: pos += len;
99: }
100: printf("%d %s %s %s %s\n",
101: ntohl(msg.type), msg.name, msg.id, msg.ip, msg.str);
102: }
103: close(s);
104: return 0;
105: }