chiark / gitweb /
remove "ignore_device"
[elogind.git] / udev / udevd.c
1 /*
2  * Copyright (C) 2004-2009 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 <stdbool.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <getopt.h>
33 #include <dirent.h>
34 #include <sys/time.h>
35 #include <sys/prctl.h>
36 #include <sys/socket.h>
37 #include <sys/signalfd.h>
38 #include <sys/select.h>
39 #include <sys/poll.h>
40 #include <sys/wait.h>
41 #include <sys/stat.h>
42 #include <sys/ioctl.h>
43 #include <sys/inotify.h>
44
45 #include "udev.h"
46
47 #define UDEVD_PRIORITY                  -4
48 #define UDEV_PRIORITY                   -2
49
50 static bool 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                 char buf[1024];
58                 struct timeval tv;
59                 struct timezone tz;
60
61                 vsnprintf(buf, sizeof(buf), format, args);
62                 gettimeofday(&tv, &tz);
63                 fprintf(stderr, "%llu.%06u [%u] %s: %s",
64                         (unsigned long long) tv.tv_sec, (unsigned int) tv.tv_usec,
65                         (int) getpid(), fn, buf);
66         } else {
67                 vsyslog(priority, format, args);
68         }
69 }
70
71 static bool debug_trace;
72 static struct udev_rules *rules;
73 static struct udev_queue_export *udev_queue_export;
74 static struct udev_ctrl *udev_ctrl;
75 static struct udev_monitor *monitor;
76 static int worker_watch[2];
77 static pid_t settle_pid;
78 static bool stop_exec_queue;
79 static bool reload_config;
80 static int max_childs;
81 static int childs;
82 static sigset_t orig_sigmask;
83 static struct udev_list_node event_list;
84 static struct udev_list_node worker_list;
85 static bool udev_exit;
86 static volatile sig_atomic_t worker_exit;
87
88 enum poll_fd {
89         FD_CONTROL,
90         FD_NETLINK,
91         FD_INOTIFY,
92         FD_SIGNAL,
93         FD_WORKER,
94 };
95
96 static struct pollfd pfd[] = {
97         [FD_NETLINK] = { .events = POLLIN },
98         [FD_WORKER] =  { .events = POLLIN },
99         [FD_SIGNAL] =  { .events = POLLIN },
100         [FD_INOTIFY] = { .events = POLLIN },
101         [FD_CONTROL] = { .events = POLLIN },
102 };
103
104 enum event_state {
105         EVENT_UNDEF,
106         EVENT_QUEUED,
107         EVENT_RUNNING,
108 };
109
110 struct event {
111         struct udev_list_node node;
112         struct udev *udev;
113         struct udev_device *dev;
114         enum event_state state;
115         int exitcode;
116         unsigned long long int delaying_seqnum;
117         unsigned long long int seqnum;
118         const char *devpath;
119         size_t devpath_len;
120         const char *devpath_old;
121         dev_t devnum;
122         bool is_block;
123 };
124
125 static struct event *node_to_event(struct udev_list_node *node)
126 {
127         char *event;
128
129         event = (char *)node;
130         event -= offsetof(struct event, node);
131         return (struct event *)event;
132 }
133
134 enum worker_state {
135         WORKER_UNDEF,
136         WORKER_RUNNING,
137         WORKER_IDLE,
138         WORKER_KILLED,
139 };
140
141 struct worker {
142         struct udev_list_node node;
143         struct udev *udev;
144         int refcount;
145         pid_t pid;
146         struct udev_monitor *monitor;
147         enum worker_state state;
148         struct event *event;
149 };
150
151 /* passed from worker to main process */
152 struct worker_message {
153         pid_t pid;
154         int exitcode;
155 };
156
157 static struct worker *node_to_worker(struct udev_list_node *node)
158 {
159         char *worker;
160
161         worker = (char *)node;
162         worker -= offsetof(struct worker, node);
163         return (struct worker *)worker;
164 }
165
166 static void event_queue_delete(struct event *event)
167 {
168         udev_list_node_remove(&event->node);
169
170         /* mark as failed, if "add" event returns non-zero */
171         if (event->exitcode != 0 && strcmp(udev_device_get_action(event->dev), "add") == 0)
172                 udev_queue_export_device_failed(udev_queue_export, event->dev);
173         else
174                 udev_queue_export_device_finished(udev_queue_export, event->dev);
175
176         info(event->udev, "seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
177         udev_device_unref(event->dev);
178         free(event);
179 }
180
181 static void event_sig_handler(int signum)
182 {
183         switch (signum) {
184         case SIGALRM:
185                 _exit(1);
186                 break;
187         case SIGTERM:
188                 worker_exit = true;
189                 break;
190         }
191 }
192
193 static struct worker *worker_ref(struct worker *worker)
194 {
195         worker->refcount++;
196         return worker;
197 }
198
199 static void worker_unref(struct worker *worker)
200 {
201         worker->refcount--;
202         if (worker->refcount > 0)
203                 return;
204
205         udev_list_node_remove(&worker->node);
206         udev_monitor_unref(worker->monitor);
207         childs--;
208         info(worker->udev, "worker [%u] cleaned up\n", worker->pid);
209         free(worker);
210 }
211
212 static void worker_new(struct event *event)
213 {
214         struct worker *worker;
215         struct udev_monitor *worker_monitor;
216         pid_t pid;
217         struct sigaction act;
218
219         /* listen for new events */
220         worker_monitor = udev_monitor_new_from_netlink(event->udev, NULL);
221         if (worker_monitor == NULL)
222                 return;
223         /* allow the main daemon netlink address to send devices to the worker */
224         udev_monitor_allow_unicast_sender(worker_monitor, monitor);
225         udev_monitor_enable_receiving(worker_monitor);
226
227         worker = calloc(1, sizeof(struct worker));
228         if (worker == NULL)
229                 return;
230         /* worker + event reference */
231         worker->refcount = 2;
232         worker->udev = event->udev;
233
234         pid = fork();
235         switch (pid) {
236         case 0: {
237                 sigset_t sigmask;
238                 struct udev_device *dev;
239                 struct pollfd pmon = {
240                         .fd = udev_monitor_get_fd(worker_monitor),
241                         .events = POLLIN,
242                 };
243
244                 udev_queue_export_unref(udev_queue_export);
245                 udev_monitor_unref(monitor);
246                 udev_ctrl_unref(udev_ctrl);
247                 close(pfd[FD_SIGNAL].fd);
248                 close(worker_watch[READ_END]);
249                 udev_log_close();
250                 udev_log_init("udevd-work");
251                 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
252
253                 /* set signal handlers */
254                 memset(&act, 0x00, sizeof(act));
255                 act.sa_handler = event_sig_handler;
256                 sigemptyset (&act.sa_mask);
257                 act.sa_flags = 0;
258                 sigaction(SIGTERM, &act, NULL);
259                 sigaction(SIGALRM, &act, NULL);
260
261                 /* unblock SIGALRM */
262                 sigfillset(&sigmask);
263                 sigdelset(&sigmask, SIGALRM);
264                 sigprocmask(SIG_SETMASK, &sigmask, NULL);
265                 /* SIGTERM is unblocked in ppoll() */
266                 sigdelset(&sigmask, SIGTERM);
267
268                 /* request TERM signal if parent exits */
269                 prctl(PR_SET_PDEATHSIG, SIGTERM);
270
271                 /* initial device */
272                 dev = event->dev;
273
274                 do {
275                         struct udev_event *udev_event;
276                         struct worker_message msg = {};
277                         int err;
278                         int failed = 0;
279
280                         info(event->udev, "seq %llu running\n", udev_device_get_seqnum(dev));
281                         udev_event = udev_event_new(dev);
282                         if (udev_event == NULL)
283                                 _exit(3);
284
285                         /* set timeout to prevent hanging processes */
286                         alarm(UDEV_EVENT_TIMEOUT);
287
288                         /* apply rules, create node, symlinks */
289                         err = udev_event_execute_rules(udev_event, rules);
290
291                         /* rules may change/disable the timeout */
292                         if (udev_device_get_event_timeout(dev) >= 0)
293                                 alarm(udev_device_get_event_timeout(dev));
294
295                         /* execute RUN= */
296                         if (err == 0 && udev_get_run(udev_event->udev))
297                                 failed = udev_event_execute_run(udev_event,
298                                                                 &orig_sigmask);
299
300                         /* reset alarm */
301                         alarm(0);
302
303                         /* apply/restore inotify watch */
304                         if (err == 0 && udev_event->inotify_watch) {
305                                 udev_watch_begin(udev_event->udev, dev);
306                                 udev_device_update_db(dev);
307                         }
308
309                         /* send processed event back to libudev listeners */
310                         udev_monitor_send_device(worker_monitor, NULL, dev);
311
312                         /* send back the result of the event execution */
313                         if (err != 0)
314                                 msg.exitcode = err;
315                         else if (failed != 0)
316                                 msg.exitcode = failed;
317                         msg.pid = getpid();
318                         send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
319
320                         info(event->udev, "seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
321                         udev_event_unref(udev_event);
322                         udev_device_unref(dev);
323                         dev = NULL;
324
325                         /* wait for more device messages or signal from udevd */
326                         while (!worker_exit) {
327                                 int fdcount;
328
329                                 fdcount = ppoll(&pmon, 1, NULL, &sigmask);
330                                 if (fdcount < 0)
331                                         continue;
332
333                                 if (pmon.revents & POLLIN) {
334                                         dev = udev_monitor_receive_device(worker_monitor);
335                                         if (dev != NULL)
336                                                 break;
337                                 }
338                         }
339                 } while (dev != NULL);
340
341                 udev_monitor_unref(worker_monitor);
342                 udev_log_close();
343                 exit(0);
344         }
345         case -1:
346                 udev_monitor_unref(worker_monitor);
347                 event->state = EVENT_QUEUED;
348                 free(worker);
349                 err(event->udev, "fork of child failed: %m\n");
350                 break;
351         default:
352                 /* close monitor, but keep address around */
353                 udev_monitor_disconnect(worker_monitor);
354                 worker->monitor = worker_monitor;
355                 worker->pid = pid;
356                 worker->state = WORKER_RUNNING;
357                 worker->event = event;
358                 event->state = EVENT_RUNNING;
359                 udev_list_node_append(&worker->node, &worker_list);
360                 childs++;
361                 info(event->udev, "seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
362                 break;
363         }
364 }
365
366 static void event_run(struct event *event)
367 {
368         struct udev_list_node *loop;
369
370         udev_list_node_foreach(loop, &worker_list) {
371                 struct worker *worker = node_to_worker(loop);
372                 ssize_t count;
373
374                 if (worker->state != WORKER_IDLE)
375                         continue;
376
377                 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
378                 if (count < 0) {
379                         err(event->udev, "worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
380                         kill(worker->pid, SIGKILL);
381                         worker->state = WORKER_KILLED;
382                         continue;
383                 }
384                 worker_ref(worker);
385                 worker->event = event;
386                 worker->state = WORKER_RUNNING;
387                 event->state = EVENT_RUNNING;
388                 return;
389         }
390
391         if (childs >= max_childs) {
392                 info(event->udev, "maximum number (%i) of childs reached\n", childs);
393                 return;
394         }
395
396         /* start new worker and pass initial device */
397         worker_new(event);
398 }
399
400 static void event_queue_insert(struct udev_device *dev)
401 {
402         struct event *event;
403
404         event = calloc(1, sizeof(struct event));
405         if (event == NULL)
406                 return;
407
408         event->udev = udev_device_get_udev(dev);
409         event->dev = dev;
410         event->seqnum = udev_device_get_seqnum(dev);
411         event->devpath = udev_device_get_devpath(dev);
412         event->devpath_len = strlen(event->devpath);
413         event->devpath_old = udev_device_get_devpath_old(dev);
414         event->devnum = udev_device_get_devnum(dev);
415         event->is_block = (strcmp("block", udev_device_get_subsystem(dev)) == 0);
416
417         udev_queue_export_device_queued(udev_queue_export, dev);
418         info(event->udev, "seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
419              udev_device_get_action(dev), udev_device_get_subsystem(dev));
420
421         event->state = EVENT_QUEUED;
422         udev_list_node_append(&event->node, &event_list);
423
424         /* run all events with a timeout set immediately */
425         if (udev_device_get_timeout(dev) > 0) {
426                 worker_new(event);
427                 return;
428         }
429 }
430
431 static void worker_kill(struct udev *udev, int retain)
432 {
433         struct udev_list_node *loop;
434         int max;
435
436         if (childs <= retain)
437                 return;
438
439         max = childs - retain;
440
441         udev_list_node_foreach(loop, &worker_list) {
442                 struct worker *worker = node_to_worker(loop);
443
444                 if (max-- <= 0)
445                         break;
446
447                 if (worker->state == WORKER_KILLED)
448                         continue;
449
450                 worker->state = WORKER_KILLED;
451                 kill(worker->pid, SIGTERM);
452         }
453 }
454
455 static int mem_size_mb(void)
456 {
457         FILE *f;
458         char buf[4096];
459         long int memsize = -1;
460
461         f = fopen("/proc/meminfo", "r");
462         if (f == NULL)
463                 return -1;
464
465         while (fgets(buf, sizeof(buf), f) != NULL) {
466                 long int value;
467
468                 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
469                         memsize = value / 1024;
470                         break;
471                 }
472         }
473
474         fclose(f);
475         return memsize;
476 }
477
478 /* lookup event for identical, parent, child device */
479 static bool is_devpath_busy(struct event *event)
480 {
481         struct udev_list_node *loop;
482         size_t common;
483
484         /* check if queue contains events we depend on */
485         udev_list_node_foreach(loop, &event_list) {
486                 struct event *loop_event = node_to_event(loop);
487
488                 /* we already found a later event, earlier can not block us, no need to check again */
489                 if (loop_event->seqnum < event->delaying_seqnum)
490                         continue;
491
492                 /* event we checked earlier still exists, no need to check again */
493                 if (loop_event->seqnum == event->delaying_seqnum)
494                         return true;
495
496                 /* found ourself, no later event can block us */
497                 if (loop_event->seqnum >= event->seqnum)
498                         break;
499
500                 /* check major/minor */
501                 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
502                         return true;
503
504                 /* check our old name */
505                 if (event->devpath_old != NULL && strcmp(loop_event->devpath, event->devpath_old) == 0) {
506                         event->delaying_seqnum = loop_event->seqnum;
507                         return true;
508                 }
509
510                 /* compare devpath */
511                 common = MIN(loop_event->devpath_len, event->devpath_len);
512
513                 /* one devpath is contained in the other? */
514                 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
515                         continue;
516
517                 /* identical device event found */
518                 if (loop_event->devpath_len == event->devpath_len) {
519                         event->delaying_seqnum = loop_event->seqnum;
520                         return true;
521                 }
522
523                 /* parent device event found */
524                 if (event->devpath[common] == '/') {
525                         event->delaying_seqnum = loop_event->seqnum;
526                         return true;
527                 }
528
529                 /* child device event found */
530                 if (loop_event->devpath[common] == '/') {
531                         event->delaying_seqnum = loop_event->seqnum;
532                         return true;
533                 }
534
535                 /* no matching device */
536                 continue;
537         }
538
539         return false;
540 }
541
542 static void events_start(struct udev *udev)
543 {
544         struct udev_list_node *loop;
545
546         udev_list_node_foreach(loop, &event_list) {
547                 struct event *event = node_to_event(loop);
548
549                 if (event->state != EVENT_QUEUED)
550                         continue;
551
552                 /* do not start event if parent or child event is still running */
553                 if (is_devpath_busy(event)) {
554                         dbg(udev, "delay seq %llu (%s)\n", event->seqnum, event->devpath);
555                         continue;
556                 }
557
558                 event_run(event);
559         }
560 }
561
562 static void worker_returned(void)
563 {
564         while (1) {
565                 struct worker_message msg;
566                 ssize_t size;
567                 struct udev_list_node *loop;
568
569                 size = recv(pfd[FD_WORKER].fd, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
570                 if (size != sizeof(struct worker_message))
571                         break;
572
573                 /* lookup worker who sent the signal */
574                 udev_list_node_foreach(loop, &worker_list) {
575                         struct worker *worker = node_to_worker(loop);
576
577                         if (worker->pid != msg.pid)
578                                 continue;
579
580                         /* worker returned */
581                         worker->event->exitcode = msg.exitcode;
582                         event_queue_delete(worker->event);
583                         worker->event = NULL;
584                         if (worker->state != WORKER_KILLED)
585                                 worker->state = WORKER_IDLE;
586                         worker_unref(worker);
587                         break;
588                 }
589         }
590 }
591
592 /* receive the udevd message from userspace */
593 static void handle_ctrl_msg(struct udev_ctrl *uctrl)
594 {
595         struct udev *udev = udev_ctrl_get_udev(uctrl);
596         struct udev_ctrl_msg *ctrl_msg;
597         const char *str;
598         int i;
599
600         ctrl_msg = udev_ctrl_receive_msg(uctrl);
601         if (ctrl_msg == NULL)
602                 return;
603
604         i = udev_ctrl_get_set_log_level(ctrl_msg);
605         if (i >= 0) {
606                 info(udev, "udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
607                 udev_set_log_priority(udev, i);
608                 worker_kill(udev, 0);
609         }
610
611         if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
612                 info(udev, "udevd message (STOP_EXEC_QUEUE) received\n");
613                 stop_exec_queue = true;
614         }
615
616         if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
617                 info(udev, "udevd message (START_EXEC_QUEUE) received\n");
618                 stop_exec_queue = false;
619         }
620
621         if (udev_ctrl_get_reload_rules(ctrl_msg) > 0) {
622                 info(udev, "udevd message (RELOAD_RULES) received\n");
623                 reload_config = true;
624         }
625
626         str = udev_ctrl_get_set_env(ctrl_msg);
627         if (str != NULL) {
628                 char *key;
629
630                 key = strdup(str);
631                 if (key != NULL) {
632                         char *val;
633
634                         val = strchr(key, '=');
635                         if (val != NULL) {
636                                 val[0] = '\0';
637                                 val = &val[1];
638                                 if (val[0] == '\0') {
639                                         info(udev, "udevd message (ENV) received, unset '%s'\n", key);
640                                         udev_add_property(udev, key, NULL);
641                                 } else {
642                                         info(udev, "udevd message (ENV) received, set '%s=%s'\n", key, val);
643                                         udev_add_property(udev, key, val);
644                                 }
645                         } else {
646                                 err(udev, "wrong key format '%s'\n", key);
647                         }
648                         free(key);
649                 }
650                 worker_kill(udev, 0);
651         }
652
653         i = udev_ctrl_get_set_max_childs(ctrl_msg);
654         if (i >= 0) {
655                 info(udev, "udevd message (SET_MAX_CHILDS) received, max_childs=%i\n", i);
656                 max_childs = i;
657         }
658
659         settle_pid = udev_ctrl_get_settle(ctrl_msg);
660         if (settle_pid > 0) {
661                 info(udev, "udevd message (SETTLE) received\n");
662                 kill(settle_pid, SIGUSR1);
663                 settle_pid = 0;
664         }
665         udev_ctrl_msg_unref(ctrl_msg);
666 }
667
668 /* read inotify messages */
669 static int handle_inotify(struct udev *udev)
670 {
671         int nbytes, pos;
672         char *buf;
673         struct inotify_event *ev;
674
675         if ((ioctl(pfd[FD_INOTIFY].fd, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
676                 return 0;
677
678         buf = malloc(nbytes);
679         if (buf == NULL) {
680                 err(udev, "error getting buffer for inotify\n");
681                 return -1;
682         }
683
684         nbytes = read(pfd[FD_INOTIFY].fd, buf, nbytes);
685
686         for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
687                 struct udev_device *dev;
688
689                 ev = (struct inotify_event *)(buf + pos);
690                 if (ev->len) {
691                         dbg(udev, "inotify event: %x for %s\n", ev->mask, ev->name);
692                         reload_config = true;
693                         continue;
694                 }
695
696                 dev = udev_watch_lookup(udev, ev->wd);
697                 if (dev != NULL) {
698                         dbg(udev, "inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
699                         if (ev->mask & IN_CLOSE_WRITE) {
700                                 char filename[UTIL_PATH_SIZE];
701                                 int fd;
702
703                                 info(udev, "device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
704                                 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
705                                 fd = open(filename, O_WRONLY);
706                                 if (fd < 0 || write(fd, "change", 6) < 0)
707                                         info(udev, "error writing uevent: %m\n");
708                                 close(fd);
709                         }
710                         if (ev->mask & IN_IGNORED)
711                                 udev_watch_end(udev, dev);
712
713                         udev_device_unref(dev);
714                 }
715
716         }
717
718         free(buf);
719         return 0;
720 }
721
722 static void handle_signal(struct udev *udev, int signo)
723 {
724         switch (signo) {
725         case SIGINT:
726         case SIGTERM:
727                 udev_exit = true;
728                 break;
729         case SIGCHLD:
730                 while (1) {
731                         pid_t pid;
732                         int status;
733                         struct udev_list_node *loop, *tmp;
734
735                         pid = waitpid(-1, &status, WNOHANG);
736                         if (pid <= 0)
737                                 break;
738
739                         udev_list_node_foreach_safe(loop, tmp, &worker_list) {
740                                 struct worker *worker = node_to_worker(loop);
741
742                                 if (worker->pid != pid)
743                                         continue;
744
745                                 info(udev, "worker [%u] exit\n", pid);
746                                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
747                                         err(udev, "worker [%u] unexpectedly returned with status 0x%04x\n", pid, status);
748                                         if (worker->event != NULL) {
749                                                 err(udev, "worker [%u] failed while handling '%s'\n", pid, worker->event->devpath);
750                                                 worker->event->exitcode = -32;
751                                                 event_queue_delete(worker->event);
752                                                 /* drop reference from running event */
753                                                 worker_unref(worker);
754                                         }
755                                 }
756                                 worker_unref(worker);
757                                 break;
758                         }
759                 }
760                 break;
761         case SIGHUP:
762                 reload_config = true;
763                 break;
764         }
765 }
766
767 static void startup_log(struct udev *udev)
768 {
769         FILE *f;
770         char path[UTIL_PATH_SIZE];
771         struct stat statbuf;
772
773         f = fopen("/dev/kmsg", "w");
774         if (f != NULL)
775                 fprintf(f, "<6>udev: starting version " VERSION "\n");
776
777         util_strscpyl(path, sizeof(path), udev_get_sys_path(udev), "/class/mem/null", NULL);
778         if (lstat(path, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) {
779                 const char *depr_str =
780                         "udev: missing sysfs features; please update the kernel "
781                         "or disable the kernel's CONFIG_SYSFS_DEPRECATED option; "
782                         "udev may fail to work correctly";
783
784                 if (f != NULL)
785                         fprintf(f, "<3>%s\n", depr_str);
786                 err(udev, "%s\n", depr_str);
787                 sleep(15);
788         }
789
790         if (f != NULL)
791                 fclose(f);
792 }
793
794 int main(int argc, char *argv[])
795 {
796         struct udev *udev;
797         int fd;
798         sigset_t mask;
799         const char *value;
800         int daemonize = false;
801         int resolve_names = 1;
802         static const struct option options[] = {
803                 { "daemon", no_argument, NULL, 'd' },
804                 { "debug-trace", no_argument, NULL, 't' },
805                 { "debug", no_argument, NULL, 'D' },
806                 { "help", no_argument, NULL, 'h' },
807                 { "version", no_argument, NULL, 'V' },
808                 { "resolve-names", required_argument, NULL, 'N' },
809                 {}
810         };
811         int rc = 1;
812
813         udev = udev_new();
814         if (udev == NULL)
815                 goto exit;
816
817         udev_log_init("udevd");
818         udev_set_log_fn(udev, log_fn);
819         info(udev, "version %s\n", VERSION);
820         udev_selinux_init(udev);
821
822         while (1) {
823                 int option;
824
825                 option = getopt_long(argc, argv, "dDthV", options, NULL);
826                 if (option == -1)
827                         break;
828
829                 switch (option) {
830                 case 'd':
831                         daemonize = true;
832                         break;
833                 case 't':
834                         debug_trace = true;
835                         break;
836                 case 'D':
837                         debug = true;
838                         if (udev_get_log_priority(udev) < LOG_INFO)
839                                 udev_set_log_priority(udev, LOG_INFO);
840                         break;
841                 case 'N':
842                         if (strcmp (optarg, "early") == 0) {
843                                 resolve_names = 1;
844                         } else if (strcmp (optarg, "late") == 0) {
845                                 resolve_names = 0;
846                         } else if (strcmp (optarg, "never") == 0) {
847                                 resolve_names = -1;
848                         } else {
849                                 fprintf(stderr, "resolve-names must be early, late or never\n");
850                                 err(udev, "resolve-names must be early, late or never\n");
851                                 goto exit;
852                         }
853                         break;
854                 case 'h':
855                         printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--debug] "
856                                "[--resolve-names=early|late|never] [--version]\n");
857                         goto exit;
858                 case 'V':
859                         printf("%s\n", VERSION);
860                         goto exit;
861                 default:
862                         goto exit;
863                 }
864         }
865
866         if (getuid() != 0) {
867                 fprintf(stderr, "root privileges required\n");
868                 err(udev, "root privileges required\n");
869                 goto exit;
870         }
871
872         /* make sure std{in,out,err} fd's are in a sane state */
873         fd = open("/dev/null", O_RDWR);
874         if (fd < 0) {
875                 fprintf(stderr, "cannot open /dev/null\n");
876                 err(udev, "cannot open /dev/null\n");
877         }
878         if (write(STDOUT_FILENO, 0, 0) < 0)
879                 dup2(fd, STDOUT_FILENO);
880         if (write(STDERR_FILENO, 0, 0) < 0)
881                 dup2(fd, STDERR_FILENO);
882
883         /* init control socket, bind() ensures, that only one udevd instance is running */
884         udev_ctrl = udev_ctrl_new_from_socket(udev, UDEV_CTRL_SOCK_PATH);
885         if (udev_ctrl == NULL) {
886                 fprintf(stderr, "error initializing control socket");
887                 err(udev, "error initializing udevd socket");
888                 rc = 1;
889                 goto exit;
890         }
891         if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
892                 fprintf(stderr, "error binding control socket, seems udevd is already running\n");
893                 err(udev, "error binding control socket, seems udevd is already running\n");
894                 rc = 1;
895                 goto exit;
896         }
897         pfd[FD_CONTROL].fd = udev_ctrl_get_fd(udev_ctrl);
898
899         monitor = udev_monitor_new_from_netlink(udev, "kernel");
900         if (monitor == NULL || udev_monitor_enable_receiving(monitor) < 0) {
901                 fprintf(stderr, "error initializing netlink socket\n");
902                 err(udev, "error initializing netlink socket\n");
903                 rc = 3;
904                 goto exit;
905         }
906         udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
907         pfd[FD_NETLINK].fd = udev_monitor_get_fd(monitor);
908
909         pfd[FD_INOTIFY].fd = udev_watch_init(udev);
910         if (pfd[FD_INOTIFY].fd < 0) {
911                 fprintf(stderr, "error initializing inotify\n");
912                 err(udev, "error initializing inotify\n");
913                 rc = 4;
914                 goto exit;
915         }
916
917         if (udev_get_rules_path(udev) != NULL) {
918                 inotify_add_watch(pfd[FD_INOTIFY].fd, udev_get_rules_path(udev),
919                                   IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
920         } else {
921                 char filename[UTIL_PATH_SIZE];
922                 struct stat statbuf;
923
924                 inotify_add_watch(pfd[FD_INOTIFY].fd, LIBEXECDIR "/rules.d",
925                                   IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
926                 inotify_add_watch(pfd[FD_INOTIFY].fd, SYSCONFDIR "/udev/rules.d",
927                                   IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
928
929                 /* watch dynamic rules directory */
930                 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/rules.d", NULL);
931                 if (stat(filename, &statbuf) != 0) {
932                         util_create_path(udev, filename);
933                         udev_selinux_setfscreatecon(udev, filename, S_IFDIR|0755);
934                         mkdir(filename, 0755);
935                         udev_selinux_resetfscreatecon(udev);
936                 }
937                 inotify_add_watch(pfd[FD_INOTIFY].fd, filename,
938                                   IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
939         }
940         udev_watch_restore(udev);
941
942         /* block and listen to all signals on signalfd */
943         sigfillset(&mask);
944         sigprocmask(SIG_SETMASK, &mask, &orig_sigmask);
945         pfd[FD_SIGNAL].fd = signalfd(-1, &mask, 0);
946         if (pfd[FD_SIGNAL].fd < 0) {
947                 fprintf(stderr, "error getting signalfd\n");
948                 err(udev, "error getting signalfd\n");
949                 rc = 5;
950                 goto exit;
951         }
952
953         /* unnamed socket from workers to the main daemon */
954         if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
955                 fprintf(stderr, "error getting socketpair\n");
956                 err(udev, "error getting socketpair\n");
957                 rc = 6;
958                 goto exit;
959         }
960         pfd[FD_WORKER].fd = worker_watch[READ_END];
961
962         rules = udev_rules_new(udev, resolve_names);
963         if (rules == NULL) {
964                 err(udev, "error reading rules\n");
965                 goto exit;
966         }
967
968         udev_queue_export = udev_queue_export_new(udev);
969         if (udev_queue_export == NULL) {
970                 err(udev, "error creating queue file\n");
971                 goto exit;
972         }
973
974         if (daemonize) {
975                 pid_t pid;
976
977                 pid = fork();
978                 switch (pid) {
979                 case 0:
980                         break;
981                 case -1:
982                         err(udev, "fork of daemon failed: %m\n");
983                         rc = 4;
984                         goto exit;
985                 default:
986                         rc = 0;
987                         goto exit;
988                 }
989         }
990
991         startup_log(udev);
992
993         /* redirect std{out,err} */
994         if (!debug && !debug_trace) {
995                 dup2(fd, STDIN_FILENO);
996                 dup2(fd, STDOUT_FILENO);
997                 dup2(fd, STDERR_FILENO);
998         }
999         if (fd > STDERR_FILENO)
1000                 close(fd);
1001
1002         /* set scheduling priority for the daemon */
1003         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
1004
1005         chdir("/");
1006         umask(022);
1007         setsid();
1008
1009         /* OOM_DISABLE == -17 */
1010         fd = open("/proc/self/oom_adj", O_RDWR);
1011         if (fd < 0) {
1012                 err(udev, "error disabling OOM: %m\n");
1013         } else {
1014                 write(fd, "-17", 3);
1015                 close(fd);
1016         }
1017
1018         /* in trace mode run one event after the other */
1019         if (debug_trace) {
1020                 max_childs = 1;
1021         } else {
1022                 int memsize = mem_size_mb();
1023
1024                 if (memsize > 0)
1025                         max_childs = 128 + (memsize / 8);
1026                 else
1027                         max_childs = 128;
1028         }
1029
1030         /* possibly overwrite maximum limit of executed events */
1031         value = getenv("UDEVD_MAX_CHILDS");
1032         if (value)
1033                 max_childs = strtoul(value, NULL, 10);
1034         info(udev, "initialize max_childs to %u\n", max_childs);
1035
1036         udev_list_init(&event_list);
1037         udev_list_init(&worker_list);
1038
1039         while (!udev_exit) {
1040                 int fdcount;
1041                 int timeout;
1042
1043                 /* set timeout to kill idle workers */
1044                 if (udev_list_is_empty(&event_list) && childs > 2)
1045                         timeout = 3 * 1000;
1046                 else
1047                         timeout = -1;
1048                 /* wait for events */
1049                 fdcount = poll(pfd, ARRAY_SIZE(pfd), timeout);
1050                 if (fdcount < 0)
1051                         continue;
1052
1053                 /* timeout - kill idle workers */
1054                 if (fdcount == 0)
1055                         worker_kill(udev, 2);
1056
1057                 /* event has finished */
1058                 if (pfd[FD_WORKER].revents & POLLIN)
1059                         worker_returned();
1060
1061                 /* get kernel uevent */
1062                 if (pfd[FD_NETLINK].revents & POLLIN) {
1063                         struct udev_device *dev;
1064
1065                         dev = udev_monitor_receive_device(monitor);
1066                         if (dev != NULL)
1067                                 event_queue_insert(dev);
1068                         else
1069                                 udev_device_unref(dev);
1070                 }
1071
1072                 /* start new events */
1073                 if (!udev_list_is_empty(&event_list) && !stop_exec_queue)
1074                         events_start(udev);
1075
1076                 /* get signal */
1077                 if (pfd[FD_SIGNAL].revents & POLLIN) {
1078                         struct signalfd_siginfo fdsi;
1079                         ssize_t size;
1080
1081                         size = read(pfd[FD_SIGNAL].fd, &fdsi, sizeof(struct signalfd_siginfo));
1082                         if (size == sizeof(struct signalfd_siginfo))
1083                                 handle_signal(udev, fdsi.ssi_signo);
1084                 }
1085
1086                 /* device node and rules directory inotify watch */
1087                 if (pfd[FD_INOTIFY].revents & POLLIN)
1088                         handle_inotify(udev);
1089
1090                 /*
1091                  * get control message
1092                  *
1093                  * This needs to be after the inotify handling, to make sure,
1094                  * that the settle signal is send back after the possibly generated
1095                  * "change" events by the inotify device node watch.
1096                  */
1097                 if (pfd[FD_CONTROL].revents & POLLIN)
1098                         handle_ctrl_msg(udev_ctrl);
1099
1100                 /* rules changed, set by inotify or a HUP signal */
1101                 if (reload_config) {
1102                         struct udev_rules *rules_new;
1103
1104                         worker_kill(udev, 0);
1105                         rules_new = udev_rules_new(udev, resolve_names);
1106                         if (rules_new != NULL) {
1107                                 udev_rules_unref(rules);
1108                                 rules = rules_new;
1109                         }
1110                         reload_config = 0;
1111                 }
1112         }
1113
1114         udev_queue_export_cleanup(udev_queue_export);
1115         rc = 0;
1116 exit:
1117         udev_queue_export_unref(udev_queue_export);
1118         udev_rules_unref(rules);
1119         udev_ctrl_unref(udev_ctrl);
1120         if (pfd[FD_SIGNAL].fd >= 0)
1121                 close(pfd[FD_SIGNAL].fd);
1122         if (worker_watch[READ_END] >= 0)
1123                 close(worker_watch[READ_END]);
1124         if (worker_watch[WRITE_END] >= 0)
1125                 close(worker_watch[WRITE_END]);
1126         udev_monitor_unref(monitor);
1127         udev_selinux_exit(udev);
1128         udev_unref(udev);
1129         udev_log_close();
1130         return rc;
1131 }