aboutsummaryrefslogtreecommitdiffstats
path: root/small-codes/syslog-listen.c
blob: 4b582718f285cc95a60795c32c90f2f8dead4e4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// This program is able to listen to a datagram unix socket displaying
// a linefeed at each receive. Useful when other program wants scrutinize
// syslog forwarded outputs for example (like in omuxsock module by rsyslog
// does).
//
// compile with gcc/clang -o syslog-listen syslog-listen.c


#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>

#define PERROR(code, msg) { if ((code) == -1) { perror((msg)); exit(1); } }

int main(int argc, const char** argv)
{
    if (argc < 2) {
        fprintf(stderr, "Usage: syslog-listen </path>\n");
        exit(1);
    }

    struct sockaddr_un sock_file;
    memset(&sock_file, 0, sizeof(sock_file));
    sock_file.sun_family = AF_UNIX;
    strncpy(sock_file.sun_path, argv[1], sizeof(sock_file.sun_path));

    int sock = socket(AF_UNIX, SOCK_DGRAM, 0);
    PERROR(sock, "socket");
    unlink(argv[1]); // no need to test ret as bind will crash if needed
    umask(0007); // by default allow user/group calling the program
    int ret = bind(sock, (struct sockaddr*)&sock_file, sizeof(sock_file));
    PERROR(ret, "bind");

    char buf[8192 + 1];
    int received;
    while (1) {
        received = recv(sock, buf, sizeof(buf)-1, 0);
        PERROR(received, "recv");
        buf[received] = '\n';
        write(1, buf, received+1);
    }

    return 0;
}