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