ucode: check for errors in ftruncate()
[project/udebug.git] / main.c
1 #include <sys/stat.h>
2 #include <sys/socket.h>
3 #include <getopt.h>
4 #include <string.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <errno.h>
8
9 #include <libubox/usock.h>
10
11 #include "server.h"
12
13 static struct uloop_fd server_fd;
14 static char *socket_name;
15 int debug_level = 3;
16
17 static void server_fd_cb(struct uloop_fd *ufd, unsigned int events)
18 {
19 D(3, "cb");
20 while (1) {
21 int fd = accept(ufd->fd, NULL, 0);
22 if (fd < 0) {
23 if (errno == EINTR || errno == ECONNABORTED)
24 continue;
25 return;
26 }
27
28 client_alloc(fd);
29 }
30 }
31
32 static int usage(const char *progname)
33 {
34 fprintf(stderr, "Usage: %s [options]\n"
35 "Options:\n"
36 " -s <name>: Set path to socket\n"
37 "\n", progname);
38 return 1;
39 }
40
41 static void mkdir_sockdir(void)
42 {
43 char *sep;
44
45 sep = strrchr(socket_name, '/');
46 if (!sep)
47 return;
48
49 *sep = 0;
50 mkdir(socket_name, 0755);
51 *sep = '/';
52 }
53
54 int main(int argc, char **argv)
55 {
56 int ret = -1;
57 int ch;
58
59 while ((ch = getopt(argc, argv, "s:")) != -1) {
60 switch (ch) {
61 case 's':
62 socket_name = optarg;
63 break;
64 default:
65 return usage(argv[0]);
66 }
67 }
68
69 if (!socket_name)
70 socket_name = strdup(UDEBUG_SOCK_NAME);
71
72 signal(SIGPIPE, SIG_IGN);
73
74 uloop_init();
75
76 unlink(socket_name);
77 mkdir_sockdir();
78 umask(0111);
79 server_fd.cb = server_fd_cb;
80 server_fd.fd = usock(USOCK_UNIX | USOCK_SERVER | USOCK_NONBLOCK, socket_name, NULL);
81 if (server_fd.fd < 0) {
82 perror("usock");
83 goto out;
84 }
85
86 uloop_fd_add(&server_fd, ULOOP_READ);
87 udebug_ubus_init();
88 uloop_run();
89
90 out:
91 udebug_ubus_free();
92 unlink(socket_name);
93 uloop_done();
94
95 return ret;
96 }