chiark / gitweb /
bring std(in|out|err) fd's in a sane state
[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 pipefds[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(&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         int rc;
640
641         switch (signum) {
642                 case SIGINT:
643                 case SIGTERM:
644                         udev_exit = 1;
645                         break;
646                 case SIGALRM:
647                         /* set flag, then write to pipe if needed */
648                         run_msg_q = 1;
649                         break;
650                 case SIGCHLD:
651                         /* set flag, then write to pipe if needed */
652                         sigchilds_waiting = 1;
653                         break;
654         }
655
656         /* if pipe is empty, write to pipe to force select to return,
657          * which will wakeup our mainloop
658          */
659         if (!sig_flag) {
660                 rc = write(pipefds[1], &signum, sizeof(signum));
661                 if (rc >= 0)
662                         sig_flag = 1;
663         }
664 }
665
666 static void udev_done(int pid)
667 {
668         /* find msg associated with pid and delete it */
669         struct uevent_msg *msg;
670         struct sysinfo info;
671
672         list_for_each_entry(msg, &running_list, node) {
673                 if (msg->pid == pid) {
674                         sysinfo(&info);
675                         info("seq %llu exit, %ld seconds old", msg->seqnum, info.uptime - msg->queue_time);
676                         msg_queue_delete(msg);
677
678                         /* we want to run the exec queue manager since there may
679                          * be events waiting with the devpath of the one that
680                          * just finished
681                          */
682                         run_exec_q = 1;
683                         return;
684                 }
685         }
686 }
687
688 static void reap_sigchilds(void)
689 {
690         pid_t pid;
691
692         while (1) {
693                 pid = waitpid(-1, NULL, WNOHANG);
694                 if (pid <= 0)
695                         break;
696                 udev_done(pid);
697         }
698 }
699
700 static int init_udevd_socket(void)
701 {
702         struct sockaddr_un saddr;
703         const int buffersize = 1024 * 1024;
704         socklen_t addrlen;
705         const int feature_on = 1;
706         int retval;
707
708         memset(&saddr, 0x00, sizeof(saddr));
709         saddr.sun_family = AF_LOCAL;
710         /* use abstract namespace for socket path */
711         strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
712         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
713
714         udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
715         if (udevd_sock == -1) {
716                 err("error getting socket, %s", strerror(errno));
717                 return -1;
718         }
719
720         /* set receive buffersize */
721         setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
722
723         /* the bind takes care of ensuring only one copy running */
724         retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
725         if (retval < 0) {
726                 err("bind failed, %s", strerror(errno));
727                 close(udevd_sock);
728                 return -1;
729         }
730
731         /* enable receiving of the sender credentials */
732         setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
733
734         return 0;
735 }
736
737 static int init_uevent_netlink_sock(void)
738 {
739         struct sockaddr_nl snl;
740         const int buffersize = 1024 * 1024;
741         int retval;
742
743         memset(&snl, 0x00, sizeof(struct sockaddr_nl));
744         snl.nl_family = AF_NETLINK;
745         snl.nl_pid = getpid();
746         snl.nl_groups = 0xffffffff;
747
748         uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
749         if (uevent_netlink_sock == -1) {
750                 dbg("error getting socket, %s", strerror(errno));
751                 return -1;
752         }
753
754         /* set receive buffersize */
755         setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
756
757         retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl,
758                       sizeof(struct sockaddr_nl));
759         if (retval < 0) {
760                 dbg("bind failed, %s", strerror(errno));
761                 close(uevent_netlink_sock);
762                 uevent_netlink_sock = -1;
763                 return -1;
764         }
765
766         return 0;
767 }
768
769 int main(int argc, char *argv[], char *envp[])
770 {
771         int retval;
772         int devnull;
773         struct sigaction act;
774         fd_set readfds;
775         const char *value;
776         int uevent_netlink_active = 0;
777         int daemonize = 0;
778         int i;
779
780         /* set std fd's to /dev/null, if the kernel forks us, we don't have them at all */
781         devnull = open("/dev/null", O_RDWR);
782         if (devnull >= 0)  {
783                 if (devnull != STDIN_FILENO)
784                         dup2(devnull, STDIN_FILENO);
785                 if (devnull != STDOUT_FILENO)
786                         dup2(devnull, STDOUT_FILENO);
787                 if (devnull != STDERR_FILENO)
788                         dup2(devnull, STDERR_FILENO);
789                 if (devnull > STDERR_FILENO)
790                         close(devnull);
791         }
792
793         logging_init("udevd");
794         if (devnull < 0)
795                 err("fatal, could not open /dev/null");
796
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
817         if (daemonize) {
818                 pid_t pid;
819
820                 pid = fork();
821                 switch (pid) {
822                 case 0:
823                         dbg("damonized fork running");
824                         break;
825                 case -1:
826                         err("fork of daemon failed");
827                         goto exit;
828                 default:
829                         logging_close();
830                         exit(0);
831                 }
832         }
833
834         /* become session leader */
835         sid = setsid();
836         dbg("our session is %d", sid);
837
838         chdir("/");
839         umask(umask(077) | 022);
840
841         /* set a reasonable scheduling priority for the daemon */
842         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
843
844         /* setup signal handler pipe */
845         retval = pipe(pipefds);
846         if (retval < 0) {
847                 err("error getting pipes: %s", strerror(errno));
848                 goto exit;
849         }
850         retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
851         if (retval < 0) {
852                 err("error fcntl on read pipe: %s", strerror(errno));
853                 goto exit;
854         }
855         retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
856         if (retval < 0)
857                 err("error fcntl on read pipe: %s", strerror(errno));
858         retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
859         if (retval < 0) {
860                 err("error fcntl on write pipe: %s", strerror(errno));
861                 goto exit;
862         }
863         retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
864         if (retval < 0)
865                 err("error fcntl on write pipe: %s", strerror(errno));
866
867         /* set signal handlers */
868         memset(&act, 0x00, sizeof(struct sigaction));
869         act.sa_handler = (void (*)(int)) sig_handler;
870         sigemptyset(&act.sa_mask);
871         act.sa_flags = SA_RESTART;
872         sigaction(SIGINT, &act, NULL);
873         sigaction(SIGTERM, &act, NULL);
874         sigaction(SIGALRM, &act, NULL);
875         sigaction(SIGCHLD, &act, NULL);
876         sigaction(SIGHUP, &act, NULL);
877
878         if (init_udevd_socket() < 0) {
879                 if (errno == EADDRINUSE)
880                         dbg("another udevd running, exit");
881                 else
882                         dbg("error initialising udevd socket: %s", strerror(errno));
883
884                 goto exit;
885         }
886
887         if (init_uevent_netlink_sock() < 0)
888                 info("uevent socket not available");
889
890         /* override of forked udev binary, used for testing */
891         udev_bin = getenv("UDEV_BIN");
892         if (udev_bin != NULL)
893                 info("udev binary is set to '%s'", udev_bin);
894         else
895                 udev_bin = UDEV_BIN;
896
897         /* init of expected_seqnum value */
898         value = getenv("UDEVD_EXPECTED_SEQNUM");
899         if (value) {
900                 expected_seqnum = strtoull(value, NULL, 10);
901                 info("initialize expected_seqnum to %llu", expected_seqnum);
902         }
903
904         /* timeout to wait for missing events */
905         value = getenv("UDEVD_EVENT_TIMEOUT");
906         if (value)
907                 event_timeout = strtoul(value, NULL, 10);
908         else
909                 event_timeout = UDEVD_EVENT_TIMEOUT;
910         info("initialize event_timeout to %u", event_timeout);
911
912         /* maximum limit of forked childs */
913         value = getenv("UDEVD_MAX_CHILDS");
914         if (value)
915                 max_childs = strtoul(value, NULL, 10);
916         else
917                 max_childs = UDEVD_MAX_CHILDS;
918         info("initialize max_childs to %u", max_childs);
919
920         /* start to throttle forking if maximum number of _running_ childs is reached */
921         value = getenv("UDEVD_MAX_CHILDS_RUNNING");
922         if (value)
923                 max_childs_running = strtoull(value, NULL, 10);
924         else
925                 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
926         info("initialize max_childs_running to %u", max_childs_running);
927
928         /* export log_priority , as called programs may want to follow that setting */
929         sprintf(log, "UDEV_LOG=%i", udev_log_priority);
930         putenv(log);
931
932         while (!udev_exit) {
933                 struct uevent_msg *msg;
934                 int fdcount;
935
936                 FD_ZERO(&readfds);
937                 FD_SET(pipefds[0], &readfds);
938                 FD_SET(udevd_sock, &readfds);
939                 if (uevent_netlink_sock > 0)
940                         FD_SET(uevent_netlink_sock, &readfds);
941
942                 fdcount = select(UDEV_MAX(udevd_sock, uevent_netlink_sock)+1, &readfds, NULL, NULL, NULL);
943                 if (fdcount < 0) {
944                         if (errno != EINTR)
945                                 dbg("error in select: %s", strerror(errno));
946                         continue;
947                 }
948
949                 /* get user socket message */
950                 if (FD_ISSET(udevd_sock, &readfds)) {
951                         msg = get_udevd_msg();
952                         if (msg) {
953                                 /* discard kernel messages if netlink is active */
954                                 if (uevent_netlink_active && msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
955                                         dbg("skip uevent_helper message, netlink is active");
956                                         free(msg);
957                                         continue;
958                                 }
959                                 msg_queue_insert(msg);
960                         }
961                 }
962
963                 /* get kernel netlink message */
964                 if ((uevent_netlink_sock > 0) && FD_ISSET(uevent_netlink_sock, &readfds)) {
965                         msg = get_netlink_msg();
966                         if (msg) {
967                                 msg_queue_insert(msg);
968                                 /* disable udevsend with first netlink message */
969                                 if (!uevent_netlink_active) {
970                                         info("uevent_nl message received, disable udevsend messages");
971                                         uevent_netlink_active = 1;
972                                 }
973                         }
974                 }
975
976                 /* received a signal, clear our notification pipe */
977                 if (FD_ISSET(pipefds[0], &readfds)) {
978                         int sig;
979                         ssize_t rlen;
980
981                         while(1) {
982                                 rlen = read(pipefds[0], &sig, sizeof(sig));
983                                 if (rlen <= 0)
984                                         break;
985                         }
986                         sig_flag = 0;
987                 }
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         if (uevent_netlink_sock > 0)
1022                 close(uevent_netlink_sock);
1023
1024         logging_close();
1025
1026         return 0;
1027 }