03fea9c761252e1aef94305146ce48244158407e
[oweals/busybox.git] / sysklogd / syslogd.c
1 /* userver.c - simple server for Unix domain sockets */
2
3 /* Waits for a connection on the ./sample-socket Unix domain
4    socket. Once a connection has been established, copy data
5    from the socket to stdout until the other end closes the
6    connection, and then wait for another connection to the socket. */
7
8 #include <stdio.h>
9 #include <sys/socket.h>
10 #include <sys/un.h>
11 #include <unistd.h>
12
13 #define _PATH_LOG       "/dev/log"
14
15
16 /* issue an error message via perror() and terminate the program */
17 void die(char * message) {
18     perror(message);
19     exit(1);
20 }
21
22 /* Copies data from file descriptor 'from' to file descriptor 'to'
23    until nothing is left to be copied. Exits if an error occurs.   */
24 void copyData(int from, int to) {
25     char buf[1024];
26     int amount;
27     
28     while ((amount = read(from, buf, sizeof(buf))) > 0) {
29         if (write(to, buf, amount) != amount) {
30             die("write");
31             return;
32         }
33     }
34     if (amount < 0)
35         die("read");
36 }
37
38
39 int main(void) {
40     struct sockaddr_un address;
41     int fd, conn;
42     size_t addrLength;
43
44     /* Remove any preexisting socket (or other file) */
45     unlink(_PATH_LOG);
46
47     memset(&address, 0, sizeof(address));
48     address.sun_family = AF_UNIX;       /* Unix domain socket */
49     strncpy(address.sun_path, _PATH_LOG, sizeof(address.sun_path));
50
51     if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
52         die("socket");
53
54
55     /* The total length of the address includes the sun_family 
56        element */
57     addrLength = sizeof(address.sun_family) + 
58                  strlen(address.sun_path);
59
60     if (bind(fd, (struct sockaddr *) &address, addrLength))
61         die("bind");
62
63     if (chmod(_PATH_LOG, 0666) < 0)
64         die("chmod");
65
66     if (listen(fd, 5))
67         die("listen");
68
69
70     while ((conn = accept(fd, (struct sockaddr *) &address, 
71                           &addrLength)) >= 0) {
72         printf("---- getting data\n");
73         copyData(conn, fileno(stdout));
74         printf("---- done\n");
75         close(conn);
76     }
77
78     if (conn < 0) 
79         die("accept");
80     
81     close(fd);
82     return 0;
83 }
84
85
86