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