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