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