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