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