chiark / gitweb /
rules: fix md "change"/"remove" handling
[elogind.git] / udev / udevd.c
1 /*
2  * Copyright (C) 2004-2008 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
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include <stddef.h>
20 #include <signal.h>
21 #include <unistd.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <fcntl.h>
28 #include <time.h>
29 #include <getopt.h>
30 #include <dirent.h>
31 #include <sys/select.h>
32 #include <sys/poll.h>
33 #include <sys/wait.h>
34 #include <sys/stat.h>
35 #include <sys/ioctl.h>
36 #ifdef HAVE_INOTIFY
37 #include <sys/inotify.h>
38 #endif
39
40 #include "udev.h"
41
42 #define UDEVD_PRIORITY                  -4
43 #define UDEV_PRIORITY                   -2
44
45 /* maximum limit of forked childs */
46 #define UDEVD_MAX_CHILDS                256
47
48 static int debug;
49
50 static void log_fn(struct udev *udev, int priority,
51                    const char *file, int line, const char *fn,
52                    const char *format, va_list args)
53 {
54         if (debug) {
55                 fprintf(stderr, "[%d] %s: ", (int) getpid(), fn);
56                 vfprintf(stderr, format, args);
57         } else {
58                 vsyslog(priority, format, args);
59         }
60 }
61
62 static void reap_sigchilds(void);
63
64 static int debug_trace;
65 static struct udev_rules *rules;
66 static struct udev_ctrl *udev_ctrl;
67 static struct udev_monitor *kernel_monitor;
68 static int inotify_fd = -1;
69 static volatile int sigchilds_waiting;
70 static volatile int udev_exit;
71 static volatile int reload_config;
72 static volatile int signal_received;
73 static int run_exec_q;
74 static int stop_exec_q;
75 static int max_childs;
76 static int childs;
77 static struct udev_list_node event_list;
78
79 enum event_state {
80         EVENT_QUEUED,
81         EVENT_FINISHED,
82         EVENT_FAILED,
83 };
84
85 static struct udev_event *node_to_event(struct udev_list_node *node)
86 {
87         char *event;
88
89         event = (char *)node;
90         event -= offsetof(struct udev_event, node);
91         return (struct udev_event *)event;
92 }
93
94 static void export_event_state(struct udev_event *event, enum event_state state)
95 {
96         char filename[UTIL_PATH_SIZE];
97         char filename_failed[UTIL_PATH_SIZE];
98         size_t start;
99
100         /* location of queue file */
101         snprintf(filename, sizeof(filename), "%s/.udev/queue/%llu",
102                  udev_get_dev_path(event->udev), udev_device_get_seqnum(event->dev));
103
104         /* location of failed file */
105         util_strlcpy(filename_failed, udev_get_dev_path(event->udev), sizeof(filename_failed));
106         util_strlcat(filename_failed, "/", sizeof(filename_failed));
107         start = util_strlcat(filename_failed, ".udev/failed/", sizeof(filename_failed));
108         util_strlcat(filename_failed, udev_device_get_devpath(event->dev), sizeof(filename_failed));
109         util_path_encode(&filename_failed[start], sizeof(filename_failed) - start);
110
111         switch (state) {
112         case EVENT_QUEUED:
113                 if(unlink(filename_failed) == 0)
114                         util_delete_path(event->udev, filename_failed);
115                 util_create_path(event->udev, filename);
116                 udev_selinux_setfscreatecon(event->udev, filename, S_IFLNK);
117                 symlink(udev_device_get_devpath(event->dev), filename);
118                 udev_selinux_resetfscreatecon(event->udev);
119                 break;
120         case EVENT_FINISHED:
121                 if (udev_device_get_devpath_old(event->dev) != NULL) {
122                         /* "move" event - rename failed file to current name, do not delete failed */
123                         char filename_failed_old[UTIL_PATH_SIZE];
124
125                         util_strlcpy(filename_failed_old, udev_get_dev_path(event->udev), sizeof(filename_failed_old));
126                         util_strlcat(filename_failed_old, "/", sizeof(filename_failed_old));
127                         start = util_strlcat(filename_failed_old, ".udev/failed/", sizeof(filename_failed_old));
128                         util_strlcat(filename_failed_old, udev_device_get_devpath_old(event->dev), sizeof(filename_failed_old));
129                         util_path_encode(&filename_failed_old[start], sizeof(filename) - start);
130
131                         if (rename(filename_failed_old, filename_failed) == 0)
132                                 info(event->udev, "renamed devpath, moved failed state of '%s' to %s'\n",
133                                      udev_device_get_devpath_old(event->dev), udev_device_get_devpath(event->dev));
134                 } else {
135                         if (unlink(filename_failed) == 0)
136                                 util_delete_path(event->udev, filename_failed);
137                 }
138
139                 unlink(filename);
140
141                 /* clean up possibly empty queue directory */
142                 if (udev_list_is_empty(&event_list))
143                         util_delete_path(event->udev, filename);
144                 break;
145         case EVENT_FAILED:
146                 /* move failed event to the failed directory */
147                 util_create_path(event->udev, filename_failed);
148                 rename(filename, filename_failed);
149
150                 /* clean up possibly empty queue directory */
151                 if (udev_list_is_empty(&event_list))
152                         util_delete_path(event->udev, filename);
153                 break;
154         }
155
156         return;
157 }
158
159 static void event_queue_delete(struct udev_event *event)
160 {
161         udev_list_node_remove(&event->node);
162
163         /* mark as failed, if "add" event returns non-zero */
164         if (event->exitstatus && strcmp(udev_device_get_action(event->dev), "add") == 0)
165                 export_event_state(event, EVENT_FAILED);
166         else
167                 export_event_state(event, EVENT_FINISHED);
168
169         udev_device_unref(event->dev);
170         udev_event_unref(event);
171 }
172
173 static void asmlinkage event_sig_handler(int signum)
174 {
175         if (signum == SIGALRM)
176                 exit(1);
177 }
178
179 static void event_fork(struct udev_event *event)
180 {
181         pid_t pid;
182         struct sigaction act;
183         int err;
184
185         if (debug_trace) {
186                 event->trace = 1;
187                 fprintf(stderr, "fork %s (%llu)\n",
188                        udev_device_get_syspath(event->dev),
189                        udev_device_get_seqnum(event->dev));
190         }
191
192         pid = fork();
193         switch (pid) {
194         case 0:
195                 /* child */
196                 udev_monitor_unref(kernel_monitor);
197                 udev_ctrl_unref(udev_ctrl);
198                 if (inotify_fd >= 0)
199                         close(inotify_fd);
200                 logging_close();
201                 logging_init("udevd-event");
202                 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
203
204                 /* set signal handlers */
205                 memset(&act, 0x00, sizeof(act));
206                 act.sa_handler = (void (*)(int)) event_sig_handler;
207                 sigemptyset (&act.sa_mask);
208                 act.sa_flags = 0;
209                 sigaction(SIGALRM, &act, NULL);
210
211                 /* reset to default */
212                 act.sa_handler = SIG_DFL;
213                 sigaction(SIGINT, &act, NULL);
214                 sigaction(SIGTERM, &act, NULL);
215                 sigaction(SIGCHLD, &act, NULL);
216                 sigaction(SIGHUP, &act, NULL);
217
218                 /* set timeout to prevent hanging processes */
219                 alarm(UDEV_EVENT_TIMEOUT);
220
221                 /* apply rules, create node, symlinks */
222                 err = udev_event_execute_rules(event, rules);
223
224                 /* rules may change/disable the timeout */
225                 if (udev_device_get_event_timeout(event->dev) >= 0)
226                         alarm(udev_device_get_event_timeout(event->dev));
227
228                 /* execute RUN= */
229                 if (err == 0 && !event->ignore_device && udev_get_run(event->udev))
230                         udev_event_execute_run(event);
231
232                 info(event->udev, "seq %llu exit with %i\n", udev_device_get_seqnum(event->dev), err);
233                 logging_close();
234                 if (err != 0)
235                         exit(1);
236                 exit(0);
237         case -1:
238                 err(event->udev, "fork of child failed: %m\n");
239                 event_queue_delete(event);
240                 break;
241         default:
242                 /* get SIGCHLD in main loop */
243                 info(event->udev, "seq %llu forked, pid [%d], '%s' '%s', %ld seconds old\n",
244                      udev_device_get_seqnum(event->dev),
245                      pid,
246                      udev_device_get_action(event->dev),
247                      udev_device_get_subsystem(event->dev),
248                      time(NULL) - event->queue_time);
249                 event->pid = pid;
250                 childs++;
251         }
252 }
253
254 static void event_queue_insert(struct udev_event *event)
255 {
256         char filename[UTIL_PATH_SIZE];
257         int fd;
258
259         event->queue_time = time(NULL);
260
261         export_event_state(event, EVENT_QUEUED);
262         info(event->udev, "seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(event->dev),
263              udev_device_get_action(event->dev), udev_device_get_subsystem(event->dev));
264
265         util_strlcpy(filename, udev_get_dev_path(event->udev), sizeof(filename));
266         util_strlcat(filename, "/.udev/uevent_seqnum", sizeof(filename));
267         fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
268         if (fd >= 0) {
269                 char str[32];
270                 int len;
271
272                 len = sprintf(str, "%llu\n", udev_device_get_seqnum(event->dev));
273                 write(fd, str, len);
274                 close(fd);
275         }
276
277
278         udev_list_node_append(&event->node, &event_list);
279         run_exec_q = 1;
280
281         /* run all events with a timeout set immediately */
282         if (udev_device_get_timeout(event->dev) > 0) {
283                 event_fork(event);
284                 return;
285         }
286 }
287
288 static int mem_size_mb(void)
289 {
290         FILE* f;
291         char buf[4096];
292         long int memsize = -1;
293
294         f = fopen("/proc/meminfo", "r");
295         if (f == NULL)
296                 return -1;
297
298         while (fgets(buf, sizeof(buf), f) != NULL) {
299                 long int value;
300
301                 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
302                         memsize = value / 1024;
303                         break;
304                 }
305         }
306
307         fclose(f);
308         return memsize;
309 }
310
311 static int compare_devpath(const char *running, const char *waiting)
312 {
313         int i = 0;
314
315         while (running[i] != '\0' && running[i] == waiting[i])
316                 i++;
317
318         /* identical device event found */
319         if (running[i] == '\0' && waiting[i] == '\0')
320                 return 1;
321
322         /* parent device event found */
323         if (running[i] == '\0' && waiting[i] == '/')
324                 return 2;
325
326         /* child device event found */
327         if (running[i] == '/' && waiting[i] == '\0')
328                 return 3;
329
330         /* no matching event */
331         return 0;
332 }
333
334 /* lookup event for identical, parent, child, or physical device */
335 static int devpath_busy(struct udev_event *event)
336 {
337         struct udev_list_node *loop;
338
339         if (event->delaying_seqnum > 0) {
340         }
341         /* check if queue contains events we depend on */
342         udev_list_node_foreach(loop, &event_list) {
343                 struct udev_event *loop_event = node_to_event(loop);
344
345                 /* we already found a later event, earlier can not block us, no need to check again */
346                 if (udev_device_get_seqnum(loop_event->dev) < event->delaying_seqnum)
347                         continue;
348
349                 /* event we checked earlier still exists, no need to check again */
350                 if (udev_device_get_seqnum(loop_event->dev) == event->delaying_seqnum)
351                         return 2;
352
353                 /* found ourself, no later event can block us */
354                 if (udev_device_get_seqnum(loop_event->dev) >= udev_device_get_seqnum(event->dev))
355                         break;
356
357                 /* check our old name */
358                 if (udev_device_get_devpath_old(event->dev) != NULL)
359                         if (strcmp(udev_device_get_devpath(loop_event->dev), udev_device_get_devpath_old(event->dev)) == 0) {
360                                 event->delaying_seqnum = udev_device_get_seqnum(loop_event->dev);
361                                 return 3;
362                         }
363
364                 /* check identical, parent, or child device event */
365                 if (compare_devpath(udev_device_get_devpath(loop_event->dev), udev_device_get_devpath(event->dev)) != 0) {
366                         dbg(event->udev, "%llu, device event still pending %llu (%s)\n",
367                             udev_device_get_seqnum(event->dev),
368                             udev_device_get_seqnum(loop_event->dev),
369                             udev_device_get_devpath(loop_event->dev));
370                         event->delaying_seqnum = udev_device_get_seqnum(loop_event->dev);
371                         return 4;
372                 }
373
374                 /* check for our major:minor number */
375                 if (major(udev_device_get_devnum(event->dev)) > 0 &&
376                     udev_device_get_devnum(loop_event->dev) == udev_device_get_devnum(event->dev) &&
377                     strcmp(udev_device_get_subsystem(event->dev), udev_device_get_subsystem(loop_event->dev)) == 0) {
378                         dbg(event->udev, "%llu, device event still pending %llu (%d:%d)\n",
379                             udev_device_get_seqnum(event->dev),
380                             udev_device_get_seqnum(loop_event->dev),
381                             major(udev_device_get_devnum(loop_event->dev)), minor(udev_device_get_devnum(loop_event->dev)));
382                         event->delaying_seqnum = udev_device_get_seqnum(loop_event->dev);
383                         return 5;
384                 }
385
386                 /* check physical device event (special case of parent) */
387                 if (udev_device_get_physdevpath(event->dev) != NULL &&
388                     strcmp(udev_device_get_action(event->dev), "add") == 0)
389                         if (compare_devpath(udev_device_get_devpath(loop_event->dev),
390                                             udev_device_get_physdevpath(event->dev)) != 0) {
391                                 dbg(event->udev, "%llu, physical device event still pending %llu (%s)\n",
392                                     udev_device_get_seqnum(event->dev),
393                                     udev_device_get_seqnum(loop_event->dev),
394                                     udev_device_get_devpath(loop_event->dev));
395                                 event->delaying_seqnum = udev_device_get_seqnum(loop_event->dev);
396                                 return 6;
397                         }
398         }
399         return 0;
400 }
401
402 /* serializes events for the identical and parent and child devices */
403 static void event_queue_manager(struct udev *udev)
404 {
405         struct udev_list_node *loop;
406         struct udev_list_node *tmp;
407
408 start_over:
409         if (udev_list_is_empty(&event_list)) {
410                 if (childs > 0) {
411                         err(udev, "event list empty, but childs count is %i", childs);
412                         childs = 0;
413                 }
414                 return;
415         }
416
417         udev_list_node_foreach_safe(loop, tmp, &event_list) {
418                 struct udev_event *loop_event = node_to_event(loop);
419
420                 if (childs >= max_childs) {
421                         info(udev, "maximum number (%i) of childs reached\n", childs);
422                         break;
423                 }
424
425                 if (loop_event->pid != 0)
426                         continue;
427
428                 /* do not start event if parent or child event is still running */
429                 if (devpath_busy(loop_event) != 0) {
430                         dbg(udev, "delay seq %llu (%s)\n",
431                             udev_device_get_seqnum(loop_event->dev),
432                             udev_device_get_devpath(loop_event->dev));
433                         continue;
434                 }
435
436                 event_fork(loop_event);
437                 dbg(udev, "moved seq %llu to running list\n", udev_device_get_seqnum(loop_event->dev));
438
439                 /* retry if events finished in the meantime */
440                 if (sigchilds_waiting) {
441                         sigchilds_waiting = 0;
442                         reap_sigchilds();
443                         goto start_over;
444                 }
445         }
446 }
447
448 /* receive the udevd message from userspace */
449 static void handle_ctrl_msg(struct udev_ctrl *uctrl)
450 {
451         struct udev *udev = udev_ctrl_get_udev(uctrl);
452         struct udev_ctrl_msg *ctrl_msg;
453         const char *str;
454         int i;
455
456         ctrl_msg = udev_ctrl_receive_msg(uctrl);
457         if (ctrl_msg == NULL)
458                 return;
459
460         i = udev_ctrl_get_set_log_level(ctrl_msg);
461         if (i >= 0) {
462                 info(udev, "udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
463                 udev_set_log_priority(udev, i);
464         }
465
466         if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
467                 info(udev, "udevd message (STOP_EXEC_QUEUE) received\n");
468                 stop_exec_q = 1;
469         }
470
471         if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
472                 info(udev, "udevd message (START_EXEC_QUEUE) received\n");
473                 stop_exec_q = 0;
474                 event_queue_manager(udev);
475         }
476
477         if (udev_ctrl_get_reload_rules(ctrl_msg) > 0) {
478                 info(udev, "udevd message (RELOAD_RULES) received\n");
479                 reload_config = 1;
480         }
481
482         str = udev_ctrl_get_set_env(ctrl_msg);
483         if (str != NULL) {
484                 char *key;
485
486                 key = strdup(str);
487                 if (key != NULL) {
488                         char *val;
489
490                         val = strchr(key, '=');
491                         if (val != NULL) {
492                                 val[0] = '\0';
493                                 val = &val[1];
494                                 if (val[0] == '\0') {
495                                         info(udev, "udevd message (ENV) received, unset '%s'\n", key);
496                                         udev_add_property(udev, key, NULL);
497                                 } else {
498                                         info(udev, "udevd message (ENV) received, set '%s=%s'\n", key, val);
499                                         udev_add_property(udev, key, val);
500                                 }
501                         } else {
502                                 err(udev, "wrong key format '%s'\n", key);
503                         }
504                         free(key);
505                 }
506         }
507
508         i = udev_ctrl_get_set_max_childs(ctrl_msg);
509         if (i >= 0) {
510                 info(udev, "udevd message (SET_MAX_CHILDS) received, max_childs=%i\n", i);
511                 max_childs = i;
512         }
513         udev_ctrl_msg_unref(ctrl_msg);
514 }
515
516 static void asmlinkage sig_handler(int signum)
517 {
518         switch (signum) {
519                 case SIGINT:
520                 case SIGTERM:
521                         udev_exit = 1;
522                         break;
523                 case SIGCHLD:
524                         /* set flag, then write to pipe if needed */
525                         sigchilds_waiting = 1;
526                         break;
527                 case SIGHUP:
528                         reload_config = 1;
529                         break;
530         }
531
532         signal_received = 1;
533 }
534
535 static void udev_done(int pid, int exitstatus)
536 {
537         struct udev_list_node *loop;
538
539         /* find event associated with pid and delete it */
540         udev_list_node_foreach(loop, &event_list) {
541                 struct udev_event *loop_event = node_to_event(loop);
542
543                 if (loop_event->pid == pid) {
544                         info(loop_event->udev, "seq %llu cleanup, pid [%d], status %i, %ld seconds old\n",
545                              udev_device_get_seqnum(loop_event->dev), loop_event->pid,
546                              exitstatus, time(NULL) - loop_event->queue_time);
547                         loop_event->exitstatus = exitstatus;
548                         if (debug_trace)
549                                 fprintf(stderr, "exit %s (%llu)\n",
550                                        udev_device_get_syspath(loop_event->dev),
551                                        udev_device_get_seqnum(loop_event->dev));
552                         event_queue_delete(loop_event);
553                         childs--;
554
555                         /* there may be dependent events waiting */
556                         run_exec_q = 1;
557                         return;
558                 }
559         }
560 }
561
562 static void reap_sigchilds(void)
563 {
564         pid_t pid;
565         int status;
566
567         while (1) {
568                 pid = waitpid(-1, &status, WNOHANG);
569                 if (pid <= 0)
570                         break;
571                 if (WIFEXITED(status))
572                         status = WEXITSTATUS(status);
573                 else if (WIFSIGNALED(status))
574                         status = WTERMSIG(status) + 128;
575                 else
576                         status = 0;
577                 udev_done(pid, status);
578         }
579 }
580
581 static void cleanup_queue_dir(struct udev *udev)
582 {
583         char dirname[UTIL_PATH_SIZE];
584         char filename[UTIL_PATH_SIZE];
585         DIR *dir;
586
587         util_strlcpy(filename, udev_get_dev_path(udev), sizeof(filename));
588         util_strlcat(filename, "/.udev/uevent_seqnum", sizeof(filename));
589         unlink(filename);
590
591         util_strlcpy(dirname, udev_get_dev_path(udev), sizeof(dirname));
592         util_strlcat(dirname, "/.udev/queue", sizeof(dirname));
593         dir = opendir(dirname);
594         if (dir != NULL) {
595                 while (1) {
596                         struct dirent *dent;
597
598                         dent = readdir(dir);
599                         if (dent == NULL || dent->d_name[0] == '\0')
600                                 break;
601                         if (dent->d_name[0] == '.')
602                                 continue;
603                         util_strlcpy(filename, dirname, sizeof(filename));
604                         util_strlcat(filename, "/", sizeof(filename));
605                         util_strlcat(filename, dent->d_name, sizeof(filename));
606                         unlink(filename);
607                 }
608                 closedir(dir);
609                 rmdir(dirname);
610         }
611 }
612
613 static void export_initial_seqnum(struct udev *udev)
614 {
615         char filename[UTIL_PATH_SIZE];
616         int fd;
617         char seqnum[32];
618         ssize_t len = 0;
619
620         util_strlcpy(filename, udev_get_sys_path(udev), sizeof(filename));
621         util_strlcat(filename, "/kernel/uevent_seqnum", sizeof(filename));
622         fd = open(filename, O_RDONLY);
623         if (fd >= 0) {
624                 len = read(fd, seqnum, sizeof(seqnum)-1);
625                 close(fd);
626         }
627         if (len <= 0) {
628                 strcpy(seqnum, "0\n");
629                 len = 3;
630         }
631         util_strlcpy(filename, udev_get_dev_path(udev), sizeof(filename));
632         util_strlcat(filename, "/.udev/uevent_seqnum", sizeof(filename));
633         util_create_path(udev, filename);
634         fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0644);
635         if (fd >= 0) {
636                 write(fd, seqnum, len);
637                 close(fd);
638         }
639 }
640
641 int main(int argc, char *argv[])
642 {
643         struct udev *udev;
644         int fd;
645         struct sigaction act;
646         const char *value;
647         int daemonize = 0;
648         int resolve_names = 1;
649         static const struct option options[] = {
650                 { "daemon", no_argument, NULL, 'd' },
651                 { "debug-trace", no_argument, NULL, 't' },
652                 { "debug", no_argument, NULL, 'D' },
653                 { "help", no_argument, NULL, 'h' },
654                 { "version", no_argument, NULL, 'V' },
655                 { "resolve-names", required_argument, NULL, 'N' },
656                 {}
657         };
658         int rc = 1;
659
660         udev = udev_new();
661         if (udev == NULL)
662                 goto exit;
663
664         logging_init("udevd");
665         udev_set_log_fn(udev, log_fn);
666         info(udev, "version %s\n", VERSION);
667         udev_selinux_init(udev);
668
669         while (1) {
670                 int option;
671
672                 option = getopt_long(argc, argv, "dDthV", options, NULL);
673                 if (option == -1)
674                         break;
675
676                 switch (option) {
677                 case 'd':
678                         daemonize = 1;
679                         break;
680                 case 't':
681                         debug_trace = 1;
682                         break;
683                 case 'D':
684                         debug = 1;
685                         if (udev_get_log_priority(udev) < LOG_INFO)
686                                 udev_set_log_priority(udev, LOG_INFO);
687                         break;
688                 case 'N':
689                         if (strcmp (optarg, "early") == 0) {
690                                 resolve_names = 1;
691                         } else if (strcmp (optarg, "late") == 0) {
692                                 resolve_names = 0;
693                         } else if (strcmp (optarg, "never") == 0) {
694                                 resolve_names = -1;
695                         } else {
696                                 fprintf(stderr, "resolve-names must be early, late or never\n");
697                                 err(udev, "resolve-names must be early, late or never\n");
698                                 goto exit;
699                         }
700                         break;
701                 case 'h':
702                         printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--debug] "
703                                "[--resolve-names=early|late|never] [--version]\n");
704                         goto exit;
705                 case 'V':
706                         printf("%s\n", VERSION);
707                         goto exit;
708                 default:
709                         goto exit;
710                 }
711         }
712
713         if (getuid() != 0) {
714                 fprintf(stderr, "root privileges required\n");
715                 err(udev, "root privileges required\n");
716                 goto exit;
717         }
718
719         /* make sure std{in,out,err} fd's are in a sane state */
720         fd = open("/dev/null", O_RDWR);
721         if (fd < 0) {
722                 fprintf(stderr, "cannot open /dev/null\n");
723                 err(udev, "cannot open /dev/null\n");
724         }
725         if (write(STDOUT_FILENO, 0, 0) < 0)
726                 dup2(fd, STDOUT_FILENO);
727         if (write(STDERR_FILENO, 0, 0) < 0)
728                 dup2(fd, STDERR_FILENO);
729
730         /* init control socket, bind() ensures, that only one udevd instance is running */
731         udev_ctrl = udev_ctrl_new_from_socket(udev, UDEV_CTRL_SOCK_PATH);
732         if (udev_ctrl == NULL) {
733                 fprintf(stderr, "error initializing control socket");
734                 err(udev, "error initializing udevd socket");
735                 rc = 1;
736                 goto exit;
737         }
738
739         if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
740                 fprintf(stderr, "error binding control socket, seems udevd is already running\n");
741                 err(udev, "error binding control socket, seems udevd is already running\n");
742                 rc = 1;
743                 goto exit;
744         }
745
746         kernel_monitor = udev_monitor_new_from_netlink(udev);
747         if (kernel_monitor == NULL || udev_monitor_enable_receiving(kernel_monitor) < 0) {
748                 fprintf(stderr, "error initializing netlink socket\n");
749                 err(udev, "error initializing netlink socket\n");
750                 rc = 3;
751                 goto exit;
752         }
753         udev_monitor_set_receive_buffer_size(kernel_monitor, 128*1024*1024);
754
755         rules = udev_rules_new(udev, resolve_names);
756         if (rules == NULL) {
757                 err(udev, "error reading rules\n");
758                 goto exit;
759         }
760         udev_list_init(&event_list);
761         cleanup_queue_dir(udev);
762         export_initial_seqnum(udev);
763
764         if (daemonize) {
765                 pid_t pid;
766
767                 pid = fork();
768                 switch (pid) {
769                 case 0:
770                         dbg(udev, "daemonized fork running\n");
771                         break;
772                 case -1:
773                         err(udev, "fork of daemon failed: %m\n");
774                         rc = 4;
775                         goto exit;
776                 default:
777                         dbg(udev, "child [%u] running, parent exits\n", pid);
778                         rc = 0;
779                         goto exit;
780                 }
781         }
782
783         /* redirect std{out,err} */
784         if (!debug && !debug_trace) {
785                 dup2(fd, STDIN_FILENO);
786                 dup2(fd, STDOUT_FILENO);
787                 dup2(fd, STDERR_FILENO);
788         }
789         if (fd > STDERR_FILENO)
790                 close(fd);
791
792         /* set scheduling priority for the daemon */
793         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
794
795         chdir("/");
796         umask(022);
797         setsid();
798
799         /* OOM_DISABLE == -17 */
800         fd = open("/proc/self/oom_adj", O_RDWR);
801         if (fd < 0)
802                 err(udev, "error disabling OOM: %m\n");
803         else {
804                 write(fd, "-17", 3);
805                 close(fd);
806         }
807
808         fd = open("/dev/kmsg", O_WRONLY);
809         if (fd > 0) {
810                 const char *ver_str = "<6>udev: starting version " VERSION "\n";
811                 char path[UTIL_PATH_SIZE];
812                 struct stat statbuf;
813
814                 write(fd, ver_str, strlen(ver_str));
815                 util_strlcpy(path, udev_get_sys_path(udev), sizeof(path));
816                 util_strlcat(path, "/class/mem/null", sizeof(path));
817                 if (lstat(path, &statbuf) == 0) {
818                         if (S_ISDIR(statbuf.st_mode)) {
819                                 const char *depr_str =
820                                         "<6>udev: deprecated sysfs layout; update the kernel or "
821                                         "disable CONFIG_SYSFS_DEPRECATED; some udev features will "
822                                         "not work correctly\n";
823
824                                 write(fd, depr_str, strlen(depr_str));
825                         }
826                 }
827                 close(fd);
828         }
829
830         /* set signal handlers */
831         memset(&act, 0x00, sizeof(struct sigaction));
832         act.sa_handler = (void (*)(int)) sig_handler;
833         sigemptyset(&act.sa_mask);
834         act.sa_flags = SA_RESTART;
835         sigaction(SIGINT, &act, NULL);
836         sigaction(SIGTERM, &act, NULL);
837         sigaction(SIGCHLD, &act, NULL);
838         sigaction(SIGHUP, &act, NULL);
839
840         /* watch rules directory */
841         inotify_fd = inotify_init();
842         if (inotify_fd >= 0) {
843                 if (udev_get_rules_path(udev) != NULL) {
844                         inotify_add_watch(inotify_fd, udev_get_rules_path(udev),
845                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
846                 } else {
847                         char filename[UTIL_PATH_SIZE];
848
849                         inotify_add_watch(inotify_fd, UDEV_PREFIX "/lib/udev/rules.d",
850                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
851                         inotify_add_watch(inotify_fd, SYSCONFDIR "/udev/rules.d",
852                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
853
854                         /* watch dynamic rules directory */
855                         util_strlcpy(filename, udev_get_dev_path(udev), sizeof(filename));
856                         util_strlcat(filename, "/.udev/rules.d", sizeof(filename));
857                         inotify_add_watch(inotify_fd, filename,
858                                           IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
859                 }
860         } else if (errno == ENOSYS)
861                 info(udev, "unable to use inotify, udevd will not monitor rule files changes\n");
862         else
863                 err(udev, "inotify_init failed: %m\n");
864
865         /* in trace mode run one event after the other */
866         if (debug_trace) {
867                 max_childs = 1;
868         } else {
869                 int memsize = mem_size_mb();
870                 if (memsize > 0)
871                         max_childs = 128 + (memsize / 4);
872                 else
873                         max_childs = UDEVD_MAX_CHILDS;
874         }
875         /* possibly overwrite maximum limit of executed events */
876         value = getenv("UDEVD_MAX_CHILDS");
877         if (value)
878                 max_childs = strtoul(value, NULL, 10);
879         info(udev, "initialize max_childs to %u\n", max_childs);
880
881         while (!udev_exit) {
882                 sigset_t blocked_mask, orig_mask;
883                 struct pollfd pfd[4];
884                 struct pollfd *ctrl_poll, *monitor_poll, *inotify_poll = NULL;
885                 int nfds = 0;
886                 int fdcount;
887
888                 sigfillset(&blocked_mask);
889                 sigprocmask(SIG_SETMASK, &blocked_mask, &orig_mask);
890                 if (signal_received) {
891                         sigprocmask(SIG_SETMASK, &orig_mask, NULL);
892                         goto handle_signals;
893                 }
894
895                 ctrl_poll = &pfd[nfds++];
896                 ctrl_poll->fd = udev_ctrl_get_fd(udev_ctrl);
897                 ctrl_poll->events = POLLIN;
898
899                 monitor_poll = &pfd[nfds++];
900                 monitor_poll->fd = udev_monitor_get_fd(kernel_monitor);
901                 monitor_poll->events = POLLIN;
902
903                 if (inotify_fd >= 0) {
904                         inotify_poll = &pfd[nfds++];
905                         inotify_poll->fd = inotify_fd;
906                         inotify_poll->events = POLLIN;
907                 }
908
909                 fdcount = ppoll(pfd, nfds, NULL, &orig_mask);
910                 sigprocmask(SIG_SETMASK, &orig_mask, NULL);
911                 if (fdcount < 0) {
912                         if (errno == EINTR)
913                                 goto handle_signals;
914                         err(udev, "error in select: %m\n");
915                         continue;
916                 }
917
918                 /* get control message */
919                 if (ctrl_poll->revents & POLLIN)
920                         handle_ctrl_msg(udev_ctrl);
921
922                 /* get kernel uevent */
923                 if (monitor_poll->revents & POLLIN) {
924                         struct udev_device *dev;
925
926                         dev = udev_monitor_receive_device(kernel_monitor);
927                         if (dev != NULL) {
928                                 struct udev_event *event;
929
930                                 event = udev_event_new(dev);
931                                 if (event != NULL)
932                                         event_queue_insert(event);
933                                 else
934                                         udev_device_unref(dev);
935                         }
936                 }
937
938                 /* rules directory inotify watch */
939                 if (inotify_poll && (inotify_poll->revents & POLLIN)) {
940                         int nbytes;
941
942                         /* discard all possible events, we can just reload the config */
943                         if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes > 0) {
944                                 char *buf;
945
946                                 reload_config = 1;
947                                 buf = malloc(nbytes);
948                                 if (buf == NULL) {
949                                         err(udev, "error getting buffer for inotify, disable watching\n");
950                                         close(inotify_fd);
951                                         inotify_fd = -1;
952                                 }
953                                 read(inotify_fd, buf, nbytes);
954                                 free(buf);
955                         }
956                 }
957
958 handle_signals:
959                 signal_received = 0;
960
961                 /* rules changed, set by inotify or a HUP signal */
962                 if (reload_config) {
963                         struct udev_rules *rules_new;
964
965                         reload_config = 0;
966                         rules_new = udev_rules_new(udev, resolve_names);
967                         if (rules_new != NULL) {
968                                 udev_rules_unref(rules);
969                                 rules = rules_new;
970                         }
971                 }
972
973                 if (sigchilds_waiting) {
974                         sigchilds_waiting = 0;
975                         reap_sigchilds();
976                 }
977
978                 if (run_exec_q) {
979                         run_exec_q = 0;
980                         if (!stop_exec_q)
981                                 event_queue_manager(udev);
982                 }
983         }
984         cleanup_queue_dir(udev);
985         rc = 0;
986 exit:
987         udev_rules_unref(rules);
988         udev_ctrl_unref(udev_ctrl);
989         if (inotify_fd >= 0)
990                 close(inotify_fd);
991         udev_monitor_unref(kernel_monitor);
992         udev_selinux_exit(udev);
993         udev_unref(udev);
994         logging_close();
995         return rc;
996 }