chiark / gitweb /
Force key release for volume keys on Dell Studio 1557
[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                         if (err == 0)
296                                 failed = udev_event_execute_run(udev_event, &orig_sigmask);
297
298                         alarm(0);
299
300                         /* apply/restore inotify watch */
301                         if (err == 0 && udev_event->inotify_watch) {
302                                 udev_watch_begin(udev_event->udev, dev);
303                                 udev_device_update_db(dev);
304                         }
305
306                         /* send processed event back to libudev listeners */
307                         udev_monitor_send_device(worker_monitor, NULL, dev);
308
309                         /* send udevd the result of the event execution */
310                         if (err != 0)
311                                 msg.exitcode = err;
312                         else if (failed != 0)
313                                 msg.exitcode = failed;
314                         msg.pid = getpid();
315                         send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
316
317                         info(event->udev, "seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
318                         udev_event_unref(udev_event);
319                         udev_device_unref(dev);
320                         dev = NULL;
321
322                         /* wait for more device messages or signal from udevd */
323                         while (!worker_exit) {
324                                 int fdcount;
325
326                                 fdcount = ppoll(&pmon, 1, NULL, &sigmask);
327                                 if (fdcount < 0)
328                                         continue;
329
330                                 if (pmon.revents & POLLIN) {
331                                         dev = udev_monitor_receive_device(worker_monitor);
332                                         if (dev != NULL)
333                                                 break;
334                                 }
335                         }
336                 } while (dev != NULL);
337
338                 udev_monitor_unref(worker_monitor);
339                 udev_log_close();
340                 exit(0);
341         }
342         case -1:
343                 udev_monitor_unref(worker_monitor);
344                 event->state = EVENT_QUEUED;
345                 free(worker);
346                 err(event->udev, "fork of child failed: %m\n");
347                 break;
348         default:
349                 /* close monitor, but keep address around */
350                 udev_monitor_disconnect(worker_monitor);
351                 worker->monitor = worker_monitor;
352                 worker->pid = pid;
353                 worker->state = WORKER_RUNNING;
354                 worker->event = event;
355                 event->state = EVENT_RUNNING;
356                 udev_list_node_append(&worker->node, &worker_list);
357                 childs++;
358                 info(event->udev, "seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
359                 break;
360         }
361 }
362
363 static void event_run(struct event *event)
364 {
365         struct udev_list_node *loop;
366
367         udev_list_node_foreach(loop, &worker_list) {
368                 struct worker *worker = node_to_worker(loop);
369                 ssize_t count;
370
371                 if (worker->state != WORKER_IDLE)
372                         continue;
373
374                 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
375                 if (count < 0) {
376                         err(event->udev, "worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
377                         kill(worker->pid, SIGKILL);
378                         worker->state = WORKER_KILLED;
379                         continue;
380                 }
381                 worker_ref(worker);
382                 worker->event = event;
383                 worker->state = WORKER_RUNNING;
384                 event->state = EVENT_RUNNING;
385                 return;
386         }
387
388         if (childs >= max_childs) {
389                 info(event->udev, "maximum number (%i) of childs reached\n", childs);
390                 return;
391         }
392
393         /* start new worker and pass initial device */
394         worker_new(event);
395 }
396
397 static void event_queue_insert(struct udev_device *dev)
398 {
399         struct event *event;
400
401         event = calloc(1, sizeof(struct event));
402         if (event == NULL)
403                 return;
404
405         event->udev = udev_device_get_udev(dev);
406         event->dev = dev;
407         event->seqnum = udev_device_get_seqnum(dev);
408         event->devpath = udev_device_get_devpath(dev);
409         event->devpath_len = strlen(event->devpath);
410         event->devpath_old = udev_device_get_devpath_old(dev);
411         event->devnum = udev_device_get_devnum(dev);
412         event->is_block = (strcmp("block", udev_device_get_subsystem(dev)) == 0);
413
414         udev_queue_export_device_queued(udev_queue_export, dev);
415         info(event->udev, "seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
416              udev_device_get_action(dev), udev_device_get_subsystem(dev));
417
418         event->state = EVENT_QUEUED;
419         udev_list_node_append(&event->node, &event_list);
420
421         /* run all events with a timeout set immediately */
422         if (udev_device_get_timeout(dev) > 0) {
423                 worker_new(event);
424                 return;
425         }
426 }
427
428 static void worker_kill(struct udev *udev, int retain)
429 {
430         struct udev_list_node *loop;
431         int max;
432
433         if (childs <= retain)
434                 return;
435
436         max = childs - retain;
437
438         udev_list_node_foreach(loop, &worker_list) {
439                 struct worker *worker = node_to_worker(loop);
440
441                 if (max-- <= 0)
442                         break;
443
444                 if (worker->state == WORKER_KILLED)
445                         continue;
446
447                 worker->state = WORKER_KILLED;
448                 kill(worker->pid, SIGTERM);
449         }
450 }
451
452 static int mem_size_mb(void)
453 {
454         FILE *f;
455         char buf[4096];
456         long int memsize = -1;
457
458         f = fopen("/proc/meminfo", "r");
459         if (f == NULL)
460                 return -1;
461
462         while (fgets(buf, sizeof(buf), f) != NULL) {
463                 long int value;
464
465                 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
466                         memsize = value / 1024;
467                         break;
468                 }
469         }
470
471         fclose(f);
472         return memsize;
473 }
474
475 /* lookup event for identical, parent, child device */
476 static bool is_devpath_busy(struct event *event)
477 {
478         struct udev_list_node *loop;
479         size_t common;
480
481         /* check if queue contains events we depend on */
482         udev_list_node_foreach(loop, &event_list) {
483                 struct event *loop_event = node_to_event(loop);
484
485                 /* we already found a later event, earlier can not block us, no need to check again */
486                 if (loop_event->seqnum < event->delaying_seqnum)
487                         continue;
488
489                 /* event we checked earlier still exists, no need to check again */
490                 if (loop_event->seqnum == event->delaying_seqnum)
491                         return true;
492
493                 /* found ourself, no later event can block us */
494                 if (loop_event->seqnum >= event->seqnum)
495                         break;
496
497                 /* check major/minor */
498                 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
499                         return true;
500
501                 /* check our old name */
502                 if (event->devpath_old != NULL && strcmp(loop_event->devpath, event->devpath_old) == 0) {
503                         event->delaying_seqnum = loop_event->seqnum;
504                         return true;
505                 }
506
507                 /* compare devpath */
508                 common = MIN(loop_event->devpath_len, event->devpath_len);
509
510                 /* one devpath is contained in the other? */
511                 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
512                         continue;
513
514                 /* identical device event found */
515                 if (loop_event->devpath_len == event->devpath_len) {
516                         event->delaying_seqnum = loop_event->seqnum;
517                         return true;
518                 }
519
520                 /* parent device event found */
521                 if (event->devpath[common] == '/') {
522                         event->delaying_seqnum = loop_event->seqnum;
523                         return true;
524                 }
525
526                 /* child device event found */
527                 if (loop_event->devpath[common] == '/') {
528                         event->delaying_seqnum = loop_event->seqnum;
529                         return true;
530                 }
531
532                 /* no matching device */
533                 continue;
534         }
535
536         return false;
537 }
538
539 static void events_start(struct udev *udev)
540 {
541         struct udev_list_node *loop;
542
543         udev_list_node_foreach(loop, &event_list) {
544                 struct event *event = node_to_event(loop);
545
546                 if (event->state != EVENT_QUEUED)
547                         continue;
548
549                 /* do not start event if parent or child event is still running */
550                 if (is_devpath_busy(event)) {
551                         dbg(udev, "delay seq %llu (%s)\n", event->seqnum, event->devpath);
552                         continue;
553                 }
554
555                 event_run(event);
556         }
557 }
558
559 static void worker_returned(void)
560 {
561         while (1) {
562                 struct worker_message msg;
563                 ssize_t size;
564                 struct udev_list_node *loop;
565
566                 size = recv(pfd[FD_WORKER].fd, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
567                 if (size != sizeof(struct worker_message))
568                         break;
569
570                 /* lookup worker who sent the signal */
571                 udev_list_node_foreach(loop, &worker_list) {
572                         struct worker *worker = node_to_worker(loop);
573
574                         if (worker->pid != msg.pid)
575                                 continue;
576
577                         /* worker returned */
578                         worker->event->exitcode = msg.exitcode;
579                         event_queue_delete(worker->event);
580                         worker->event = NULL;
581                         if (worker->state != WORKER_KILLED)
582                                 worker->state = WORKER_IDLE;
583                         worker_unref(worker);
584                         break;
585                 }
586         }
587 }
588
589 /* receive the udevd message from userspace */
590 static void handle_ctrl_msg(struct udev_ctrl *uctrl)
591 {
592         struct udev *udev = udev_ctrl_get_udev(uctrl);
593         struct udev_ctrl_msg *ctrl_msg;
594         const char *str;
595         int i;
596
597         ctrl_msg = udev_ctrl_receive_msg(uctrl);
598         if (ctrl_msg == NULL)
599                 return;
600
601         i = udev_ctrl_get_set_log_level(ctrl_msg);
602         if (i >= 0) {
603                 info(udev, "udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
604                 udev_set_log_priority(udev, i);
605                 worker_kill(udev, 0);
606         }
607
608         if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
609                 info(udev, "udevd message (STOP_EXEC_QUEUE) received\n");
610                 stop_exec_queue = true;
611         }
612
613         if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
614                 info(udev, "udevd message (START_EXEC_QUEUE) received\n");
615                 stop_exec_queue = false;
616         }
617
618         if (udev_ctrl_get_reload_rules(ctrl_msg) > 0) {
619                 info(udev, "udevd message (RELOAD_RULES) received\n");
620                 reload_config = true;
621         }
622
623         str = udev_ctrl_get_set_env(ctrl_msg);
624         if (str != NULL) {
625                 char *key;
626
627                 key = strdup(str);
628                 if (key != NULL) {
629                         char *val;
630
631                         val = strchr(key, '=');
632                         if (val != NULL) {
633                                 val[0] = '\0';
634                                 val = &val[1];
635                                 if (val[0] == '\0') {
636                                         info(udev, "udevd message (ENV) received, unset '%s'\n", key);
637                                         udev_add_property(udev, key, NULL);
638                                 } else {
639                                         info(udev, "udevd message (ENV) received, set '%s=%s'\n", key, val);
640                                         udev_add_property(udev, key, val);
641                                 }
642                         } else {
643                                 err(udev, "wrong key format '%s'\n", key);
644                         }
645                         free(key);
646                 }
647                 worker_kill(udev, 0);
648         }
649
650         i = udev_ctrl_get_set_max_childs(ctrl_msg);
651         if (i >= 0) {
652                 info(udev, "udevd message (SET_MAX_CHILDS) received, max_childs=%i\n", i);
653                 max_childs = i;
654         }
655
656         settle_pid = udev_ctrl_get_settle(ctrl_msg);
657         if (settle_pid > 0) {
658                 info(udev, "udevd message (SETTLE) received\n");
659                 kill(settle_pid, SIGUSR1);
660                 settle_pid = 0;
661         }
662         udev_ctrl_msg_unref(ctrl_msg);
663 }
664
665 /* read inotify messages */
666 static int handle_inotify(struct udev *udev)
667 {
668         int nbytes, pos;
669         char *buf;
670         struct inotify_event *ev;
671
672         if ((ioctl(pfd[FD_INOTIFY].fd, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
673                 return 0;
674
675         buf = malloc(nbytes);
676         if (buf == NULL) {
677                 err(udev, "error getting buffer for inotify\n");
678                 return -1;
679         }
680
681         nbytes = read(pfd[FD_INOTIFY].fd, buf, nbytes);
682
683         for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
684                 struct udev_device *dev;
685
686                 ev = (struct inotify_event *)(buf + pos);
687                 if (ev->len) {
688                         dbg(udev, "inotify event: %x for %s\n", ev->mask, ev->name);
689                         reload_config = true;
690                         continue;
691                 }
692
693                 dev = udev_watch_lookup(udev, ev->wd);
694                 if (dev != NULL) {
695                         dbg(udev, "inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
696                         if (ev->mask & IN_CLOSE_WRITE) {
697                                 char filename[UTIL_PATH_SIZE];
698                                 int fd;
699
700                                 info(udev, "device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
701                                 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
702                                 fd = open(filename, O_WRONLY);
703                                 if (fd < 0 || write(fd, "change", 6) < 0)
704                                         info(udev, "error writing uevent: %m\n");
705                                 close(fd);
706                         }
707                         if (ev->mask & IN_IGNORED)
708                                 udev_watch_end(udev, dev);
709
710                         udev_device_unref(dev);
711                 }
712
713         }
714
715         free(buf);
716         return 0;
717 }
718
719 static void handle_signal(struct udev *udev, int signo)
720 {
721         switch (signo) {
722         case SIGINT:
723         case SIGTERM:
724                 udev_exit = true;
725                 break;
726         case SIGCHLD:
727                 while (1) {
728                         pid_t pid;
729                         int status;
730                         struct udev_list_node *loop, *tmp;
731
732                         pid = waitpid(-1, &status, WNOHANG);
733                         if (pid <= 0)
734                                 break;
735
736                         udev_list_node_foreach_safe(loop, tmp, &worker_list) {
737                                 struct worker *worker = node_to_worker(loop);
738
739                                 if (worker->pid != pid)
740                                         continue;
741
742                                 info(udev, "worker [%u] exit\n", pid);
743                                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
744                                         err(udev, "worker [%u] unexpectedly returned with status 0x%04x\n", pid, status);
745                                         if (worker->event != NULL) {
746                                                 err(udev, "worker [%u] failed while handling '%s'\n", pid, worker->event->devpath);
747                                                 worker->event->exitcode = -32;
748                                                 event_queue_delete(worker->event);
749                                                 /* drop reference from running event */
750                                                 worker_unref(worker);
751                                         }
752                                 }
753                                 worker_unref(worker);
754                                 break;
755                         }
756                 }
757                 break;
758         case SIGHUP:
759                 reload_config = true;
760                 break;
761         }
762 }
763
764 int main(int argc, char *argv[])
765 {
766         struct udev *udev;
767         int fd;
768         FILE *f;
769         sigset_t mask;
770         const char *value;
771         int daemonize = false;
772         int resolve_names = 1;
773         static const struct option options[] = {
774                 { "daemon", no_argument, NULL, 'd' },
775                 { "debug-trace", no_argument, NULL, 't' },
776                 { "debug", no_argument, NULL, 'D' },
777                 { "help", no_argument, NULL, 'h' },
778                 { "version", no_argument, NULL, 'V' },
779                 { "resolve-names", required_argument, NULL, 'N' },
780                 {}
781         };
782         int rc = 1;
783
784         udev = udev_new();
785         if (udev == NULL)
786                 goto exit;
787
788         udev_log_init("udevd");
789         udev_set_log_fn(udev, log_fn);
790         info(udev, "version %s\n", VERSION);
791         udev_selinux_init(udev);
792
793         while (1) {
794                 int option;
795
796                 option = getopt_long(argc, argv, "dDthV", options, NULL);
797                 if (option == -1)
798                         break;
799
800                 switch (option) {
801                 case 'd':
802                         daemonize = true;
803                         break;
804                 case 't':
805                         debug_trace = true;
806                         break;
807                 case 'D':
808                         debug = true;
809                         if (udev_get_log_priority(udev) < LOG_INFO)
810                                 udev_set_log_priority(udev, LOG_INFO);
811                         break;
812                 case 'N':
813                         if (strcmp (optarg, "early") == 0) {
814                                 resolve_names = 1;
815                         } else if (strcmp (optarg, "late") == 0) {
816                                 resolve_names = 0;
817                         } else if (strcmp (optarg, "never") == 0) {
818                                 resolve_names = -1;
819                         } else {
820                                 fprintf(stderr, "resolve-names must be early, late or never\n");
821                                 err(udev, "resolve-names must be early, late or never\n");
822                                 goto exit;
823                         }
824                         break;
825                 case 'h':
826                         printf("Usage: udevd [--help] [--daemon] [--debug-trace] [--debug] "
827                                "[--resolve-names=early|late|never] [--version]\n");
828                         goto exit;
829                 case 'V':
830                         printf("%s\n", VERSION);
831                         goto exit;
832                 default:
833                         goto exit;
834                 }
835         }
836
837         if (getuid() != 0) {
838                 fprintf(stderr, "root privileges required\n");
839                 err(udev, "root privileges required\n");
840                 goto exit;
841         }
842
843         /* make sure std{in,out,err} fd's are in a sane state */
844         fd = open("/dev/null", O_RDWR);
845         if (fd < 0) {
846                 fprintf(stderr, "cannot open /dev/null\n");
847                 err(udev, "cannot open /dev/null\n");
848         }
849         if (write(STDOUT_FILENO, 0, 0) < 0)
850                 dup2(fd, STDOUT_FILENO);
851         if (write(STDERR_FILENO, 0, 0) < 0)
852                 dup2(fd, STDERR_FILENO);
853
854         /* init control socket, bind() ensures, that only one udevd instance is running */
855         udev_ctrl = udev_ctrl_new_from_socket(udev, UDEV_CTRL_SOCK_PATH);
856         if (udev_ctrl == NULL) {
857                 fprintf(stderr, "error initializing control socket");
858                 err(udev, "error initializing udevd socket");
859                 rc = 1;
860                 goto exit;
861         }
862         if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
863                 fprintf(stderr, "error binding control socket, seems udevd is already running\n");
864                 err(udev, "error binding control socket, seems udevd is already running\n");
865                 rc = 1;
866                 goto exit;
867         }
868         pfd[FD_CONTROL].fd = udev_ctrl_get_fd(udev_ctrl);
869
870         monitor = udev_monitor_new_from_netlink(udev, "kernel");
871         if (monitor == NULL || udev_monitor_enable_receiving(monitor) < 0) {
872                 fprintf(stderr, "error initializing netlink socket\n");
873                 err(udev, "error initializing netlink socket\n");
874                 rc = 3;
875                 goto exit;
876         }
877         udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
878         pfd[FD_NETLINK].fd = udev_monitor_get_fd(monitor);
879
880         pfd[FD_INOTIFY].fd = udev_watch_init(udev);
881         if (pfd[FD_INOTIFY].fd < 0) {
882                 fprintf(stderr, "error initializing inotify\n");
883                 err(udev, "error initializing inotify\n");
884                 rc = 4;
885                 goto exit;
886         }
887
888         if (udev_get_rules_path(udev) != NULL) {
889                 inotify_add_watch(pfd[FD_INOTIFY].fd, udev_get_rules_path(udev),
890                                   IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
891         } else {
892                 char filename[UTIL_PATH_SIZE];
893                 struct stat statbuf;
894
895                 inotify_add_watch(pfd[FD_INOTIFY].fd, LIBEXECDIR "/rules.d",
896                                   IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
897                 inotify_add_watch(pfd[FD_INOTIFY].fd, SYSCONFDIR "/udev/rules.d",
898                                   IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
899
900                 /* watch dynamic rules directory */
901                 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/rules.d", NULL);
902                 if (stat(filename, &statbuf) != 0) {
903                         util_create_path(udev, filename);
904                         udev_selinux_setfscreatecon(udev, filename, S_IFDIR|0755);
905                         mkdir(filename, 0755);
906                         udev_selinux_resetfscreatecon(udev);
907                 }
908                 inotify_add_watch(pfd[FD_INOTIFY].fd, filename,
909                                   IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
910         }
911         udev_watch_restore(udev);
912
913         /* block and listen to all signals on signalfd */
914         sigfillset(&mask);
915         sigprocmask(SIG_SETMASK, &mask, &orig_sigmask);
916         pfd[FD_SIGNAL].fd = signalfd(-1, &mask, 0);
917         if (pfd[FD_SIGNAL].fd < 0) {
918                 fprintf(stderr, "error getting signalfd\n");
919                 err(udev, "error getting signalfd\n");
920                 rc = 5;
921                 goto exit;
922         }
923
924         /* unnamed socket from workers to the main daemon */
925         if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
926                 fprintf(stderr, "error getting socketpair\n");
927                 err(udev, "error getting socketpair\n");
928                 rc = 6;
929                 goto exit;
930         }
931         pfd[FD_WORKER].fd = worker_watch[READ_END];
932
933         rules = udev_rules_new(udev, resolve_names);
934         if (rules == NULL) {
935                 err(udev, "error reading rules\n");
936                 goto exit;
937         }
938
939         udev_queue_export = udev_queue_export_new(udev);
940         if (udev_queue_export == NULL) {
941                 err(udev, "error creating queue file\n");
942                 goto exit;
943         }
944
945         if (daemonize) {
946                 pid_t pid;
947
948                 pid = fork();
949                 switch (pid) {
950                 case 0:
951                         break;
952                 case -1:
953                         err(udev, "fork of daemon failed: %m\n");
954                         rc = 4;
955                         goto exit;
956                 default:
957                         rc = 0;
958                         goto exit;
959                 }
960         }
961
962         f = fopen("/dev/kmsg", "w");
963         if (f != NULL) {
964                 fprintf(f, "<6>udev: starting version " VERSION "\n");
965                 fclose(f);
966         }
967
968         /* redirect std{out,err} */
969         if (!debug && !debug_trace) {
970                 dup2(fd, STDIN_FILENO);
971                 dup2(fd, STDOUT_FILENO);
972                 dup2(fd, STDERR_FILENO);
973         }
974         if (fd > STDERR_FILENO)
975                 close(fd);
976
977         /* set scheduling priority for the daemon */
978         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
979
980         chdir("/");
981         umask(022);
982         setsid();
983
984         /* OOM_DISABLE == -17 */
985         fd = open("/proc/self/oom_adj", O_RDWR);
986         if (fd < 0) {
987                 err(udev, "error disabling OOM: %m\n");
988         } else {
989                 write(fd, "-17", 3);
990                 close(fd);
991         }
992
993         /* in trace mode run one event after the other */
994         if (debug_trace) {
995                 max_childs = 1;
996         } else {
997                 int memsize = mem_size_mb();
998
999                 if (memsize > 0)
1000                         max_childs = 128 + (memsize / 8);
1001                 else
1002                         max_childs = 128;
1003         }
1004
1005         /* possibly overwrite maximum limit of executed events */
1006         value = getenv("UDEVD_MAX_CHILDS");
1007         if (value)
1008                 max_childs = strtoul(value, NULL, 10);
1009         info(udev, "initialize max_childs to %u\n", max_childs);
1010
1011         udev_list_init(&event_list);
1012         udev_list_init(&worker_list);
1013
1014         while (!udev_exit) {
1015                 int fdcount;
1016                 int timeout;
1017
1018                 /* set timeout to kill idle workers */
1019                 if (udev_list_is_empty(&event_list) && childs > 2)
1020                         timeout = 3 * 1000;
1021                 else
1022                         timeout = -1;
1023                 /* wait for events */
1024                 fdcount = poll(pfd, ARRAY_SIZE(pfd), timeout);
1025                 if (fdcount < 0)
1026                         continue;
1027
1028                 /* timeout - kill idle workers */
1029                 if (fdcount == 0)
1030                         worker_kill(udev, 2);
1031
1032                 /* event has finished */
1033                 if (pfd[FD_WORKER].revents & POLLIN)
1034                         worker_returned();
1035
1036                 /* get kernel uevent */
1037                 if (pfd[FD_NETLINK].revents & POLLIN) {
1038                         struct udev_device *dev;
1039
1040                         dev = udev_monitor_receive_device(monitor);
1041                         if (dev != NULL)
1042                                 event_queue_insert(dev);
1043                         else
1044                                 udev_device_unref(dev);
1045                 }
1046
1047                 /* start new events */
1048                 if (!udev_list_is_empty(&event_list) && !stop_exec_queue)
1049                         events_start(udev);
1050
1051                 /* get signal */
1052                 if (pfd[FD_SIGNAL].revents & POLLIN) {
1053                         struct signalfd_siginfo fdsi;
1054                         ssize_t size;
1055
1056                         size = read(pfd[FD_SIGNAL].fd, &fdsi, sizeof(struct signalfd_siginfo));
1057                         if (size == sizeof(struct signalfd_siginfo))
1058                                 handle_signal(udev, fdsi.ssi_signo);
1059                 }
1060
1061                 /* device node and rules directory inotify watch */
1062                 if (pfd[FD_INOTIFY].revents & POLLIN)
1063                         handle_inotify(udev);
1064
1065                 /*
1066                  * get control message
1067                  *
1068                  * This needs to be after the inotify handling, to make sure,
1069                  * that the settle signal is send back after the possibly generated
1070                  * "change" events by the inotify device node watch.
1071                  */
1072                 if (pfd[FD_CONTROL].revents & POLLIN)
1073                         handle_ctrl_msg(udev_ctrl);
1074
1075                 /* rules changed, set by inotify or a HUP signal */
1076                 if (reload_config) {
1077                         struct udev_rules *rules_new;
1078
1079                         worker_kill(udev, 0);
1080                         rules_new = udev_rules_new(udev, resolve_names);
1081                         if (rules_new != NULL) {
1082                                 udev_rules_unref(rules);
1083                                 rules = rules_new;
1084                         }
1085                         reload_config = 0;
1086                 }
1087         }
1088
1089         udev_queue_export_cleanup(udev_queue_export);
1090         rc = 0;
1091 exit:
1092         udev_queue_export_unref(udev_queue_export);
1093         udev_rules_unref(rules);
1094         udev_ctrl_unref(udev_ctrl);
1095         if (pfd[FD_SIGNAL].fd >= 0)
1096                 close(pfd[FD_SIGNAL].fd);
1097         if (worker_watch[READ_END] >= 0)
1098                 close(worker_watch[READ_END]);
1099         if (worker_watch[WRITE_END] >= 0)
1100                 close(worker_watch[WRITE_END]);
1101         udev_monitor_unref(monitor);
1102         udev_selinux_exit(udev);
1103         udev_unref(udev);
1104         udev_log_close();
1105         return rc;
1106 }