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