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