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