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