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