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