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