chiark / gitweb /
udevd: ignore all messages without DEVPATH
[elogind.git] / udevd.c
1 /*
2  * udevd.c - event listener and serializer
3  *
4  * Copyright (C) 2004-2005 Kay Sievers <kay.sievers@vrfy.org>
5  * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
6  *
7  *
8  *      This program is free software; you can redistribute it and/or modify it
9  *      under the terms of the GNU General Public License as published by the
10  *      Free Software Foundation version 2 of the License.
11  *
12  *      This program is distributed in the hope that it will be useful, but
13  *      WITHOUT ANY WARRANTY; without even the implied warranty of
14  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *      General Public License for more details.
16  *
17  *      You should have received a copy of the GNU General Public License along
18  *      with this program; if not, write to the Free Software Foundation, Inc.,
19  *      675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22
23 #include <stddef.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <dirent.h>
32 #include <fcntl.h>
33 #include <syslog.h>
34 #include <time.h>
35 #include <sys/select.h>
36 #include <sys/wait.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40 #include <sys/stat.h>
41 #include <sys/ioctl.h>
42 #include <linux/types.h>
43 #include <linux/netlink.h>
44
45 #include "list.h"
46 #include "udev_libc_wrapper.h"
47 #include "udev.h"
48 #include "udev_version.h"
49 #include "udev_rules.h"
50 #include "udev_utils.h"
51 #include "udevd.h"
52 #include "logging.h"
53
54 struct udev_rules rules;
55 static int udevd_sock;
56 static int uevent_netlink_sock;
57 static int inotify_fd;
58 static pid_t sid;
59
60 static int signal_pipe[2] = {-1, -1};
61 static volatile int sigchilds_waiting;
62 static volatile int udev_exit;
63 static volatile int reload_config;
64 static int run_exec_q;
65 static int stop_exec_q;
66 static int max_childs;
67 static int max_childs_running;
68 static char udev_log[32];
69
70 static LIST_HEAD(exec_list);
71 static LIST_HEAD(running_list);
72
73
74 #ifdef USE_LOG
75 void log_message(int priority, const char *format, ...)
76 {
77         va_list args;
78
79         if (priority > udev_log_priority)
80                 return;
81
82         va_start(args, format);
83         vsyslog(priority, format, args);
84         va_end(args);
85 }
86 #endif
87
88 static void asmlinkage udev_event_sig_handler(int signum)
89 {
90         if (signum == SIGALRM)
91                 exit(1);
92 }
93
94 static int udev_event_process(struct uevent_msg *msg)
95 {
96         struct sigaction act;
97         struct udevice udev;
98         struct name_entry *name_loop;
99         int i;
100         int retval;
101
102         /* set signal handlers */
103         memset(&act, 0x00, sizeof(act));
104         act.sa_handler = (void (*)(int)) udev_event_sig_handler;
105         sigemptyset (&act.sa_mask);
106         act.sa_flags = 0;
107         sigaction(SIGALRM, &act, NULL);
108
109         /* trigger timeout to prevent hanging processes */
110         alarm(UDEV_ALARM_TIMEOUT);
111
112         /* reconstruct env from message */
113         for (i = 0; msg->envp[i]; i++)
114                 putenv(msg->envp[i]);
115
116         udev_init_device(&udev, msg->devpath, msg->subsystem, msg->action);
117         retval = udev_process_event(&rules, &udev);
118
119         /* run programs collected by RUN-key*/
120         if (!retval) {
121                 list_for_each_entry(name_loop, &udev.run_list, node) {
122                         if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
123                                 pass_env_to_socket(&name_loop->name[strlen("socket:")], msg->devpath, msg->action);
124                         else
125                                 run_program(name_loop->name, udev.subsystem, NULL, 0, NULL, (udev_log_priority >= LOG_INFO));
126                 }
127         }
128
129         udev_cleanup_device(&udev);
130
131         return 0;
132 }
133
134 static void msg_queue_delete(struct uevent_msg *msg)
135 {
136         list_del(&msg->node);
137         free(msg);
138 }
139
140 static void udev_event_run(struct uevent_msg *msg)
141 {
142         pid_t pid;
143
144         pid = fork();
145         switch (pid) {
146         case 0:
147                 /* child */
148                 close(uevent_netlink_sock);
149                 close(udevd_sock);
150                 if (inotify_fd > 0)
151                         close(inotify_fd);
152                 close(signal_pipe[READ_END]);
153                 close(signal_pipe[WRITE_END]);
154                 logging_close();
155
156                 logging_init("udevd-event");
157                 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
158                 udev_event_process(msg);
159                 info("seq %llu finished", msg->seqnum);
160
161                 logging_close();
162                 exit(0);
163         case -1:
164                 err("fork of child failed: %s", strerror(errno));
165                 msg_queue_delete(msg);
166                 break;
167         default:
168                 /* get SIGCHLD in main loop */
169                 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
170                      msg->seqnum, pid,  msg->action, msg->subsystem, time(NULL) - msg->queue_time);
171                 msg->pid = pid;
172         }
173 }
174
175 static void msg_queue_insert(struct uevent_msg *msg)
176 {
177         msg->queue_time = time(NULL);
178
179         /* run all events with a timeout set immediately */
180         if (msg->timeout != 0) {
181                 list_add_tail(&msg->node, &running_list);
182                 udev_event_run(msg);
183                 return;
184         }
185
186         list_add_tail(&msg->node, &exec_list);
187         run_exec_q = 1;
188 }
189
190 /* runs event and removes event from run queue when finished */
191 static int running_processes(void)
192 {
193         int f;
194         static char buf[4096];
195         int len;
196         int running;
197         const char *pos;
198
199         f = open("/proc/stat", O_RDONLY);
200         if (f == -1)
201                 return -1;
202
203         len = read(f, buf, sizeof(buf)-1);
204         close(f);
205
206         if (len <= 0)
207                 return -1;
208         else
209                 buf[len] = '\0';
210
211         pos = strstr(buf, "procs_running ");
212         if (pos == NULL)
213                 return -1;
214
215         if (sscanf(pos, "procs_running %u", &running) != 1)
216                 return -1;
217
218         return running;
219 }
220
221 /* return the number of process es in our session, count only until limit */
222 static int running_processes_in_session(pid_t session, int limit)
223 {
224         DIR *dir;
225         struct dirent *dent;
226         int running = 0;
227
228         dir = opendir("/proc");
229         if (!dir)
230                 return -1;
231
232         /* read process info from /proc */
233         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
234                 int f;
235                 char procdir[64];
236                 char line[256];
237                 const char *pos;
238                 char state;
239                 pid_t ppid, pgrp, sess;
240                 int len;
241
242                 if (!isdigit(dent->d_name[0]))
243                         continue;
244
245                 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
246                 procdir[sizeof(procdir)-1] = '\0';
247
248                 f = open(procdir, O_RDONLY);
249                 if (f == -1)
250                         continue;
251
252                 len = read(f, line, sizeof(line)-1);
253                 close(f);
254
255                 if (len <= 0)
256                         continue;
257                 else
258                         line[len] = '\0';
259
260                 /* skip ugly program name */
261                 pos = strrchr(line, ')') + 2;
262                 if (pos == NULL)
263                         continue;
264
265                 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
266                         continue;
267
268                 /* count only processes in our session */
269                 if (sess != session)
270                         continue;
271
272                 /* count only running, no sleeping processes */
273                 if (state != 'R')
274                         continue;
275
276                 running++;
277                 if (limit > 0 && running >= limit)
278                         break;
279         }
280         closedir(dir);
281
282         return running;
283 }
284
285 static int compare_devpath(const char *running, const char *waiting)
286 {
287         int i;
288
289         for (i = 0; i < PATH_SIZE; i++) {
290                 /* identical device event found */
291                 if (running[i] == '\0' && waiting[i] == '\0')
292                         return 1;
293
294                 /* parent device event found */
295                 if (running[i] == '\0' && waiting[i] == '/')
296                         return 2;
297
298                 /* child device event found */
299                 if (running[i] == '/' && waiting[i] == '\0')
300                         return 3;
301
302                 /* no matching event */
303                 if (running[i] != waiting[i])
304                         break;
305         }
306
307         return 0;
308 }
309
310 /* returns still running task for the same device, its parent or its physical device */
311 static int running_with_devpath(struct uevent_msg *msg, int limit)
312 {
313         struct uevent_msg *loop_msg;
314         int childs_count = 0;
315
316         list_for_each_entry(loop_msg, &running_list, node) {
317                 if (limit && childs_count++ > limit) {
318                         dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
319                         return 1;
320                 }
321
322                 /* return running parent/child device event */
323                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
324                         dbg("%llu, child device event still running %llu (%s)",
325                             msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
326                         return 2;
327                 }
328
329                 /* return running physical device event */
330                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
331                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
332                                 dbg("%llu, physical device event still running %llu (%s)",
333                                     msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
334                                 return 3;
335                         }
336         }
337
338         return 0;
339 }
340
341 /* exec queue management routine executes the events and serializes events in the same sequence */
342 static void msg_queue_manager(void)
343 {
344         struct uevent_msg *loop_msg;
345         struct uevent_msg *tmp_msg;
346         int running;
347
348         if (list_empty(&exec_list))
349                 return;
350
351         running = running_processes();
352         dbg("%d processes runnning on system", running);
353         if (running < 0)
354                 running = max_childs_running;
355
356         list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
357                 /* check running processes in our session and possibly throttle */
358                 if (running >= max_childs_running) {
359                         running = running_processes_in_session(sid, max_childs_running+10);
360                         dbg("at least %d processes running in session", running);
361                         if (running >= max_childs_running) {
362                                 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
363                                 return;
364                         }
365                 }
366
367                 /* don't run two processes for the same devpath and wait for the parent*/
368                 if (running_with_devpath(loop_msg, max_childs)) {
369                         dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
370                         continue;
371                 }
372
373                 /* move event to run list */
374                 list_move_tail(&loop_msg->node, &running_list);
375                 udev_event_run(loop_msg);
376                 running++;
377                 dbg("moved seq %llu to running list", loop_msg->seqnum);
378         }
379 }
380
381 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
382 {
383         int bufpos;
384         int i;
385         struct uevent_msg *msg;
386         int major = 0;
387         int minor = 0;
388
389         msg = malloc(sizeof(struct uevent_msg) + buf_size);
390         if (msg == NULL)
391                 return NULL;
392         memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
393
394         /* copy environment buffer and reconstruct envp */
395         memcpy(msg->envbuf, buf, buf_size);
396         bufpos = 0;
397         for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
398                 int keylen;
399                 char *key;
400
401                 key = &msg->envbuf[bufpos];
402                 keylen = strlen(key);
403                 msg->envp[i] = key;
404                 bufpos += keylen + 1;
405                 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
406
407                 /* remember some keys for further processing */
408                 if (strncmp(key, "ACTION=", 7) == 0)
409                         msg->action = &key[7];
410                 else if (strncmp(key, "DEVPATH=", 8) == 0)
411                         msg->devpath = &key[8];
412                 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
413                         msg->subsystem = &key[10];
414                 else if (strncmp(key, "SEQNUM=", 7) == 0)
415                         msg->seqnum = strtoull(&key[7], NULL, 10);
416                 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
417                         msg->physdevpath = &key[12];
418                 else if (strncmp(key, "MAJOR=", 6) == 0)
419                         major = strtoull(&key[6], NULL, 10);
420                 else if (strncmp(key, "MINOR=", 6) == 0)
421                         minor = strtoull(&key[6], NULL, 10);
422                 else if (strncmp(key, "TIMEOUT=", 8) == 0)
423                         msg->timeout = strtoull(&key[8], NULL, 10);
424         }
425         msg->devt = makedev(major, minor);
426         msg->envp[i++] = "UDEVD_EVENT=1";
427         msg->envp[i] = NULL;
428
429         if (!msg->devpath) {
430                 info("DEVPATH missing, ingnore message");
431                 free(msg);
432                 return NULL;
433         }
434
435         return msg;
436 }
437
438 /* receive the udevd message from userspace */
439 static struct uevent_msg *get_udevd_msg(void)
440 {
441         static struct udevd_msg usend_msg;
442         struct uevent_msg *msg;
443         ssize_t size;
444         struct msghdr smsg;
445         struct cmsghdr *cmsg;
446         struct iovec iov;
447         struct ucred *cred;
448         char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
449         int envbuf_size;
450         int *intval;
451
452         memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
453         iov.iov_base = &usend_msg;
454         iov.iov_len = sizeof(struct udevd_msg);
455
456         memset(&smsg, 0x00, sizeof(struct msghdr));
457         smsg.msg_iov = &iov;
458         smsg.msg_iovlen = 1;
459         smsg.msg_control = cred_msg;
460         smsg.msg_controllen = sizeof(cred_msg);
461
462         size = recvmsg(udevd_sock, &smsg, 0);
463         if (size <  0) {
464                 if (errno != EINTR)
465                         err("unable to receive udevd message: %s", strerror(errno));
466                 return NULL;
467         }
468         cmsg = CMSG_FIRSTHDR(&smsg);
469         cred = (struct ucred *) CMSG_DATA(cmsg);
470
471         if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
472                 err("no sender credentials received, message ignored");
473                 return NULL;
474         }
475
476         if (cred->uid != 0) {
477                 err("sender uid=%i, message ignored", cred->uid);
478                 return NULL;
479         }
480
481         if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
482                 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
483                 return NULL;
484         }
485
486         switch (usend_msg.type) {
487         case UDEVD_UEVENT_UDEVSEND:
488         case UDEVD_UEVENT_INITSEND:
489                 info("udevd event message received");
490                 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
491                 dbg("envbuf_size=%i", envbuf_size);
492                 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
493                 if (msg == NULL)
494                         return NULL;
495                 msg->type = usend_msg.type;
496                 return msg;
497         case UDEVD_STOP_EXEC_QUEUE:
498                 info("udevd message (STOP_EXEC_QUEUE) received");
499                 stop_exec_q = 1;
500                 break;
501         case UDEVD_START_EXEC_QUEUE:
502                 info("udevd message (START_EXEC_QUEUE) received");
503                 stop_exec_q = 0;
504                 msg_queue_manager();
505                 break;
506         case UDEVD_SET_LOG_LEVEL:
507                 intval = (int *) usend_msg.envbuf;
508                 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
509                 udev_log_priority = *intval;
510                 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
511                 putenv(udev_log);
512                 break;
513         case UDEVD_SET_MAX_CHILDS:
514                 intval = (int *) usend_msg.envbuf;
515                 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
516                 max_childs = *intval;
517                 break;
518         case UDEVD_RELOAD_RULES:
519                 info("udevd message (RELOAD_RULES) received");
520                 reload_config = 1;
521                 break;
522         default:
523                 dbg("unknown message type");
524         }
525         return NULL;
526 }
527
528 /* receive the kernel user event message and do some sanity checks */
529 static struct uevent_msg *get_netlink_msg(void)
530 {
531         struct uevent_msg *msg;
532         int bufpos;
533         ssize_t size;
534         static char buffer[UEVENT_BUFFER_SIZE + 512];
535         char *pos;
536
537         size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
538         if (size <  0) {
539                 if (errno != EINTR)
540                         err("unable to receive udevd message: %s", strerror(errno));
541                 return NULL;
542         }
543
544         if ((size_t)size > sizeof(buffer)-1)
545                 size = sizeof(buffer)-1;
546         buffer[size] = '\0';
547         dbg("uevent_size=%zi", size);
548
549         /* start of event payload */
550         bufpos = strlen(buffer)+1;
551         msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
552         if (msg == NULL)
553                 return NULL;
554         msg->type = UDEVD_UEVENT_NETLINK;
555
556         /* validate message */
557         pos = strchr(buffer, '@');
558         if (pos == NULL) {
559                 err("invalid uevent '%s'", buffer);
560                 free(msg);
561                 return NULL;
562         }
563         pos[0] = '\0';
564
565         if (msg->action == NULL) {
566                 info("no ACTION in payload found, skip event '%s'", buffer);
567                 free(msg);
568                 return NULL;
569         }
570
571         if (strcmp(msg->action, buffer) != 0) {
572                 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
573                 free(msg);
574                 return NULL;
575         }
576
577         return msg;
578 }
579
580 static void asmlinkage sig_handler(int signum)
581 {
582         switch (signum) {
583                 case SIGINT:
584                 case SIGTERM:
585                         udev_exit = 1;
586                         break;
587                 case SIGCHLD:
588                         /* set flag, then write to pipe if needed */
589                         sigchilds_waiting = 1;
590                         break;
591                 case SIGHUP:
592                         reload_config = 1;
593                         break;
594         }
595
596         /* write to pipe, which will wakeup select() in our mainloop */
597         write(signal_pipe[WRITE_END], "", 1);
598 }
599
600 static void udev_done(int pid)
601 {
602         /* find msg associated with pid and delete it */
603         struct uevent_msg *msg;
604
605         list_for_each_entry(msg, &running_list, node) {
606                 if (msg->pid == pid) {
607                         info("seq %llu, pid [%d] exit, %ld seconds old", msg->seqnum, msg->pid, time(NULL) - msg->queue_time);
608                         msg_queue_delete(msg);
609
610                         /* there may be events waiting with the same devpath */
611                         run_exec_q = 1;
612                         return;
613                 }
614         }
615 }
616
617 static void reap_sigchilds(void)
618 {
619         pid_t pid;
620
621         while (1) {
622                 pid = waitpid(-1, NULL, WNOHANG);
623                 if (pid <= 0)
624                         break;
625                 udev_done(pid);
626         }
627 }
628
629 static int init_udevd_socket(void)
630 {
631         struct sockaddr_un saddr;
632         const int buffersize = 16 * 1024 * 1024;
633         socklen_t addrlen;
634         const int feature_on = 1;
635         int retval;
636
637         memset(&saddr, 0x00, sizeof(saddr));
638         saddr.sun_family = AF_LOCAL;
639         /* use abstract namespace for socket path */
640         strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
641         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
642
643         udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
644         if (udevd_sock == -1) {
645                 err("error getting socket: %s", strerror(errno));
646                 return -1;
647         }
648
649         /* set receive buffersize */
650         setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
651
652         /* the bind takes care of ensuring only one copy running */
653         retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
654         if (retval < 0) {
655                 err("bind failed: %s", strerror(errno));
656                 return -1;
657         }
658
659         /* enable receiving of the sender credentials */
660         setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
661
662         return 0;
663 }
664
665 static int init_uevent_netlink_sock(void)
666 {
667         struct sockaddr_nl snl;
668         const int buffersize = 16 * 1024 * 1024;
669         int retval;
670
671         memset(&snl, 0x00, sizeof(struct sockaddr_nl));
672         snl.nl_family = AF_NETLINK;
673         snl.nl_pid = getpid();
674         snl.nl_groups = 0xffffffff;
675
676         uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
677         if (uevent_netlink_sock == -1) {
678                 err("error getting socket: %s", strerror(errno));
679                 return -1;
680         }
681
682         /* set receive buffersize */
683         setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
684
685         retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
686         if (retval < 0) {
687                 err("bind failed: %s", strerror(errno));
688                 close(uevent_netlink_sock);
689                 uevent_netlink_sock = -1;
690                 return -1;
691         }
692         return 0;
693 }
694
695 int main(int argc, char *argv[], char *envp[])
696 {
697         int retval;
698         int fd;
699         struct sigaction act;
700         fd_set readfds;
701         const char *value;
702         int daemonize = 0;
703         int i;
704         int rc = 0;
705         int maxfd;
706
707         /* redirect std fd's, if the kernel forks us, we don't have them at all */
708         fd = open("/dev/null", O_RDWR);
709         if (fd >= 0) {
710                 if (fd != STDIN_FILENO)
711                         dup2(fd, STDIN_FILENO);
712                 if (fd != STDOUT_FILENO)
713                         dup2(fd, STDOUT_FILENO);
714                 if (fd != STDERR_FILENO)
715                         dup2(fd, STDERR_FILENO);
716                 if (fd > STDERR_FILENO)
717                         close(fd);
718         }
719
720         logging_init("udevd");
721         if (fd < 0)
722                 err("fatal, could not open /dev/null: %s", strerror(errno));
723
724         udev_init_config();
725         dbg("version %s", UDEV_VERSION);
726
727         if (getuid() != 0) {
728                 err("need to be root, exit");
729                 goto exit;
730         }
731
732         /* parse commandline options */
733         for (i = 1 ; i < argc; i++) {
734                 char *arg = argv[i];
735                 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
736                         info("will daemonize");
737                         daemonize = 1;
738                 }
739                 if (strcmp(arg, "--stop-exec-queue") == 0) {
740                         info("will not execute events until START_EXEC_QUEUE is received");
741                         stop_exec_q = 1;
742                 }
743         }
744
745         /* init sockets to receive events */
746         if (init_udevd_socket() < 0) {
747                 if (errno == EADDRINUSE) {
748                         err("another udevd running, exit");
749                         rc = 1;
750                 } else {
751                         err("error initializing udevd socket: %s", strerror(errno));
752                         rc = 2;
753                 }
754                 goto exit;
755         }
756
757         if (init_uevent_netlink_sock() < 0) {
758                 err("uevent socket not available");
759                 rc = 3;
760                 goto exit;
761         }
762
763         /* parse the rules and keep it in memory */
764         udev_rules_init(&rules, 1);
765
766         if (daemonize) {
767                 pid_t pid;
768
769                 pid = fork();
770                 switch (pid) {
771                 case 0:
772                         dbg("daemonized fork running");
773                         break;
774                 case -1:
775                         err("fork of daemon failed: %s", strerror(errno));
776                         rc = 4;
777                         goto exit;
778                 default:
779                         dbg("child [%u] running, parent exits", pid);
780                         goto exit;
781                 }
782         }
783
784         /* set scheduling priority for the daemon */
785         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
786
787         chdir("/");
788         umask(022);
789
790         /* become session leader */
791         sid = setsid();
792         dbg("our session is %d", sid);
793
794         /* OOM_DISABLE == -17 */
795         fd = open("/proc/self/oom_adj", O_RDWR);
796         if (fd < 0)
797                 err("error disabling OOM: %s", strerror(errno));
798         else {
799                 write(fd, "-17", 3);
800                 close(fd);
801         }
802
803         /* setup signal handler pipe */
804         retval = pipe(signal_pipe);
805         if (retval < 0) {
806                 err("error getting pipes: %s", strerror(errno));
807                 goto exit;
808         }
809         retval = fcntl(signal_pipe[READ_END], F_SETFL, O_NONBLOCK);
810         if (retval < 0) {
811                 err("error fcntl on read pipe: %s", strerror(errno));
812                 goto exit;
813         }
814         retval = fcntl(signal_pipe[WRITE_END], F_SETFL, O_NONBLOCK);
815         if (retval < 0) {
816                 err("error fcntl on write pipe: %s", strerror(errno));
817                 goto exit;
818         }
819
820         /* set signal handlers */
821         memset(&act, 0x00, sizeof(struct sigaction));
822         act.sa_handler = (void (*)(int)) sig_handler;
823         sigemptyset(&act.sa_mask);
824         act.sa_flags = SA_RESTART;
825         sigaction(SIGINT, &act, NULL);
826         sigaction(SIGTERM, &act, NULL);
827         sigaction(SIGCHLD, &act, NULL);
828         sigaction(SIGHUP, &act, NULL);
829
830         /* watch rules directory */
831         inotify_fd = inotify_init();
832         if (inotify_fd > 0)
833                 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
834
835         /* maximum limit of forked childs */
836         value = getenv("UDEVD_MAX_CHILDS");
837         if (value)
838                 max_childs = strtoul(value, NULL, 10);
839         else
840                 max_childs = UDEVD_MAX_CHILDS;
841         info("initialize max_childs to %u", max_childs);
842
843         /* start to throttle forking if maximum number of _running_ childs is reached */
844         value = getenv("UDEVD_MAX_CHILDS_RUNNING");
845         if (value)
846                 max_childs_running = strtoull(value, NULL, 10);
847         else
848                 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
849         info("initialize max_childs_running to %u", max_childs_running);
850
851         /* clear environment for forked event processes */
852         clearenv();
853
854         /* export log_priority , as called programs may want to follow that setting */
855         sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
856         putenv(udev_log);
857
858         maxfd = udevd_sock;
859         maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
860         maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
861         maxfd = UDEV_MAX(maxfd, inotify_fd);
862
863         while (!udev_exit) {
864                 struct uevent_msg *msg;
865                 int fdcount;
866
867                 FD_ZERO(&readfds);
868                 FD_SET(signal_pipe[READ_END], &readfds);
869                 FD_SET(udevd_sock, &readfds);
870                 FD_SET(uevent_netlink_sock, &readfds);
871                 if (inotify_fd > 0)
872                         FD_SET(inotify_fd, &readfds);
873
874                 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
875                 if (fdcount < 0) {
876                         if (errno != EINTR)
877                                 err("error in select: %s", strerror(errno));
878                         continue;
879                 }
880
881                 /* get user socket message */
882                 if (FD_ISSET(udevd_sock, &readfds)) {
883                         msg = get_udevd_msg();
884                         if (msg) {
885                                 if (msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
886                                         info("skip non-kernel message with SEQNUM");
887                                         free(msg);
888                                 } else
889                                         msg_queue_insert(msg);
890                         }
891                 }
892
893                 /* get kernel netlink message */
894                 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
895                         msg = get_netlink_msg();
896                         if (msg)
897                                 msg_queue_insert(msg);
898                 }
899
900                 /* received a signal, clear our notification pipe */
901                 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
902                         char buf[256];
903
904                         read(signal_pipe[READ_END], &buf, sizeof(buf));
905                 }
906
907                 /* rules directory inotify watch */
908                 if ((inotify_fd > 0) && FD_ISSET(inotify_fd, &readfds)) {
909                         int nbytes;
910
911                         /* discard all possible events, we can just reload the config */
912                         if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
913                                 char *buf;
914
915                                 reload_config = 1;
916                                 buf = malloc(nbytes);
917                                 if (!buf) {
918                                         err("error getting buffer for inotify, disable watching");
919                                         close(inotify_fd);
920                                         inotify_fd = -1;
921                                 }
922                                 read(inotify_fd, buf, nbytes);
923                                 free(buf);
924                         }
925                 }
926
927                 /* rules changed, set by inotify or a signal*/
928                 if (reload_config) {
929                         reload_config = 0;
930                         udev_rules_close(&rules);
931                         udev_rules_init(&rules, 1);
932                 }
933
934                 /* forked child has returned */
935                 if (sigchilds_waiting) {
936                         sigchilds_waiting = 0;
937                         reap_sigchilds();
938                 }
939
940                 if (run_exec_q) {
941                         run_exec_q = 0;
942                         if (!stop_exec_q)
943                                 msg_queue_manager();
944                 }
945         }
946
947 exit:
948         udev_rules_close(&rules);
949
950         if (signal_pipe[READ_END] > 0)
951                 close(signal_pipe[READ_END]);
952         if (signal_pipe[WRITE_END] > 0)
953                 close(signal_pipe[WRITE_END]);
954
955         if (udevd_sock > 0)
956                 close(udevd_sock);
957         if (inotify_fd > 0)
958                 close(inotify_fd);
959         if (uevent_netlink_sock > 0)
960                 close(uevent_netlink_sock);
961
962         logging_close();
963
964         return rc;
965 }