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