chiark / gitweb /
rules: use ID_FS_UUID_SAFE
[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         return memsize;
339 }
340
341 static int cpu_count(void)
342 {
343         FILE* f;
344         char buf[4096];
345         int count = 0;
346
347         f = fopen("/proc/stat", "r");
348         if (f == NULL)
349                 return -1;
350
351         while (fgets(buf, sizeof(buf), f) != NULL) {
352                 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
353                         count++;
354         }
355
356         fclose(f);
357         if (count == 0)
358                 return -1;
359         return count;
360 }
361
362 static int running_processes(void)
363 {
364         FILE* f;
365         char buf[4096];
366         int running = -1;
367
368         f = fopen("/proc/stat", "r");
369         if (f == NULL)
370                 return -1;
371
372         while (fgets(buf, sizeof(buf), f) != NULL) {
373                 int value;
374
375                 if (sscanf(buf, "procs_running %u", &value) == 1) {
376                         running = value;
377                         break;
378                 }
379         }
380
381         fclose(f);
382         return running;
383 }
384
385 /* return the number of process es in our session, count only until limit */
386 static int running_processes_in_session(pid_t session, int limit)
387 {
388         DIR *dir;
389         struct dirent *dent;
390         int running = 0;
391
392         dir = opendir("/proc");
393         if (!dir)
394                 return -1;
395
396         /* read process info from /proc */
397         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
398                 int f;
399                 char procdir[64];
400                 char line[256];
401                 const char *pos;
402                 char state;
403                 pid_t ppid, pgrp, sess;
404                 int len;
405
406                 if (!isdigit(dent->d_name[0]))
407                         continue;
408
409                 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
410                 procdir[sizeof(procdir)-1] = '\0';
411
412                 f = open(procdir, O_RDONLY);
413                 if (f == -1)
414                         continue;
415
416                 len = read(f, line, sizeof(line)-1);
417                 close(f);
418
419                 if (len <= 0)
420                         continue;
421                 else
422                         line[len] = '\0';
423
424                 /* skip ugly program name */
425                 pos = strrchr(line, ')') + 2;
426                 if (pos == NULL)
427                         continue;
428
429                 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
430                         continue;
431
432                 /* count only processes in our session */
433                 if (sess != session)
434                         continue;
435
436                 /* count only running, no sleeping processes */
437                 if (state != 'R')
438                         continue;
439
440                 running++;
441                 if (limit > 0 && running >= limit)
442                         break;
443         }
444         closedir(dir);
445
446         return running;
447 }
448
449 static int compare_devpath(const char *running, const char *waiting)
450 {
451         int i;
452
453         for (i = 0; i < PATH_SIZE; i++) {
454                 /* identical device event found */
455                 if (running[i] == '\0' && waiting[i] == '\0')
456                         return 1;
457
458                 /* parent device event found */
459                 if (running[i] == '\0' && waiting[i] == '/')
460                         return 2;
461
462                 /* child device event found */
463                 if (running[i] == '/' && waiting[i] == '\0')
464                         return 3;
465
466                 /* no matching event */
467                 if (running[i] != waiting[i])
468                         break;
469         }
470
471         return 0;
472 }
473
474 /* lookup event for identical, parent, child, or physical device */
475 static int devpath_busy(struct udevd_uevent_msg *msg, int limit)
476 {
477         struct udevd_uevent_msg *loop_msg;
478         int childs_count = 0;
479
480         /* check exec-queue which may still contain delayed events we depend on */
481         list_for_each_entry(loop_msg, &exec_list, node) {
482                 /* skip ourself and all later events */
483                 if (loop_msg->seqnum >= msg->seqnum)
484                         break;
485
486                 /* check identical, parent, or child device event */
487                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
488                         dbg("%llu, device event still pending %llu (%s)",
489                             msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
490                         return 2;
491                 }
492
493                 /* check physical device event (special case of parent) */
494                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
495                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
496                                 dbg("%llu, physical device event still pending %llu (%s)",
497                                     msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
498                                 return 3;
499                         }
500         }
501
502         /* check runing-queue for still running events */
503         list_for_each_entry(loop_msg, &running_list, node) {
504                 if (limit && childs_count++ > limit) {
505                         dbg("%llu, maximum number (%i) of childs reached", msg->seqnum, childs_count);
506                         return 1;
507                 }
508
509                 /* check identical, parent, or child device event */
510                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
511                         dbg("%llu, device event still running %llu (%s)",
512                             msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
513                         return 2;
514                 }
515
516                 /* check physical device event (special case of parent) */
517                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
518                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
519                                 dbg("%llu, physical device event still running %llu (%s)",
520                                     msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
521                                 return 3;
522                         }
523         }
524         return 0;
525 }
526
527 /* serializes events for the identical and parent and child devices */
528 static void msg_queue_manager(void)
529 {
530         struct udevd_uevent_msg *loop_msg;
531         struct udevd_uevent_msg *tmp_msg;
532         int running;
533
534         if (list_empty(&exec_list))
535                 return;
536
537         running = running_processes();
538         dbg("%d processes runnning on system", running);
539         if (running < 0)
540                 running = max_childs_running;
541
542         list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
543                 /* check running processes in our session and possibly throttle */
544                 if (running >= max_childs_running) {
545                         running = running_processes_in_session(sid, max_childs_running+10);
546                         dbg("at least %d processes running in session", running);
547                         if (running >= max_childs_running) {
548                                 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
549                                 return;
550                         }
551                 }
552
553                 /* serialize and wait for parent or child events */
554                 if (devpath_busy(loop_msg, max_childs) != 0) {
555                         dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
556                         continue;
557                 }
558
559                 /* move event to run list */
560                 list_move_tail(&loop_msg->node, &running_list);
561                 udev_event_run(loop_msg);
562                 running++;
563                 dbg("moved seq %llu to running list", loop_msg->seqnum);
564         }
565 }
566
567 static struct udevd_uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
568 {
569         int bufpos;
570         int i;
571         struct udevd_uevent_msg *msg;
572         char *physdevdriver_key = NULL;
573         int maj = 0;
574         int min = 0;
575
576         msg = malloc(sizeof(struct udevd_uevent_msg) + buf_size);
577         if (msg == NULL)
578                 return NULL;
579         memset(msg, 0x00, sizeof(struct udevd_uevent_msg) + buf_size);
580
581         /* copy environment buffer and reconstruct envp */
582         memcpy(msg->envbuf, buf, buf_size);
583         bufpos = 0;
584         for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
585                 int keylen;
586                 char *key;
587
588                 key = &msg->envbuf[bufpos];
589                 keylen = strlen(key);
590                 msg->envp[i] = key;
591                 bufpos += keylen + 1;
592                 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
593
594                 /* remember some keys for further processing */
595                 if (strncmp(key, "ACTION=", 7) == 0)
596                         msg->action = &key[7];
597                 else if (strncmp(key, "DEVPATH=", 8) == 0)
598                         msg->devpath = &key[8];
599                 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
600                         msg->subsystem = &key[10];
601                 else if (strncmp(key, "DRIVER=", 7) == 0)
602                         msg->driver = &key[7];
603                 else if (strncmp(key, "SEQNUM=", 7) == 0)
604                         msg->seqnum = strtoull(&key[7], NULL, 10);
605                 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
606                         msg->physdevpath = &key[12];
607                 else if (strncmp(key, "PHYSDEVDRIVER=", 14) == 0)
608                         physdevdriver_key = key;
609                 else if (strncmp(key, "MAJOR=", 6) == 0)
610                         maj = strtoull(&key[6], NULL, 10);
611                 else if (strncmp(key, "MINOR=", 6) == 0)
612                         min = strtoull(&key[6], NULL, 10);
613                 else if (strncmp(key, "TIMEOUT=", 8) == 0)
614                         msg->timeout = strtoull(&key[8], NULL, 10);
615         }
616         msg->devt = makedev(maj, min);
617         msg->envp[i++] = "UDEVD_EVENT=1";
618
619         if (msg->driver == NULL && msg->physdevpath == NULL && physdevdriver_key != NULL) {
620                 /* for older kernels DRIVER is empty for a bus device, export PHYSDEVDRIVER as DRIVER */
621                 msg->envp[i++] = &physdevdriver_key[7];
622                 msg->driver = &physdevdriver_key[14];
623         }
624
625         msg->envp[i] = NULL;
626
627         if (msg->devpath == NULL || msg->action == NULL) {
628                 info("DEVPATH or ACTION missing, ignore message");
629                 free(msg);
630                 return NULL;
631         }
632         return msg;
633 }
634
635 /* receive the udevd message from userspace */
636 static void get_ctrl_msg(void)
637 {
638         struct udevd_ctrl_msg ctrl_msg;
639         ssize_t size;
640         struct msghdr smsg;
641         struct cmsghdr *cmsg;
642         struct iovec iov;
643         struct ucred *cred;
644         char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
645         int *intval;
646         char *pos;
647
648         memset(&ctrl_msg, 0x00, sizeof(struct udevd_ctrl_msg));
649         iov.iov_base = &ctrl_msg;
650         iov.iov_len = sizeof(struct udevd_ctrl_msg);
651
652         memset(&smsg, 0x00, sizeof(struct msghdr));
653         smsg.msg_iov = &iov;
654         smsg.msg_iovlen = 1;
655         smsg.msg_control = cred_msg;
656         smsg.msg_controllen = sizeof(cred_msg);
657
658         size = recvmsg(udevd_sock, &smsg, 0);
659         if (size <  0) {
660                 if (errno != EINTR)
661                         err("unable to receive user udevd message: %s", strerror(errno));
662                 return;
663         }
664         cmsg = CMSG_FIRSTHDR(&smsg);
665         cred = (struct ucred *) CMSG_DATA(cmsg);
666
667         if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
668                 err("no sender credentials received, message ignored");
669                 return;
670         }
671
672         if (cred->uid != 0) {
673                 err("sender uid=%i, message ignored", cred->uid);
674                 return;
675         }
676
677         if (strncmp(ctrl_msg.magic, UDEVD_CTRL_MAGIC, sizeof(UDEVD_CTRL_MAGIC)) != 0 ) {
678                 err("message magic '%s' doesn't match, ignore it", ctrl_msg.magic);
679                 return;
680         }
681
682         switch (ctrl_msg.type) {
683         case UDEVD_CTRL_ENV:
684                 pos = strchr(ctrl_msg.buf, '=');
685                 if (pos == NULL) {
686                         err("wrong key format '%s'", ctrl_msg.buf);
687                         break;
688                 }
689                 pos[0] = '\0';
690                 if (pos[1] == '\0') {
691                         info("udevd message (ENV) received, unset '%s'", ctrl_msg.buf);
692                         unsetenv(ctrl_msg.buf);
693                 } else {
694                         info("udevd message (ENV) received, set '%s=%s'", ctrl_msg.buf, &pos[1]);
695                         setenv(ctrl_msg.buf, &pos[1], 1);
696                 }
697                 break;
698         case UDEVD_CTRL_STOP_EXEC_QUEUE:
699                 info("udevd message (STOP_EXEC_QUEUE) received");
700                 stop_exec_q = 1;
701                 break;
702         case UDEVD_CTRL_START_EXEC_QUEUE:
703                 info("udevd message (START_EXEC_QUEUE) received");
704                 stop_exec_q = 0;
705                 msg_queue_manager();
706                 break;
707         case UDEVD_CTRL_SET_LOG_LEVEL:
708                 intval = (int *) ctrl_msg.buf;
709                 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
710                 udev_log_priority = *intval;
711                 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
712                 putenv(udev_log);
713                 break;
714         case UDEVD_CTRL_SET_MAX_CHILDS:
715                 intval = (int *) ctrl_msg.buf;
716                 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
717                 max_childs = *intval;
718                 break;
719         case UDEVD_CTRL_SET_MAX_CHILDS_RUNNING:
720                 intval = (int *) ctrl_msg.buf;
721                 info("udevd message (UDEVD_SET_MAX_CHILDS_RUNNING) received, max_childs=%i", *intval);
722                 max_childs_running = *intval;
723                 break;
724         case UDEVD_CTRL_RELOAD_RULES:
725                 info("udevd message (RELOAD_RULES) received");
726                 reload_config = 1;
727                 break;
728         default:
729                 err("unknown control message type");
730         }
731 }
732
733 /* receive the kernel user event message and do some sanity checks */
734 static struct udevd_uevent_msg *get_netlink_msg(void)
735 {
736         struct udevd_uevent_msg *msg;
737         int bufpos;
738         ssize_t size;
739         static char buffer[UEVENT_BUFFER_SIZE+512];
740         char *pos;
741
742         size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
743         if (size <  0) {
744                 if (errno != EINTR)
745                         err("unable to receive kernel netlink message: %s", strerror(errno));
746                 return NULL;
747         }
748
749         if ((size_t)size > sizeof(buffer)-1)
750                 size = sizeof(buffer)-1;
751         buffer[size] = '\0';
752         dbg("uevent_size=%zi", size);
753
754         /* start of event payload */
755         bufpos = strlen(buffer)+1;
756         msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
757         if (msg == NULL)
758                 return NULL;
759
760         /* validate message */
761         pos = strchr(buffer, '@');
762         if (pos == NULL) {
763                 err("invalid uevent '%s'", buffer);
764                 free(msg);
765                 return NULL;
766         }
767         pos[0] = '\0';
768
769         if (msg->action == NULL) {
770                 info("no ACTION in payload found, skip event '%s'", buffer);
771                 free(msg);
772                 return NULL;
773         }
774
775         if (strcmp(msg->action, buffer) != 0) {
776                 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
777                 free(msg);
778                 return NULL;
779         }
780
781         return msg;
782 }
783
784 static void asmlinkage sig_handler(int signum)
785 {
786         switch (signum) {
787                 case SIGINT:
788                 case SIGTERM:
789                         udev_exit = 1;
790                         break;
791                 case SIGCHLD:
792                         /* set flag, then write to pipe if needed */
793                         sigchilds_waiting = 1;
794                         break;
795                 case SIGHUP:
796                         reload_config = 1;
797                         break;
798         }
799
800         /* write to pipe, which will wakeup select() in our mainloop */
801         write(signal_pipe[WRITE_END], "", 1);
802 }
803
804 static void udev_done(int pid, int exitstatus)
805 {
806         /* find msg associated with pid and delete it */
807         struct udevd_uevent_msg *msg;
808
809         list_for_each_entry(msg, &running_list, node) {
810                 if (msg->pid == pid) {
811                         info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
812                              exitstatus, time(NULL) - msg->queue_time);
813                         msg->exitstatus = exitstatus;
814                         msg_queue_delete(msg);
815
816                         /* there may be events waiting with the same devpath */
817                         run_exec_q = 1;
818                         return;
819                 }
820         }
821 }
822
823 static void reap_sigchilds(void)
824 {
825         pid_t pid;
826         int status;
827
828         while (1) {
829                 pid = waitpid(-1, &status, WNOHANG);
830                 if (pid <= 0)
831                         break;
832                 if (WIFEXITED(status))
833                         status = WEXITSTATUS(status);
834                 else if (WIFSIGNALED(status))
835                         status = WTERMSIG(status) + 128;
836                 else
837                         status = 0;
838                 udev_done(pid, status);
839         }
840 }
841
842 static int init_udevd_socket(void)
843 {
844         struct sockaddr_un saddr;
845         socklen_t addrlen;
846         const int feature_on = 1;
847         int retval;
848
849         memset(&saddr, 0x00, sizeof(saddr));
850         saddr.sun_family = AF_LOCAL;
851         /* use abstract namespace for socket path */
852         strcpy(&saddr.sun_path[1], UDEVD_CTRL_SOCK_PATH);
853         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
854
855         udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
856         if (udevd_sock == -1) {
857                 err("error getting socket: %s", strerror(errno));
858                 return -1;
859         }
860
861         /* the bind takes care of ensuring only one copy running */
862         retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
863         if (retval < 0) {
864                 err("bind failed: %s", strerror(errno));
865                 close(udevd_sock);
866                 udevd_sock = -1;
867                 return -1;
868         }
869
870         /* enable receiving of the sender credentials */
871         setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
872
873         return 0;
874 }
875
876 static int init_uevent_netlink_sock(void)
877 {
878         struct sockaddr_nl snl;
879         const int buffersize = 16 * 1024 * 1024;
880         int retval;
881
882         memset(&snl, 0x00, sizeof(struct sockaddr_nl));
883         snl.nl_family = AF_NETLINK;
884         snl.nl_pid = getpid();
885         snl.nl_groups = 1;
886
887         uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
888         if (uevent_netlink_sock == -1) {
889                 err("error getting socket: %s", strerror(errno));
890                 return -1;
891         }
892
893         /* set receive buffersize */
894         setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
895
896         retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
897         if (retval < 0) {
898                 err("bind failed: %s", strerror(errno));
899                 close(uevent_netlink_sock);
900                 uevent_netlink_sock = -1;
901                 return -1;
902         }
903         return 0;
904 }
905
906 static void export_initial_seqnum(void)
907 {
908         char filename[PATH_SIZE];
909         int fd;
910         char seqnum[32];
911         ssize_t len = 0;
912
913         strlcpy(filename, sysfs_path, sizeof(filename));
914         strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
915         fd = open(filename, O_RDONLY);
916         if (fd >= 0) {
917                 len = read(fd, seqnum, sizeof(seqnum)-1);
918                 close(fd);
919         }
920         if (len <= 0) {
921                 strcpy(seqnum, "0\n");
922                 len = 3;
923         }
924         strlcpy(filename, udev_root, sizeof(filename));
925         strlcat(filename, "/" EVENT_SEQNUM, sizeof(filename));
926         create_path(filename);
927         fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
928         if (fd >= 0) {
929                 write(fd, seqnum, len);
930                 close(fd);
931         }
932 }
933
934 int main(int argc, char *argv[], char *envp[])
935 {
936         int retval;
937         int fd;
938         struct sigaction act;
939         fd_set readfds;
940         const char *value;
941         int daemonize = 0;
942         int option;
943         static const struct option options[] = {
944                 { "daemon", 0, NULL, 'd' },
945                 { "debug-trace", 0, NULL, 't' },
946                 { "verbose", 0, NULL, 'v' },
947                 { "help", 0, NULL, 'h' },
948                 { "version", 0, NULL, 'V' },
949                 {}
950         };
951         int rc = 1;
952         int maxfd;
953
954         logging_init("udevd");
955         udev_config_init();
956         selinux_init();
957         dbg("version %s", UDEV_VERSION);
958
959         /* parse commandline options */
960         while (1) {
961                 option = getopt_long(argc, argv, "dtvhV", options, NULL);
962                 if (option == -1)
963                         break;
964
965                 switch (option) {
966                 case 'd':
967                         daemonize = 1;
968                         break;
969                 case 't':
970                         debug_trace = 1;
971                         break;
972                 case 'v':
973                         verbose = 1;
974                         if (udev_log_priority < LOG_INFO)
975                                 udev_log_priority = LOG_INFO;
976                         break;
977                 case 'h':
978                         printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--verbose] [--version]\n");
979                         goto exit;
980                 case 'V':
981                         printf("%s\n", UDEV_VERSION);
982                         goto exit;
983                 default:
984                         goto exit;
985                 }
986         }
987
988         if (getuid() != 0) {
989                 fprintf(stderr, "root privileges required\n");
990                 err("root privileges required");
991                 goto exit;
992         }
993
994         /* make sure std{in,out,err} fd's are in a sane state */
995         fd = open("/dev/null", O_RDWR);
996         if (fd < 0) {
997                 fprintf(stderr, "cannot open /dev/null\n");
998                 err("cannot open /dev/null");
999         }
1000         if (fd > STDIN_FILENO)
1001                 dup2(fd, STDIN_FILENO);
1002         if (write(STDOUT_FILENO, 0, 0) < 0)
1003                 dup2(fd, STDOUT_FILENO);
1004         if (write(STDERR_FILENO, 0, 0) < 0)
1005                 dup2(fd, STDERR_FILENO);
1006
1007         /* init sockets to receive events */
1008         if (init_udevd_socket() < 0) {
1009                 if (errno == EADDRINUSE) {
1010                         fprintf(stderr, "another udev daemon already running\n");
1011                         err("another udev daemon already running");
1012                         rc = 1;
1013                 } else {
1014                         fprintf(stderr, "error initializing udevd socket\n");
1015                         err("error initializing udevd socket");
1016                         rc = 2;
1017                 }
1018                 goto exit;
1019         }
1020
1021         if (init_uevent_netlink_sock() < 0) {
1022                 fprintf(stderr, "error initializing netlink socket\n");
1023                 err("error initializing netlink socket");
1024                 rc = 3;
1025                 goto exit;
1026         }
1027
1028         /* setup signal handler pipe */
1029         retval = pipe(signal_pipe);
1030         if (retval < 0) {
1031                 err("error getting pipes: %s", strerror(errno));
1032                 goto exit;
1033         }
1034
1035         retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
1036         if (retval < 0) {
1037                 err("error fcntl on read pipe: %s", strerror(errno));
1038                 goto exit;
1039         }
1040         retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
1041         if (retval < 0) {
1042                 err("error fcntl on read pipe: %s", strerror(errno));
1043                 goto exit;
1044         }
1045
1046         retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
1047         if (retval < 0) {
1048                 err("error fcntl on write pipe: %s", strerror(errno));
1049                 goto exit;
1050         }
1051         retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
1052         if (retval < 0) {
1053                 err("error fcntl on write pipe: %s", strerror(errno));
1054                 goto exit;
1055         }
1056
1057         /* parse the rules and keep them in memory */
1058         sysfs_init();
1059         udev_rules_init(&rules, 1);
1060
1061         export_initial_seqnum();
1062
1063         if (daemonize) {
1064                 pid_t pid;
1065
1066                 pid = fork();
1067                 switch (pid) {
1068                 case 0:
1069                         dbg("daemonized fork running");
1070                         break;
1071                 case -1:
1072                         err("fork of daemon failed: %s", strerror(errno));
1073                         rc = 4;
1074                         goto exit;
1075                 default:
1076                         dbg("child [%u] running, parent exits", pid);
1077                         rc = 0;
1078                         goto exit;
1079                 }
1080         }
1081
1082         /* redirect std{out,err} fd's */
1083         if (!verbose)
1084                 dup2(fd, STDOUT_FILENO);
1085         dup2(fd, STDERR_FILENO);
1086         if (fd > STDERR_FILENO)
1087                 close(fd);
1088
1089         /* set scheduling priority for the daemon */
1090         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1091
1092         chdir("/");
1093         umask(022);
1094
1095         /* become session leader */
1096         sid = setsid();
1097         dbg("our session is %d", sid);
1098
1099         /* OOM_DISABLE == -17 */
1100         fd = open("/proc/self/oom_adj", O_RDWR);
1101         if (fd < 0)
1102                 err("error disabling OOM: %s", strerror(errno));
1103         else {
1104                 write(fd, "-17", 3);
1105                 close(fd);
1106         }
1107
1108         /* set signal handlers */
1109         memset(&act, 0x00, sizeof(struct sigaction));
1110         act.sa_handler = (void (*)(int)) sig_handler;
1111         sigemptyset(&act.sa_mask);
1112         act.sa_flags = SA_RESTART;
1113         sigaction(SIGINT, &act, NULL);
1114         sigaction(SIGTERM, &act, NULL);
1115         sigaction(SIGCHLD, &act, NULL);
1116         sigaction(SIGHUP, &act, NULL);
1117
1118         /* watch rules directory */
1119         inotify_fd = inotify_init();
1120         if (inotify_fd >= 0)
1121                 inotify_add_watch(inotify_fd, udev_rules_dir, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1122         else if (errno == ENOSYS)
1123                 err("the kernel does not support inotify, udevd can't monitor configuration file changes");
1124         else
1125                 err("inotify_init failed: %s", strerror(errno));
1126
1127         /* maximum limit of forked childs */
1128         value = getenv("UDEVD_MAX_CHILDS");
1129         if (value)
1130                 max_childs = strtoul(value, NULL, 10);
1131         else {
1132                 int memsize = mem_size_mb();
1133                 if (memsize > 0)
1134                         max_childs = 128 + (memsize / 4);
1135                 else
1136                         max_childs = UDEVD_MAX_CHILDS;
1137         }
1138         info("initialize max_childs to %u", max_childs);
1139
1140         /* start to throttle forking if maximum number of _running_ childs is reached */
1141         value = getenv("UDEVD_MAX_CHILDS_RUNNING");
1142         if (value)
1143                 max_childs_running = strtoull(value, NULL, 10);
1144         else {
1145                 int cpus = cpu_count();
1146                 if (cpus > 0)
1147                         max_childs_running = 8 + (8 * cpus);
1148                 else
1149                         max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
1150         }
1151         info("initialize max_childs_running to %u", max_childs_running);
1152
1153         /* clear environment for forked event processes */
1154         clearenv();
1155
1156         /* export log_priority , as called programs may want to follow that setting */
1157         sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
1158         putenv(udev_log);
1159         if (debug_trace)
1160                 putenv("DEBUG=1");
1161
1162         maxfd = udevd_sock;
1163         maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
1164         maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
1165         maxfd = UDEV_MAX(maxfd, inotify_fd);
1166
1167         while (!udev_exit) {
1168                 struct udevd_uevent_msg *msg;
1169                 int fdcount;
1170
1171                 FD_ZERO(&readfds);
1172                 FD_SET(signal_pipe[READ_END], &readfds);
1173                 FD_SET(udevd_sock, &readfds);
1174                 FD_SET(uevent_netlink_sock, &readfds);
1175                 if (inotify_fd >= 0)
1176                         FD_SET(inotify_fd, &readfds);
1177
1178                 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1179                 if (fdcount < 0) {
1180                         if (errno != EINTR)
1181                                 err("error in select: %s", strerror(errno));
1182                         continue;
1183                 }
1184
1185                 /* get control message */
1186                 if (FD_ISSET(udevd_sock, &readfds))
1187                         get_ctrl_msg();
1188
1189                 /* get netlink message */
1190                 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1191                         msg = get_netlink_msg();
1192                         if (msg)
1193                                 msg_queue_insert(msg);
1194                 }
1195
1196                 /* received a signal, clear our notification pipe */
1197                 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1198                         char buf[256];
1199
1200                         read(signal_pipe[READ_END], &buf, sizeof(buf));
1201                 }
1202
1203                 /* rules directory inotify watch */
1204                 if ((inotify_fd >= 0) && FD_ISSET(inotify_fd, &readfds)) {
1205                         int nbytes;
1206
1207                         /* discard all possible events, we can just reload the config */
1208                         if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1209                                 char *buf;
1210
1211                                 reload_config = 1;
1212                                 buf = malloc(nbytes);
1213                                 if (!buf) {
1214                                         err("error getting buffer for inotify, disable watching");
1215                                         close(inotify_fd);
1216                                         inotify_fd = -1;
1217                                 }
1218                                 read(inotify_fd, buf, nbytes);
1219                                 free(buf);
1220                         }
1221                 }
1222
1223                 /* rules changed, set by inotify or a HUP signal */
1224                 if (reload_config) {
1225                         reload_config = 0;
1226                         udev_rules_cleanup(&rules);
1227                         udev_rules_init(&rules, 1);
1228                 }
1229
1230                 /* forked child has returned */
1231                 if (sigchilds_waiting) {
1232                         sigchilds_waiting = 0;
1233                         reap_sigchilds();
1234                 }
1235
1236                 if (run_exec_q) {
1237                         run_exec_q = 0;
1238                         if (!stop_exec_q)
1239                                 msg_queue_manager();
1240                 }
1241         }
1242         rc = 0;
1243
1244 exit:
1245         udev_rules_cleanup(&rules);
1246         sysfs_cleanup();
1247         selinux_exit();
1248
1249         if (signal_pipe[READ_END] >= 0)
1250                 close(signal_pipe[READ_END]);
1251         if (signal_pipe[WRITE_END] >= 0)
1252                 close(signal_pipe[WRITE_END]);
1253
1254         if (udevd_sock >= 0)
1255                 close(udevd_sock);
1256         if (inotify_fd >= 0)
1257                 close(inotify_fd);
1258         if (uevent_netlink_sock >= 0)
1259                 close(uevent_netlink_sock);
1260
1261         logging_close();
1262
1263         return rc;
1264 }