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