chiark / gitweb /
IMPORT: do not mangle whitespace
[elogind.git] / udevd.c
1 /*
2  * Copyright (C) 2004-2006 Kay Sievers <kay.sievers@vrfy.org>
3  * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
4  *
5  *      This program is free software; you can redistribute it and/or modify it
6  *      under the terms of the GNU General Public License as published by the
7  *      Free Software Foundation version 2 of the License.
8  *
9  *      This program is distributed in the hope that it will be useful, but
10  *      WITHOUT ANY WARRANTY; without even the implied warranty of
11  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  *      General Public License for more details.
13  *
14  *      You should have received a copy of the GNU General Public License along
15  *      with this program; if not, write to the Free Software Foundation, Inc.,
16  *      51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  *
18  */
19
20 #include <stddef.h>
21 #include <signal.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
28 #include <dirent.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <time.h>
32 #include <getopt.h>
33 #include <sys/select.h>
34 #include <sys/wait.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/un.h>
38 #include <sys/stat.h>
39 #include <sys/ioctl.h>
40 #include <linux/types.h>
41 #include <linux/netlink.h>
42
43 #include "udev.h"
44 #include "udev_rules.h"
45 #include "udevd.h"
46 #include "udev_selinux.h"
47
48 static int debug_trace;
49 static int verbose;
50
51 static struct udev_rules rules;
52 static int udevd_sock = -1;
53 static int uevent_netlink_sock = -1;
54 static int inotify_fd = -1;
55 static pid_t sid;
56
57 static int signal_pipe[2] = {-1, -1};
58 static volatile int sigchilds_waiting;
59 static volatile int udev_exit;
60 static volatile int reload_config;
61 static int run_exec_q;
62 static int stop_exec_q;
63 static int max_childs;
64 static int max_childs_running;
65 static char udev_log[32];
66
67 static LIST_HEAD(exec_list);
68 static LIST_HEAD(running_list);
69
70
71 #ifdef USE_LOG
72 void log_message(int priority, const char *format, ...)
73 {
74         va_list args;
75
76         if (priority > udev_log_priority)
77                 return;
78
79         va_start(args, format);
80         vsyslog(priority, format, args);
81         va_end(args);
82
83         if (verbose) {
84                 va_start(args, format);
85                 vprintf(format, args);
86                 va_end(args);
87                 printf("\n");
88         }
89 }
90
91 #endif
92
93 static void asmlinkage udev_event_sig_handler(int signum)
94 {
95         if (signum == SIGALRM)
96                 exit(1);
97 }
98
99 static int udev_event_process(struct udevd_uevent_msg *msg)
100 {
101         struct sigaction act;
102         struct udevice *udev;
103         int i;
104         int retval;
105
106         /* set signal handlers */
107         memset(&act, 0x00, sizeof(act));
108         act.sa_handler = (void (*)(int)) udev_event_sig_handler;
109         sigemptyset (&act.sa_mask);
110         act.sa_flags = 0;
111         sigaction(SIGALRM, &act, NULL);
112
113         /* reset to default */
114         act.sa_handler = SIG_DFL;
115         sigaction(SIGINT, &act, NULL);
116         sigaction(SIGTERM, &act, NULL);
117         sigaction(SIGCHLD, &act, NULL);
118         sigaction(SIGHUP, &act, NULL);
119
120         /* trigger timeout to prevent hanging processes */
121         alarm(UDEV_ALARM_TIMEOUT);
122
123         /* reconstruct event environment from message */
124         for (i = 0; msg->envp[i]; i++)
125                 putenv(msg->envp[i]);
126
127         udev = udev_device_init(NULL);
128         if (udev == NULL)
129                 return -1;
130         strlcpy(udev->action, msg->action, sizeof(udev->action));
131         sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem, msg->driver);
132         udev->devt = msg->devt;
133
134         retval = udev_device_event(&rules, udev);
135
136         /* run programs collected by RUN-key*/
137         if (retval == 0 && !udev->ignore_device && udev_run) {
138                 struct name_entry *name_loop;
139
140                 dbg("executing run list");
141                 list_for_each_entry(name_loop, &udev->run_list, node) {
142                         if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
143                                 pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
144                         else {
145                                 char program[PATH_SIZE];
146
147                                 strlcpy(program, name_loop->name, sizeof(program));
148                                 udev_rules_apply_format(udev, program, sizeof(program));
149                                 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
150                                                 (udev_log_priority >= LOG_INFO)))
151                                         retval = -1;
152                         }
153                 }
154         }
155
156         udev_device_cleanup(udev);
157         return retval;
158 }
159
160 enum event_state {
161         EVENT_QUEUED,
162         EVENT_FINISHED,
163         EVENT_FAILED,
164 };
165
166 static void export_event_state(struct udevd_uevent_msg *msg, enum event_state state)
167 {
168         char filename[PATH_SIZE];
169         char filename_failed[PATH_SIZE];
170         size_t start;
171         struct udevd_uevent_msg *loop_msg;
172         int fd;
173
174         /* add location of queue files */
175         strlcpy(filename, udev_root, sizeof(filename));
176         strlcat(filename, "/", sizeof(filename));
177         start = strlcat(filename, EVENT_QUEUE_DIR"/", sizeof(filename));
178         strlcat(filename, msg->devpath, sizeof(filename));
179         path_encode(&filename[start], sizeof(filename) - start);
180
181         /* add location of failed files */
182         strlcpy(filename_failed, udev_root, sizeof(filename_failed));
183         strlcat(filename_failed, "/", sizeof(filename_failed));
184         start = strlcat(filename_failed, EVENT_FAILED_DIR"/", sizeof(filename_failed));
185         strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
186         path_encode(&filename_failed[start], sizeof(filename) - start);
187
188         switch (state) {
189         case EVENT_QUEUED:
190                 unlink(filename_failed);
191                 delete_path(filename_failed);
192                 create_path(filename);
193                 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
194                 if (fd > 0)
195                         close(fd);
196                 return;
197         case EVENT_FINISHED:
198         case EVENT_FAILED:
199                 unlink(filename_failed);
200                 delete_path(filename_failed);
201
202                 /* don't remove, if events for the same path are still pending */
203                 list_for_each_entry(loop_msg, &running_list, node)
204                         if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
205                                 return;
206
207                 list_for_each_entry(loop_msg, &exec_list, node)
208                         if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
209                                 return;
210
211                 /* move failed events to the failed directory */
212                 if (state == EVENT_FAILED) {
213                         create_path(filename_failed);
214                         rename(filename, filename_failed);
215                 } else {
216                         unlink(filename);
217                 }
218
219                 /* clean up the queue directory */
220                 delete_path(filename);
221
222                 return;
223         }
224 }
225
226 static void msg_queue_delete(struct udevd_uevent_msg *msg)
227 {
228         list_del(&msg->node);
229
230         /* mark as failed, if add event returns non-zero */
231         if (msg->exitstatus && strcmp(msg->action, "add") == 0)
232                 export_event_state(msg, EVENT_FAILED);
233         else
234                 export_event_state(msg, EVENT_FINISHED);
235
236         free(msg);
237 }
238
239 static void udev_event_run(struct udevd_uevent_msg *msg)
240 {
241         pid_t pid;
242         int retval;
243
244         pid = fork();
245         switch (pid) {
246         case 0:
247                 /* child */
248                 close(uevent_netlink_sock);
249                 close(udevd_sock);
250                 if (inotify_fd >= 0)
251                         close(inotify_fd);
252                 close(signal_pipe[READ_END]);
253                 close(signal_pipe[WRITE_END]);
254                 logging_close();
255
256                 logging_init("udevd-event");
257                 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
258
259                 retval = udev_event_process(msg);
260                 info("seq %llu finished", msg->seqnum);
261
262                 logging_close();
263                 if (retval)
264                         exit(1);
265                 exit(0);
266         case -1:
267                 err("fork of child failed: %s", strerror(errno));
268                 msg_queue_delete(msg);
269                 break;
270         default:
271                 /* get SIGCHLD in main loop */
272                 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
273                      msg->seqnum, pid,  msg->action, msg->subsystem, time(NULL) - msg->queue_time);
274                 msg->pid = pid;
275         }
276 }
277
278 static void msg_queue_insert(struct udevd_uevent_msg *msg)
279 {
280         char filename[PATH_SIZE];
281         int fd;
282
283         msg->queue_time = time(NULL);
284
285         strlcpy(filename, udev_root, sizeof(filename));
286         strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
287         fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
288         if (fd >= 0) {
289                 char str[32];
290                 int len;
291
292                 len = sprintf(str, "%llu\n", msg->seqnum);
293                 write(fd, str, len);
294                 close(fd);
295         }
296
297         export_event_state(msg, EVENT_QUEUED);
298
299         /* run one event after the other in debug mode */
300         if (debug_trace) {
301                 list_add_tail(&msg->node, &running_list);
302                 udev_event_run(msg);
303                 waitpid(msg->pid, NULL, 0);
304                 msg_queue_delete(msg);
305                 return;
306         }
307
308         /* run all events with a timeout set immediately */
309         if (msg->timeout != 0) {
310                 list_add_tail(&msg->node, &running_list);
311                 udev_event_run(msg);
312                 return;
313         }
314
315         list_add_tail(&msg->node, &exec_list);
316         run_exec_q = 1;
317 }
318
319 static int mem_size_mb(void)
320 {
321         FILE* f;
322         char buf[4096];
323         long int memsize = -1;
324
325         f = fopen("/proc/meminfo", "r");
326         if (f == NULL)
327                 return -1;
328
329         while (fgets(buf, sizeof(buf), f) != NULL) {
330                 long int value;
331
332                 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
333                         memsize = value / 1024;
334                         break;
335                 }
336         }
337
338         fclose(f);
339         return memsize;
340 }
341
342 static int cpu_count(void)
343 {
344         FILE* f;
345         char buf[4096];
346         int count = 0;
347
348         f = fopen("/proc/stat", "r");
349         if (f == NULL)
350                 return -1;
351
352         while (fgets(buf, sizeof(buf), f) != NULL) {
353                 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
354                         count++;
355         }
356
357         fclose(f);
358         if (count == 0)
359                 return -1;
360         return count;
361 }
362
363 static int running_processes(void)
364 {
365         FILE* f;
366         char buf[4096];
367         int running = -1;
368
369         f = fopen("/proc/stat", "r");
370         if (f == NULL)
371                 return -1;
372
373         while (fgets(buf, sizeof(buf), f) != NULL) {
374                 int value;
375
376                 if (sscanf(buf, "procs_running %u", &value) == 1) {
377                         running = value;
378                         break;
379                 }
380         }
381
382         fclose(f);
383         return running;
384 }
385
386 /* return the number of process es in our session, count only until limit */
387 static int running_processes_in_session(pid_t session, int limit)
388 {
389         DIR *dir;
390         struct dirent *dent;
391         int running = 0;
392
393         dir = opendir("/proc");
394         if (!dir)
395                 return -1;
396
397         /* read process info from /proc */
398         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
399                 int f;
400                 char procdir[64];
401                 char line[256];
402                 const char *pos;
403                 char state;
404                 pid_t ppid, pgrp, sess;
405                 int len;
406
407                 if (!isdigit(dent->d_name[0]))
408                         continue;
409
410                 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
411                 procdir[sizeof(procdir)-1] = '\0';
412
413                 f = open(procdir, O_RDONLY);
414                 if (f == -1)
415                         continue;
416
417                 len = read(f, line, sizeof(line)-1);
418                 close(f);
419
420                 if (len <= 0)
421                         continue;
422                 else
423                         line[len] = '\0';
424
425                 /* skip ugly program name */
426                 pos = strrchr(line, ')') + 2;
427                 if (pos == NULL)
428                         continue;
429
430                 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
431                         continue;
432
433                 /* count only processes in our session */
434                 if (sess != session)
435                         continue;
436
437                 /* count only running, no sleeping processes */
438                 if (state != 'R')
439                         continue;
440
441                 running++;
442                 if (limit > 0 && running >= limit)
443                         break;
444         }
445         closedir(dir);
446
447         return running;
448 }
449
450 static int compare_devpath(const char *running, const char *waiting)
451 {
452         int i;
453
454         for (i = 0; i < PATH_SIZE; i++) {
455                 /* identical device event found */
456                 if (running[i] == '\0' && waiting[i] == '\0')
457                         return 1;
458
459                 /* parent device event found */
460                 if (running[i] == '\0' && waiting[i] == '/')
461                         return 2;
462
463                 /* child device event found */
464                 if (running[i] == '/' && waiting[i] == '\0')
465                         return 3;
466
467                 /* no matching event */
468                 if (running[i] != waiting[i])
469                         break;
470         }
471
472         return 0;
473 }
474
475 /* lookup event for identical, parent, child, or physical device */
476 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
477 {
478         struct udevd_uevent_msg *loop_msg;
479         int childs_count = 0;
480
481         /* check exec-queue which may still contain delayed events we depend on */
482         list_for_each_entry(loop_msg, &exec_list, node) {
483                 /* skip ourself and all later events */
484                 if (loop_msg->seqnum >= msg->seqnum)
485                         break;
486
487                 /* check identical, parent, or child device event */
488                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
489                         dbg("%llu, device event still pending %llu (%s)",
490                             msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
491                         return 2;
492                 }
493
494                 /* check physical device event (special case of parent) */
495                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
496                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
497                                 dbg("%llu, physical device event still pending %llu (%s)",
498                                     msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
499                                 return 3;
500                         }
501         }
502
503         /* check runing-queue for still running events */
504         list_for_each_entry(loop_msg, &running_list, node) {
505                 if (limit && childs_count++ > limit) {
506                         dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
507                         return 1;
508                 }
509
510                 /* check identical, parent, or child device event */
511                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
512                         dbg("%llu, device event still running %llu (%s)",
513                             msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
514                         return 2;
515                 }
516
517                 /* check physical device event (special case of parent) */
518                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
519                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
520                                 dbg("%llu, physical device event still running %llu (%s)",
521                                     msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
522                                 return 3;
523                         }
524         }
525         return 0;
526 }
527
528 /* serializes events for the identical and parent and child devices */
529 static void msg_queue_manager(void)
530 {
531         struct udevd_uevent_msg *loop_msg;
532         struct udevd_uevent_msg *tmp_msg;
533         int running;
534
535         if (list_empty(&exec_list))
536                 return;
537
538         running = running_processes();
539         dbg("%d processes runnning on system", running);
540         if (running < 0)
541                 running = max_childs_running;
542
543         list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
544                 /* check running processes in our session and possibly throttle */
545                 if (running >= max_childs_running) {
546                         running = running_processes_in_session(sid, max_childs_running+10);
547                         dbg("at least %d processes running in session", running);
548                         if (running >= max_childs_running) {
549                                 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
550                                 return;
551                         }
552                 }
553
554                 /* serialize and wait for parent or child events */
555                 if (devpath_busy(loop_msg, max_childs) != 0) {
556                         dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
557                         continue;
558                 }
559
560                 /* move event to run list */
561                 list_move_tail(&loop_msg->node, &running_list);
562                 udev_event_run(loop_msg);
563                 running++;
564                 dbg("moved seq %llu to running list", loop_msg->seqnum);
565         }
566 }
567
568 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
569 {
570         int bufpos;
571         int i;
572         struct udevd_uevent_msg *msg;
573         char *physdevdriver_key = NULL;
574         int maj = 0;
575         int min = 0;
576
577         msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
578         if (msg == NULL)
579                 return NULL;
580         memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
581
582         /* copy environment buffer and reconstruct envp */
583         memcpy(msg->envbuf, buf, buf_size);
584         bufpos = 0;
585         for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
586                 int keylen;
587                 char *key;
588
589                 key = &msg->envbuf[bufpos];
590                 keylen = strlen(key);
591                 msg->envp[i] = key;
592                 bufpos += keylen + 1;
593                 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
594
595                 /* remember some keys for further processing */
596                 if (strncmp(key, "ACTION=", 7) == 0)
597                         msg->action = &key[7];
598                 else if (strncmp(key, "DEVPATH=", 8) == 0)
599                         msg->devpath = &key[8];
600                 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
601                         msg->subsystem = &key[10];
602                 else if (strncmp(key, "DRIVER=", 7) == 0)
603                         msg->driver = &key[7];
604                 else if (strncmp(key, "SEQNUM=", 7) == 0)
605                         msg->seqnum = strtoull(&key[7], NULL, 10);
606                 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
607                         msg->physdevpath = &key[12];
608                 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
609                         physdevdriver_key = key;
610                 else if (strncmp(key, "MAJOR=", 6) == 0)
611                         maj = strtoull(&key[6], NULL, 10);
612                 else if (strncmp(key, "MINOR=", 6) == 0)
613                         min = strtoull(&key[6], NULL, 10);
614                 else if (strncmp(key, "TIMEOUT=", 8) == 0)
615                         msg->timeout = strtoull(&key[8], NULL, 10);
616         }
617         msg->devt = makedev(maj, min);
618         msg->envp[i++] = "UDEVD_EVENT=1";
619
620         if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
621                 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
622                 msg->envp[i++] = &physdevdriver_key[7];
623                 msg->driver = &physdevdriver_key[14];
624         }
625
626         msg->envp[i] = NULL;
627
628         if (msg->devpath == NULL || msg->action == NULL) {
629                 info("DEVPATH or ACTION missing, ignore message");
630                 free(msg);
631                 return NULL;
632         }
633         return msg;
634 }
635
636 /* receive the udevd message from userspace */
637 static void get_ctrl_msg(void)
638 {
639         struct udevd_ctrl_msg ctrl_msg;
640         ssize_t size;
641         struct msghdr smsg;
642         struct cmsghdr *cmsg;
643         struct iovec iov;
644         struct ucred *cred;
645         char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
646         int *intval;
647         char *pos;
648
649         memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
650         iov.iov_base = &ctrl_msg;
651         iov.iov_len = sizeof(struct udevd_ctrl_msg);
652
653         memset(&smsg, 0x00, sizeof(struct msghdr));
654         smsg.msg_iov = &iov;
655         smsg.msg_iovlen = 1;
656         smsg.msg_control = cred_msg;
657         smsg.msg_controllen = sizeof(cred_msg);
658
659         size = recvmsg(udevd_sock, &smsg, 0);
660         if (size <  0) {
661                 if (errno != EINTR)
662                         err("unable to receive user udevd message: %s", strerror(errno));
663                 return;
664         }
665         cmsg = CMSG_FIRSTHDR(&smsg);
666         cred = (struct ucred *) CMSG_DATA(cmsg);
667
668         if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
669                 err("no sender credentials received, message ignored");
670                 return;
671         }
672
673         if (cred->uid != 0) {
674                 err("sender uid=%i, message ignored", cred->uid);
675                 return;
676         }
677
678         if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
679                 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
680                 return;
681         }
682
683         switch (ctrl_msg.type) {
684         case UDEVD_CTRL_ENV:
685                 pos = strchr(ctrl_msg.buf, '=');
686                 if (pos == NULL) {
687                         err("wrong key format '%s'", ctrl_msg.buf);
688                         break;
689                 }
690                 pos[0] = '\0';
691                 if (pos[1] == '\0') {
692                         info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
693                         unsetenv(ctrl_msg.buf);
694                 } else {
695                         info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
696                         setenv(ctrl_msg.buf, &pos[1], 1);
697                 }
698                 break;
699         case UDEVD_CTRL_STOP_EXEC_QUEUE:
700                 info("udevd message (STOP_EXEC_QUEUE) received");
701                 stop_exec_q = 1;
702                 break;
703         case UDEVD_CTRL_START_EXEC_QUEUE:
704                 info("udevd message (START_EXEC_QUEUE) received");
705                 stop_exec_q = 0;
706                 msg_queue_manager();
707                 break;
708         case UDEVD_CTRL_SET_LOG_LEVEL:
709                 intval = (int *) ctrl_msg.buf;
710                 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
711                 udev_log_priority = *intval;
712                 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
713                 putenv(udev_log);
714                 break;
715         case UDEVD_CTRL_SET_MAX_CHILDS:
716                 intval = (int *) ctrl_msg.buf;
717                 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
718                 max_childs = *intval;
719                 break;
720         case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
721                 intval = (int *) ctrl_msg.buf;
722                 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
723                 max_childs_running = *intval;
724                 break;
725         case UDEVD_CTRL_RELOAD_RULES:
726                 info("udevd message (RELOAD_RULES) received");
727                 reload_config = 1;
728                 break;
729         default:
730                 err("unknown control message type");
731         }
732 }
733
734 /* receive the kernel user event message and do some sanity checks */
735 static struct udevd_uevent_msg *get_netlink_msg(void)
736 {
737         struct udevd_uevent_msg *msg;
738         int bufpos;
739         ssize_t size;
740         static char buffer[UEVENT_BUFFER_SIZE+512];
741         char *pos;
742
743         size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
744         if (size <  0) {
745                 if (errno != EINTR)
746                         err("unable to receive kernel netlink message: %s", strerror(errno));
747                 return NULL;
748         }
749
750         if ((size_t)size > sizeof(buffer)-1)
751                 size = sizeof(buffer)-1;
752         buffer[size] = '\0';
753         dbg("uevent_size=%zi", size);
754
755         /* start of event payload */
756         bufpos = strlen(buffer)+1;
757         msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
758         if (msg == NULL)
759                 return NULL;
760
761         /* validate message */
762         pos = strchr(buffer, '@');
763         if (pos == NULL) {
764                 err("invalid uevent '%s'", buffer);
765                 free(msg);
766                 return NULL;
767         }
768         pos[0] = '\0';
769
770         if (msg->action == NULL) {
771                 info("no ACTION in payload found, skip event '%s'", buffer);
772                 free(msg);
773                 return NULL;
774         }
775
776         if (strcmp(msg->action, buffer) != 0) {
777                 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
778                 free(msg);
779                 return NULL;
780         }
781
782         return msg;
783 }
784
785 static void asmlinkage sig_handler(int signum)
786 {
787         switch (signum) {
788                 case SIGINT:
789                 case SIGTERM:
790                         udev_exit = 1;
791                         break;
792                 case SIGCHLD:
793                         /* set flag, then write to pipe if needed */
794                         sigchilds_waiting = 1;
795                         break;
796                 case SIGHUP:
797                         reload_config = 1;
798                         break;
799         }
800
801         /* write to pipe, which will wakeup select() in our mainloop */
802         write(signal_pipe[WRITE_END], "", 1);
803 }
804
805 static void udev_done(int pid, int exitstatus)
806 {
807         /* find msg associated with pid and delete it */
808         struct udevd_uevent_msg *msg;
809
810         list_for_each_entry(msg, &running_list, node) {
811                 if (msg->pid == pid) {
812                         info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
813                              exitstatus, time(NULL) - msg->queue_time);
814                         msg->exitstatus = exitstatus;
815                         msg_queue_delete(msg);
816
817                         /* there may be events waiting with the same devpath */
818                         run_exec_q = 1;
819                         return;
820                 }
821         }
822 }
823
824 static void reap_sigchilds(void)
825 {
826         pid_t pid;
827         int status;
828
829         while (1) {
830                 pid = waitpid(-1, &status, WNOHANG);
831                 if (pid <= 0)
832                         break;
833                 if (WIFEXITED(status))
834                         status = WEXITSTATUS(status);
835                 else if (WIFSIGNALED(status))
836                         status = WTERMSIG(status) + 128;
837                 else
838                         status = 0;
839                 udev_done(pid, status);
840         }
841 }
842
843 static int init_udevd_socket(void)
844 {
845         struct sockaddr_un saddr;
846         socklen_t addrlen;
847         const int feature_on = 1;
848         int retval;
849
850         memset(&saddr, 0x00, sizeof(saddr));
851         saddr.sun_family = AF_LOCAL;
852         /* use abstract namespace for socket path */
853         strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
854         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
855
856         udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
857         if (udevd_sock == -1) {
858                 err("error getting socket: %s", strerror(errno));
859                 return -1;
860         }
861
862         /* the bind takes care of ensuring only one copy running */
863         retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
864         if (retval < 0) {
865                 err("bind failed: %s", strerror(errno));
866                 close(udevd_sock);
867                 udevd_sock = -1;
868                 return -1;
869         }
870
871         /* enable receiving of the sender credentials */
872         setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
873
874         return 0;
875 }
876
877 static int init_uevent_netlink_sock(void)
878 {
879         struct sockaddr_nl snl;
880         const int buffersize = 16 * 1024 * 1024;
881         int retval;
882
883         memset(&snl, 0x00, sizeof(struct sockaddr_nl));
884         snl.nl_family = AF_NETLINK;
885         snl.nl_pid = getpid();
886         snl.nl_groups = 1;
887
888         uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
889         if (uevent_netlink_sock == -1) {
890                 err("error getting socket: %s", strerror(errno));
891                 return -1;
892         }
893
894         /* set receive buffersize */
895         setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
896
897         retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
898         if (retval < 0) {
899                 err("bind failed: %s", strerror(errno));
900                 close(uevent_netlink_sock);
901                 uevent_netlink_sock = -1;
902                 return -1;
903         }
904         return 0;
905 }
906
907 static void export_initial_seqnum(void)
908 {
909         char filename[PATH_SIZE];
910         int fd;
911         char seqnum[32];
912         ssize_t len = 0;
913
914         strlcpy(filename, sysfs_path, sizeof(filename));
915         strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
916         fd = open(filename, O_RDONLY);
917         if (fd >= 0) {
918                 len = read(fd, seqnum, sizeof(seqnum)-1);
919                 close(fd);
920         }
921         if (len <= 0) {
922                 strcpy(seqnum, "0\n");
923                 len = 3;
924         }
925         strlcpy(filename, udev_root, sizeof(filename));
926         strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
927         create_path(filename);
928         fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
929         if (fd >= 0) {
930                 write(fd, seqnum, len);
931                 close(fd);
932         }
933 }
934
935 int main(int argc, char *argv[], char *envp[])
936 {
937         int retval;
938         int fd;
939         struct sigaction act;
940         fd_set readfds;
941         const char *value;
942         int daemonize = 0;
943         int option;
944         static const struct option options[] = {
945                 { "daemon", 0, NULL, 'd' },
946                 { "debug-trace", 0, NULL, 't' },
947                 { "verbose", 0, NULL, 'v' },
948                 { "help", 0, NULL, 'h' },
949                 { "version", 0, NULL, 'V' },
950                 {}
951         };
952         int rc = 1;
953         int maxfd;
954
955         logging_init("udevd");
956         udev_config_init();
957         selinux_init();
958         dbg("version %s", UDEV_VERSION);
959
960         /* parse commandline options */
961         while (1) {
962                 option = getopt_long(argc, argv, "dtvhV", options, NULL);
963                 if (option == -1)
964                         break;
965
966                 switch (option) {
967                 case 'd':
968                         daemonize = 1;
969                         break;
970                 case 't':
971                         debug_trace = 1;
972                         break;
973                 case 'v':
974                         verbose = 1;
975                         if (udev_log_priority < LOG_INFO)
976                                 udev_log_priority = LOG_INFO;
977                         break;
978                 case 'h':
979                         printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
980                         goto exit;
981                 case 'V':
982                         printf("%s\n", UDEV_VERSION);
983                         goto exit;
984                 default:
985                         goto exit;
986                 }
987         }
988
989         if (getuid() != 0) {
990                 fprintf(stderr, "root privileges required\n");
991                 err("root privileges required");
992                 goto exit;
993         }
994
995         /* make sure std{in,out,err} fd's are in a sane state */
996         fd = open("/dev/null", O_RDWR);
997         if (fd < 0) {
998                 fprintf(stderr, "cannot open /dev/null\n");
999                 err("cannot open /dev/null");
1000         }
1001         if (fd > STDIN_FILENO)
1002                 dup2(fd, STDIN_FILENO);
1003         if (write(STDOUT_FILENO, 0, 0) < 0)
1004                 dup2(fd, STDOUT_FILENO);
1005         if (write(STDERR_FILENO, 0, 0) < 0)
1006                 dup2(fd, STDERR_FILENO);
1007
1008         /* init sockets to receive events */
1009         if (init_udevd_socket() < 0) {
1010                 if (errno == EADDRINUSE) {
1011                         fprintf(stderr, "another udev daemon already running\n");
1012                         err("another udev daemon already running");
1013                         rc = 1;
1014                 } else {
1015                         fprintf(stderr, "error initializing udevd socket\n");
1016                         err("error initializing udevd socket");
1017                         rc = 2;
1018                 }
1019                 goto exit;
1020         }
1021
1022         if (init_uevent_netlink_sock() < 0) {
1023                 fprintf(stderr, "error initializing netlink socket\n");
1024                 err("error initializing netlink socket");
1025                 rc = 3;
1026                 goto exit;
1027         }
1028
1029         /* setup signal handler pipe */
1030         retval = pipe(signal_pipe);
1031         if (retval < 0) {
1032                 err("error getting pipes: %s", strerror(errno));
1033                 goto exit;
1034         }
1035
1036         retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1037         if (retval < 0) {
1038                 err("error fcntl on read pipe: %s", strerror(errno));
1039                 goto exit;
1040         }
1041         retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1042         if (retval < 0) {
1043                 err("error fcntl on read pipe: %s", strerror(errno));
1044                 goto exit;
1045         }
1046
1047         retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1048         if (retval < 0) {
1049                 err("error fcntl on write pipe: %s", strerror(errno));
1050                 goto exit;
1051         }
1052         retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1053         if (retval < 0) {
1054                 err("error fcntl on write pipe: %s", strerror(errno));
1055                 goto exit;
1056         }
1057
1058         /* parse the rules and keep them in memory */
1059         sysfs_init();
1060         udev_rules_init(&rules, 1);
1061
1062         export_initial_seqnum();
1063
1064         if (daemonize) {
1065                 pid_t pid;
1066
1067                 pid = fork();
1068                 switch (pid) {
1069                 case 0:
1070                         dbg("daemonized fork running");
1071                         break;
1072                 case -1:
1073                         err("fork of daemon failed: %s", strerror(errno));
1074                         rc = 4;
1075                         goto exit;
1076                 default:
1077                         dbg("child [%u] running, parent exits", pid);
1078                         rc = 0;
1079                         goto exit;
1080                 }
1081         }
1082
1083         /* redirect std{out,err} fd's */
1084         if (!verbose)
1085                 dup2(fd, STDOUT_FILENO);
1086         dup2(fd, STDERR_FILENO);
1087         if (fd > STDERR_FILENO)
1088                 close(fd);
1089
1090         /* set scheduling priority for the daemon */
1091         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1092
1093         chdir("/");
1094         umask(022);
1095
1096         /* become session leader */
1097         sid = setsid();
1098         dbg("our session is %d", sid);
1099
1100         /* OOM_DISABLE == -17 */
1101         fd = open("/proc/self/oom_adj", O_RDWR);
1102         if (fd < 0)
1103                 err("error disabling OOM: %s", strerror(errno));
1104         else {
1105                 write(fd, "-17", 3);
1106                 close(fd);
1107         }
1108
1109         /* set signal handlers */
1110         memset(&act, 0x00, sizeof(struct sigaction));
1111         act.sa_handler = (void (*)(int)) sig_handler;
1112         sigemptyset(&act.sa_mask);
1113         act.sa_flags = SA_RESTART;
1114         sigaction(SIGINT, &act, NULL);
1115         sigaction(SIGTERM, &act, NULL);
1116         sigaction(SIGCHLD, &act, NULL);
1117         sigaction(SIGHUP, &act, NULL);
1118
1119         /* watch rules directory */
1120         inotify_fd = inotify_init();
1121         if (inotify_fd >= 0)
1122                 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1123         else if (errno == ENOSYS)
1124                 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1125         else
1126                 err("inotify_init failed: %s", strerror(errno));
1127
1128         /* maximum limit of forked childs */
1129         value = getenv("UDEVD_MAX_CHILDS");
1130         if (value)
1131                 max_childs = strtoul(value, NULL, 10);
1132         else {
1133                 int memsize = mem_size_mb();
1134                 if (memsize > 0)
1135                         max_childs = 128 + (memsize / 4);
1136                 else
1137                         max_childs = UDEVD_MAX_CHILDS;
1138         }
1139         info("initialize max_childs to %u", max_childs);
1140
1141         /* start to throttle forking if maximum number of _running_ childs is reached */
1142         value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1143         if (value)
1144                 max_childs_running = strtoull(value, NULL, 10);
1145         else {
1146                 int cpus = cpu_count();
1147                 if (cpus > 0)
1148                         max_childs_running = 8 + (8 * cpus);
1149                 else
1150                         max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1151         }
1152         info("initialize max_childs_running to %u", max_childs_running);
1153
1154         /* clear environment for forked event processes */
1155         clearenv();
1156
1157         /* export log_priority , as called programs may want to follow that setting */
1158         sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1159         putenv(udev_log);
1160         if (debug_trace)
1161                 putenv("DEBUG=1");
1162
1163         maxfd = udevd_sock;
1164         maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1165         maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1166         maxfd = UDEV_MAX(maxfd, inotify_fd);
1167
1168         while (!udev_exit) {
1169                 struct udevd_uevent_msg *msg;
1170                 int fdcount;
1171
1172                 FD_ZERO(&readfds);
1173                 FD_SET(signal_pipe[READ_END], &readfds);
1174                 FD_SET(udevd_sock, &readfds);
1175                 FD_SET(uevent_netlink_sock, &readfds);
1176                 if (inotify_fd >= 0)
1177                         FD_SET(inotify_fd, &readfds);
1178
1179                 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1180                 if (fdcount < 0) {
1181                         if (errno != EINTR)
1182                                 err("error in select: %s", strerror(errno));
1183                         continue;
1184                 }
1185
1186                 /* get control message */
1187                 if (FD_ISSET(udevd_sock, &readfds))
1188                         get_ctrl_msg();
1189
1190                 /* get netlink message */
1191                 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1192                         msg = get_netlink_msg();
1193                         if (msg)
1194                                 msg_queue_insert(msg);
1195                 }
1196
1197                 /* received a signal, clear our notification pipe */
1198                 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1199                         char buf[256];
1200
1201                         read(signal_pipe[READ_END], &buf, sizeof(buf));
1202                 }
1203
1204                 /* rules directory inotify watch */
1205                 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1206                         int nbytes;
1207
1208                         /* discard all possible events, we can just reload the config */
1209                         if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1210                                 char *buf;
1211
1212                                 reload_config = 1;
1213                                 buf = malloc(nbytes);
1214                                 if (!buf) {
1215                                         err("error getting buffer for inotify, disable watching");
1216                                         close(inotify_fd);
1217                                         inotify_fd = -1;
1218                                 }
1219                                 read(inotify_fd, buf, nbytes);
1220                                 free(buf);
1221                         }
1222                 }
1223
1224                 /* rules changed, set by inotify or a HUP signal */
1225                 if (reload_config) {
1226                         reload_config = 0;
1227                         udev_rules_cleanup(&rules);
1228                         udev_rules_init(&rules, 1);
1229                 }
1230
1231                 /* forked child has returned */
1232                 if (sigchilds_waiting) {
1233                         sigchilds_waiting = 0;
1234                         reap_sigchilds();
1235                 }
1236
1237                 if (run_exec_q) {
1238                         run_exec_q = 0;
1239                         if (!stop_exec_q)
1240                                 msg_queue_manager();
1241                 }
1242         }
1243         rc = 0;
1244
1245 exit:
1246         udev_rules_cleanup(&rules);
1247         sysfs_cleanup();
1248         selinux_exit();
1249
1250         if (signal_pipe[READ_END] >= 0)
1251                 close(signal_pipe[READ_END]);
1252         if (signal_pipe[WRITE_END] >= 0)
1253                 close(signal_pipe[WRITE_END]);
1254
1255         if (udevd_sock >= 0)
1256                 close(udevd_sock);
1257         if (inotify_fd >= 0)
1258                 close(inotify_fd);
1259         if (uevent_netlink_sock >= 0)
1260                 close(uevent_netlink_sock);
1261
1262         logging_close();
1263
1264         return rc;
1265 }