charon: Add custom logger to daemon
[strongswan.git] / src / libcharon / plugins / duplicheck / duplicheck.c
1 /*
2 * Copyright (C) 2011 Martin Willi
3 * Copyright (C) 2011 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 <sys/socket.h>
17 #include <sys/un.h>
18 #include <unistd.h>
19 #include <stdlib.h>
20 #include <stddef.h>
21 #include <stdio.h>
22 #include <errno.h>
23 #include <arpa/inet.h>
24
25 #include "duplicheck_msg.h"
26
27 /**
28 * Connect to the daemon, return FD
29 */
30 static int make_connection()
31 {
32 union {
33 struct sockaddr_un un;
34 struct sockaddr_in in;
35 struct sockaddr sa;
36 } addr;
37 int fd, len;
38
39 if (getenv("TCP_PORT"))
40 {
41 addr.in.sin_family = AF_INET;
42 addr.in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
43 addr.in.sin_port = htons(atoi(getenv("TCP_PORT")));
44 len = sizeof(addr.in);
45 }
46 else
47 {
48 addr.un.sun_family = AF_UNIX;
49 strcpy(addr.un.sun_path, DUPLICHECK_SOCKET);
50
51 len = offsetof(struct sockaddr_un, sun_path) + strlen(addr.un.sun_path);
52 }
53 fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
54 if (fd < 0)
55 {
56 fprintf(stderr, "opening socket failed: %s\n", strerror(errno));
57 return -1;
58 }
59 if (connect(fd, &addr.sa, len) < 0)
60 {
61 fprintf(stderr, "connecting failed: %s\n", strerror(errno));
62 close(fd);
63 return -1;
64 }
65 return fd;
66 }
67
68 int main(int argc, char *argv[])
69 {
70 char buf[128];
71 int fd, len;
72 u_int16_t msglen;
73
74 fd = make_connection();
75 if (fd < 0)
76 {
77 return 1;
78 }
79 while (1)
80 {
81 len = recv(fd, &msglen, sizeof(msglen), 0);
82 if (len != sizeof(msglen))
83 {
84 break;
85 }
86 msglen = ntohs(msglen);
87 while (msglen)
88 {
89 if (sizeof(buf) > msglen)
90 {
91 len = msglen;
92 }
93 else
94 {
95 len = sizeof(buf);
96 }
97 len = recv(fd, &buf, len, 0);
98 if (len < 0)
99 {
100 break;
101 }
102 msglen -= len;
103 printf("%.*s", len, buf);
104 }
105 printf("\n");
106 if (len < 0)
107 {
108 break;
109 }
110 }
111 fprintf(stderr, "reading from socket failed: %s\n", strerror(errno));
112 close(fd);
113 return 1;
114 }