]> git.ipfire.org Git - thirdparty/systemd.git/blame - udev/udevd.c
move rules dirs to udev context; replace inotify with time-controlled stat()
[thirdparty/systemd.git] / udev / udevd.c
CommitLineData
7fafc032 1/*
ff2c503d 2 * Copyright (C) 2004-2011 Kay Sievers <kay.sievers@vrfy.org>
2f6cbd19 3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
bb38678e
SJR
4 * Copyright (C) 2009 Canonical Ltd.
5 * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
7fafc032 6 *
55e9959b
KS
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.
7fafc032 11 *
55e9959b
KS
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.
7fafc032 16 *
55e9959b
KS
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/>.
7fafc032
KS
19 */
20
a695feae 21#include <stddef.h>
7fafc032
KS
22#include <signal.h>
23#include <unistd.h>
24#include <errno.h>
25#include <stdio.h>
26#include <stdlib.h>
c3804728 27#include <stdbool.h>
7fafc032 28#include <string.h>
085cce37 29#include <ctype.h>
085cce37 30#include <fcntl.h>
0b3dfb3d 31#include <time.h>
b52a01ee 32#include <getopt.h>
78230c0d 33#include <dirent.h>
820fc48f 34#include <sys/time.h>
1e03b754
KS
35#include <sys/prctl.h>
36#include <sys/socket.h>
a65aa40f 37#include <sys/un.h>
1e03b754 38#include <sys/signalfd.h>
ff2c503d 39#include <sys/epoll.h>
3210a72b 40#include <sys/poll.h>
138068d6 41#include <sys/wait.h>
dc117daa 42#include <sys/stat.h>
c895fd00 43#include <sys/ioctl.h>
01618658 44#include <sys/inotify.h>
761dfddc 45#include <sys/utsname.h>
7fafc032
KS
46
47#include "udev.h"
392ef7a2 48#include "sd-daemon.h"
7fafc032 49
c3804728 50static bool debug;
9e8fe79b 51
80df994c 52void udev_main_log(struct udev *udev, int priority,
7d563a17
KS
53 const char *file, int line, const char *fn,
54 const char *format, va_list args)
55{
56 if (debug) {
820fc48f 57 char buf[1024];
29bbefe4 58 struct timespec ts;
820fc48f
KS
59
60 vsnprintf(buf, sizeof(buf), format, args);
29bbefe4 61 clock_gettime(CLOCK_MONOTONIC, &ts);
2dd7eed2 62 fprintf(stderr, "[%llu.%06u] [%u] %s: %s",
29bbefe4 63 (unsigned long long) ts.tv_sec, (unsigned int) ts.tv_nsec/1000,
820fc48f 64 (int) getpid(), fn, buf);
7d563a17
KS
65 } else {
66 vsyslog(priority, format, args);
67 }
68}
69
d7ddce18 70static struct udev_rules *rules;
f503f6b2 71static struct udev_queue_export *udev_queue_export;
d59f11e1 72static struct udev_ctrl *udev_ctrl;
1e03b754 73static struct udev_monitor *monitor;
3c6ee190 74static int worker_watch[2] = { -1, -1 };
ff2c503d
KS
75static int fd_signal = -1;
76static int fd_ep = -1;
77static int fd_inotify = -1;
c3804728 78static bool stop_exec_queue;
7c85d636 79static bool reload;
87d55ff6
KS
80static int children;
81static int children_max;
c830e98d 82static int exec_delay;
2181d30a 83static sigset_t sigmask_orig;
ff2c503d
KS
84static UDEV_LIST(event_list);
85static UDEV_LIST(worker_list);
c3804728 86static bool udev_exit;
1e03b754 87
1e03b754
KS
88enum event_state {
89 EVENT_UNDEF,
90 EVENT_QUEUED,
91 EVENT_RUNNING,
92};
93
94struct event {
95 struct udev_list_node node;
96 struct udev *udev;
97 struct udev_device *dev;
98 enum event_state state;
99 int exitcode;
100 unsigned long long int delaying_seqnum;
101 unsigned long long int seqnum;
102 const char *devpath;
103 size_t devpath_len;
104 const char *devpath_old;
19711e19
KS
105 dev_t devnum;
106 bool is_block;
fc416258 107 int ifindex;
1e03b754
KS
108};
109
110static struct event *node_to_event(struct udev_list_node *node)
7e027927
KS
111{
112 char *event;
113
114 event = (char *)node;
1e03b754
KS
115 event -= offsetof(struct event, node);
116 return (struct event *)event;
117}
118
ff2c503d
KS
119static void event_queue_cleanup(struct udev *udev, enum event_state type);
120
1e03b754
KS
121enum worker_state {
122 WORKER_UNDEF,
123 WORKER_RUNNING,
124 WORKER_IDLE,
125 WORKER_KILLED,
126};
127
128struct worker {
129 struct udev_list_node node;
bc113de9
KS
130 struct udev *udev;
131 int refcount;
1e03b754
KS
132 pid_t pid;
133 struct udev_monitor *monitor;
134 enum worker_state state;
135 struct event *event;
136};
137
138/* passed from worker to main process */
139struct worker_message {
140 pid_t pid;
141 int exitcode;
142};
143
144static struct worker *node_to_worker(struct udev_list_node *node)
145{
146 char *worker;
147
148 worker = (char *)node;
149 worker -= offsetof(struct worker, node);
150 return (struct worker *)worker;
7e027927
KS
151}
152
ff2c503d 153static void event_queue_delete(struct event *event, bool export)
fc465079 154{
7e027927 155 udev_list_node_remove(&event->node);
7a770250 156
ff2c503d 157 if (export) {
289a1821 158 udev_queue_export_device_finished(udev_queue_export, event->dev);
ff2c503d
KS
159 info(event->udev, "seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
160 }
aa8734ff 161 udev_device_unref(event->dev);
1e03b754 162 free(event);
aa8734ff 163}
7a770250 164
bc113de9
KS
165static struct worker *worker_ref(struct worker *worker)
166{
167 worker->refcount++;
168 return worker;
169}
170
ff2c503d
KS
171static void worker_cleanup(struct worker *worker)
172{
173 udev_list_node_remove(&worker->node);
174 udev_monitor_unref(worker->monitor);
175 children--;
176 free(worker);
177}
178
1e03b754
KS
179static void worker_unref(struct worker *worker)
180{
bc113de9
KS
181 worker->refcount--;
182 if (worker->refcount > 0)
183 return;
bc113de9 184 info(worker->udev, "worker [%u] cleaned up\n", worker->pid);
ff2c503d
KS
185 worker_cleanup(worker);
186}
187
188static void worker_list_cleanup(struct udev *udev)
189{
190 struct udev_list_node *loop, *tmp;
191
192 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
193 struct worker *worker = node_to_worker(loop);
194
195 worker_cleanup(worker);
196 }
fc465079
KS
197}
198
1e03b754 199static void worker_new(struct event *event)
7fafc032 200{
ff2c503d 201 struct udev *udev = event->udev;
1e03b754
KS
202 struct worker *worker;
203 struct udev_monitor *worker_monitor;
90c210eb 204 pid_t pid;
ce449f89 205
1e03b754 206 /* listen for new events */
ff2c503d 207 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
1e03b754
KS
208 if (worker_monitor == NULL)
209 return;
210 /* allow the main daemon netlink address to send devices to the worker */
211 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
212 udev_monitor_enable_receiving(worker_monitor);
213
214 worker = calloc(1, sizeof(struct worker));
1851332c
YK
215 if (worker == NULL) {
216 udev_monitor_unref(worker_monitor);
1e03b754 217 return;
1851332c 218 }
bc113de9
KS
219 /* worker + event reference */
220 worker->refcount = 2;
ff2c503d 221 worker->udev = udev;
0bc74ea7 222
90c210eb
KS
223 pid = fork();
224 switch (pid) {
1e03b754 225 case 0: {
82063a88
KS
226 struct udev_device *dev = NULL;
227 int fd_monitor;
228 struct epoll_event ep_signal, ep_monitor;
229 sigset_t mask;
230 int rc = EXIT_SUCCESS;
1e03b754 231
ff2c503d
KS
232 /* move initial device from queue */
233 dev = event->dev;
234 event->dev = NULL;
235
236 free(worker);
237 worker_list_cleanup(udev);
238 event_queue_cleanup(udev, EVENT_UNDEF);
f503f6b2 239 udev_queue_export_unref(udev_queue_export);
9290143d 240 udev_monitor_unref(monitor);
d59f11e1 241 udev_ctrl_unref(udev_ctrl);
ff2c503d
KS
242 close(fd_signal);
243 close(fd_ep);
1e03b754 244 close(worker_watch[READ_END]);
b437ec95 245
82063a88
KS
246 sigfillset(&mask);
247 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
248 if (fd_signal < 0) {
249 err(udev, "error creating signalfd %m\n");
250 rc = 2;
251 goto out;
252 }
253
254 fd_ep = epoll_create1(EPOLL_CLOEXEC);
255 if (fd_ep < 0) {
256 err(udev, "error creating epoll fd: %m\n");
257 rc = 3;
258 goto out;
259 }
260
261 memset(&ep_signal, 0, sizeof(struct epoll_event));
262 ep_signal.events = EPOLLIN;
263 ep_signal.data.fd = fd_signal;
264
265 fd_monitor = udev_monitor_get_fd(worker_monitor);
266 memset(&ep_monitor, 0, sizeof(struct epoll_event));
267 ep_monitor.events = EPOLLIN;
268 ep_monitor.data.fd = fd_monitor;
269
270 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
271 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
272 err(udev, "fail to add fds to epoll: %m\n");
273 rc = 4;
274 goto out;
275 }
aa8734ff 276
1e03b754
KS
277 /* request TERM signal if parent exits */
278 prctl(PR_SET_PDEATHSIG, SIGTERM);
aa8734ff 279
82063a88 280 for (;;) {
1e03b754 281 struct udev_event *udev_event;
2181d30a 282 struct worker_message msg;
2181d30a 283 int err;
aa8734ff 284
ff2c503d 285 info(udev, "seq %llu running\n", udev_device_get_seqnum(dev));
1e03b754 286 udev_event = udev_event_new(dev);
82063a88
KS
287 if (udev_event == NULL) {
288 rc = 5;
289 goto out;
290 }
0bc74ea7 291
2181d30a
KS
292 /* needed for SIGCHLD/SIGTERM in spawn() */
293 udev_event->fd_signal = fd_signal;
1e03b754 294
c830e98d
KS
295 if (exec_delay > 0)
296 udev_event->exec_delay = exec_delay;
297
1e03b754 298 /* apply rules, create node, symlinks */
2181d30a 299 err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
1e03b754 300
f46d2e54 301 if (err == 0)
289a1821 302 udev_event_execute_run(udev_event, &sigmask_orig);
1e03b754
KS
303
304 /* apply/restore inotify watch */
305 if (err == 0 && udev_event->inotify_watch) {
ff2c503d 306 udev_watch_begin(udev, dev);
1e03b754
KS
307 udev_device_update_db(dev);
308 }
5ae82640 309
1e03b754
KS
310 /* send processed event back to libudev listeners */
311 udev_monitor_send_device(worker_monitor, NULL, dev);
11625409 312
f46d2e54 313 /* send udevd the result of the event execution */
2181d30a 314 memset(&msg, 0, sizeof(struct worker_message));
f7c5b04f
KS
315 if (err != 0)
316 msg.exitcode = err;
1e03b754
KS
317 msg.pid = getpid();
318 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
319
ff2c503d 320 info(udev, "seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
2181d30a 321
adda4c68
KS
322 udev_device_unref(dev);
323 dev = NULL;
324
2181d30a
KS
325 if (udev_event->sigterm) {
326 udev_event_unref(udev_event);
327 goto out;
328 }
329
330 udev_event_unref(udev_event);
331
82063a88
KS
332 /* wait for more device messages from main udevd, or term signal */
333 while (dev == NULL) {
334 struct epoll_event ev[4];
adda4c68 335 int fdcount;
82063a88 336 int i;
adda4c68 337
82063a88 338 fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
2181d30a
KS
339 if (fdcount < 0) {
340 if (errno == EINTR)
341 continue;
342 err = -errno;
343 err(udev, "failed to poll: %m\n");
344 goto out;
345 }
adda4c68 346
82063a88
KS
347 for (i = 0; i < fdcount; i++) {
348 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
349 dev = udev_monitor_receive_device(worker_monitor);
7944a13a 350 break;
82063a88
KS
351 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
352 struct signalfd_siginfo fdsi;
353 ssize_t size;
354
355 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
356 if (size != sizeof(struct signalfd_siginfo))
357 continue;
358 switch (fdsi.ssi_signo) {
359 case SIGTERM:
360 goto out;
82063a88
KS
361 }
362 }
adda4c68
KS
363 }
364 }
82063a88
KS
365 }
366out:
367 udev_device_unref(dev);
368 if (fd_signal >= 0)
369 close(fd_signal);
370 if (fd_ep >= 0)
371 close(fd_ep);
ff2c503d
KS
372 close(fd_inotify);
373 close(worker_watch[WRITE_END]);
374 udev_rules_unref(rules);
1e03b754 375 udev_monitor_unref(worker_monitor);
ff2c503d 376 udev_unref(udev);
9060b066 377 udev_log_close();
82063a88 378 exit(rc);
1e03b754 379 }
90c210eb 380 case -1:
1e03b754
KS
381 udev_monitor_unref(worker_monitor);
382 event->state = EVENT_QUEUED;
383 free(worker);
ff2c503d 384 err(udev, "fork of child failed: %m\n");
2f6cbd19 385 break;
90c210eb 386 default:
1e03b754
KS
387 /* close monitor, but keep address around */
388 udev_monitor_disconnect(worker_monitor);
389 worker->monitor = worker_monitor;
390 worker->pid = pid;
391 worker->state = WORKER_RUNNING;
392 worker->event = event;
393 event->state = EVENT_RUNNING;
394 udev_list_node_append(&worker->node, &worker_list);
87d55ff6 395 children++;
ff2c503d 396 info(udev, "seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
1e03b754 397 break;
90c210eb 398 }
7fafc032
KS
399}
400
665ee17d 401static void event_run(struct event *event, bool force)
fc465079 402{
1e03b754
KS
403 struct udev_list_node *loop;
404
405 udev_list_node_foreach(loop, &worker_list) {
406 struct worker *worker = node_to_worker(loop);
407 ssize_t count;
7baada47 408
1e03b754
KS
409 if (worker->state != WORKER_IDLE)
410 continue;
0f624f16 411
1e03b754
KS
412 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
413 if (count < 0) {
a073cfa8 414 err(event->udev, "worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
1e03b754 415 kill(worker->pid, SIGKILL);
bc113de9 416 worker->state = WORKER_KILLED;
1e03b754
KS
417 continue;
418 }
bc113de9
KS
419 worker_ref(worker);
420 worker->event = event;
421 worker->state = WORKER_RUNNING;
422 event->state = EVENT_RUNNING;
1e03b754
KS
423 return;
424 }
425
87d55ff6 426 if (!force && children >= children_max) {
c830e98d
KS
427 if (children_max > 1)
428 info(event->udev, "maximum number (%i) of children reached\n", children);
1e03b754
KS
429 return;
430 }
431
432 /* start new worker and pass initial device */
433 worker_new(event);
434}
435
40929a02 436static int event_queue_insert(struct udev_device *dev)
1e03b754
KS
437{
438 struct event *event;
439
440 event = calloc(1, sizeof(struct event));
441 if (event == NULL)
40929a02 442 return -1;
1e03b754
KS
443
444 event->udev = udev_device_get_udev(dev);
445 event->dev = dev;
446 event->seqnum = udev_device_get_seqnum(dev);
447 event->devpath = udev_device_get_devpath(dev);
448 event->devpath_len = strlen(event->devpath);
449 event->devpath_old = udev_device_get_devpath_old(dev);
19711e19
KS
450 event->devnum = udev_device_get_devnum(dev);
451 event->is_block = (strcmp("block", udev_device_get_subsystem(dev)) == 0);
fc416258 452 event->ifindex = udev_device_get_ifindex(dev);
1e03b754
KS
453
454 udev_queue_export_device_queued(udev_queue_export, dev);
455 info(event->udev, "seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
456 udev_device_get_action(dev), udev_device_get_subsystem(dev));
457
458 event->state = EVENT_QUEUED;
0bc74ea7 459 udev_list_node_append(&event->node, &event_list);
c7c00276 460
fc465079 461 /* run all events with a timeout set immediately */
1e03b754 462 if (udev_device_get_timeout(dev) > 0) {
665ee17d 463 event_run(event, true);
40929a02 464 return 0;
fc465079 465 }
40929a02
YK
466
467 return 0;
fc465079
KS
468}
469
adda4c68 470static void worker_kill(struct udev *udev, int retain)
1e03b754
KS
471{
472 struct udev_list_node *loop;
473 int max;
474
87d55ff6 475 if (children <= retain)
1e03b754
KS
476 return;
477
87d55ff6 478 max = children - retain;
1e03b754
KS
479
480 udev_list_node_foreach(loop, &worker_list) {
481 struct worker *worker = node_to_worker(loop);
482
483 if (max-- <= 0)
484 break;
485
486 if (worker->state == WORKER_KILLED)
487 continue;
488
489 worker->state = WORKER_KILLED;
490 kill(worker->pid, SIGTERM);
491 }
492}
493
e3196993 494/* lookup event for identical, parent, child device */
19711e19 495static bool is_devpath_busy(struct event *event)
7fafc032 496{
7e027927 497 struct udev_list_node *loop;
1e03b754 498 size_t common;
7b6571a9 499
0bc74ea7
KS
500 /* check if queue contains events we depend on */
501 udev_list_node_foreach(loop, &event_list) {
1e03b754 502 struct event *loop_event = node_to_event(loop);
7e027927 503
0bc74ea7 504 /* we already found a later event, earlier can not block us, no need to check again */
1e03b754 505 if (loop_event->seqnum < event->delaying_seqnum)
0bc74ea7
KS
506 continue;
507
508 /* event we checked earlier still exists, no need to check again */
1e03b754 509 if (loop_event->seqnum == event->delaying_seqnum)
19711e19 510 return true;
0bc74ea7
KS
511
512 /* found ourself, no later event can block us */
1e03b754 513 if (loop_event->seqnum >= event->seqnum)
fc630eda
KS
514 break;
515
19711e19
KS
516 /* check major/minor */
517 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
518 return true;
519
fc416258
KS
520 /* check network device ifindex */
521 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
522 return true;
523
a2f2270e 524 /* check our old name */
19711e19
KS
525 if (event->devpath_old != NULL && strcmp(loop_event->devpath, event->devpath_old) == 0) {
526 event->delaying_seqnum = loop_event->seqnum;
527 return true;
528 }
a2f2270e 529
1e03b754
KS
530 /* compare devpath */
531 common = MIN(loop_event->devpath_len, event->devpath_len);
532
533 /* one devpath is contained in the other? */
534 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
535 continue;
536
537 /* identical device event found */
538 if (loop_event->devpath_len == event->devpath_len) {
fc416258
KS
539 /* devices names might have changed/swapped in the meantime */
540 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
541 continue;
542 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
543 continue;
1e03b754 544 event->delaying_seqnum = loop_event->seqnum;
19711e19 545 return true;
c3b145a3 546 }
1e03b754
KS
547
548 /* parent device event found */
549 if (event->devpath[common] == '/') {
550 event->delaying_seqnum = loop_event->seqnum;
19711e19 551 return true;
1e03b754
KS
552 }
553
554 /* child device event found */
555 if (loop_event->devpath[common] == '/') {
556 event->delaying_seqnum = loop_event->seqnum;
19711e19 557 return true;
1e03b754
KS
558 }
559
560 /* no matching device */
561 continue;
80513ea3 562 }
1e03b754 563
19711e19 564 return false;
7fafc032
KS
565}
566
ff2c503d 567static void event_queue_start(struct udev *udev)
7fafc032 568{
7e027927 569 struct udev_list_node *loop;
8ab44e3f 570
1e03b754
KS
571 udev_list_node_foreach(loop, &event_list) {
572 struct event *event = node_to_event(loop);
0bc74ea7 573
1e03b754 574 if (event->state != EVENT_QUEUED)
0bc74ea7
KS
575 continue;
576
577 /* do not start event if parent or child event is still running */
19711e19 578 if (is_devpath_busy(event)) {
1e03b754 579 dbg(udev, "delay seq %llu (%s)\n", event->seqnum, event->devpath);
fc465079
KS
580 continue;
581 }
582
665ee17d 583 event_run(event, false);
1e03b754
KS
584 }
585}
586
ff2c503d
KS
587static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
588{
589 struct udev_list_node *loop, *tmp;
590
591 udev_list_node_foreach_safe(loop, tmp, &event_list) {
592 struct event *event = node_to_event(loop);
593
594 if (match_type != EVENT_UNDEF && match_type != event->state)
595 continue;
596
597 event_queue_delete(event, false);
598 }
599}
600
601static void worker_returned(int fd_worker)
1e03b754 602{
88cbfb09 603 for (;;) {
1e03b754
KS
604 struct worker_message msg;
605 ssize_t size;
606 struct udev_list_node *loop;
607
ff2c503d 608 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
1e03b754
KS
609 if (size != sizeof(struct worker_message))
610 break;
611
612 /* lookup worker who sent the signal */
613 udev_list_node_foreach(loop, &worker_list) {
614 struct worker *worker = node_to_worker(loop);
d1cc6562 615
1e03b754
KS
616 if (worker->pid != msg.pid)
617 continue;
618
619 /* worker returned */
620 worker->event->exitcode = msg.exitcode;
ff2c503d 621 event_queue_delete(worker->event, true);
1e03b754 622 worker->event = NULL;
adda4c68
KS
623 if (worker->state != WORKER_KILLED)
624 worker->state = WORKER_IDLE;
bc113de9 625 worker_unref(worker);
1e03b754 626 break;
d1cc6562 627 }
e825b59b 628 }
88f4b648
KS
629}
630
3b47c739 631/* receive the udevd message from userspace */
ff2c503d 632static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
7fafc032 633{
d59f11e1 634 struct udev *udev = udev_ctrl_get_udev(uctrl);
ff2c503d
KS
635 struct udev_ctrl_connection *ctrl_conn;
636 struct udev_ctrl_msg *ctrl_msg = NULL;
d59f11e1
KS
637 const char *str;
638 int i;
7b1cbec9 639
ff2c503d
KS
640 ctrl_conn = udev_ctrl_get_connection(uctrl);
641 if (ctrl_conn == NULL)
642 goto out;
643
644 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
d59f11e1 645 if (ctrl_msg == NULL)
ff2c503d 646 goto out;
4a231017 647
d59f11e1
KS
648 i = udev_ctrl_get_set_log_level(ctrl_msg);
649 if (i >= 0) {
650 info(udev, "udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
651 udev_set_log_priority(udev, i);
adda4c68 652 worker_kill(udev, 0);
0028653c
KS
653 }
654
d59f11e1 655 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
7d563a17 656 info(udev, "udevd message (STOP_EXEC_QUEUE) received\n");
c3804728 657 stop_exec_queue = true;
d59f11e1
KS
658 }
659
660 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
7d563a17 661 info(udev, "udevd message (START_EXEC_QUEUE) received\n");
c3804728 662 stop_exec_queue = false;
d59f11e1
KS
663 }
664
7c85d636
KS
665 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
666 info(udev, "udevd message (RELOAD) received\n");
667 reload = true;
3b47c739 668 }
d59f11e1
KS
669
670 str = udev_ctrl_get_set_env(ctrl_msg);
671 if (str != NULL) {
aa8734ff
KS
672 char *key;
673
674 key = strdup(str);
675 if (key != NULL) {
676 char *val;
677
678 val = strchr(key, '=');
679 if (val != NULL) {
680 val[0] = '\0';
681 val = &val[1];
682 if (val[0] == '\0') {
683 info(udev, "udevd message (ENV) received, unset '%s'\n", key);
684 udev_add_property(udev, key, NULL);
685 } else {
686 info(udev, "udevd message (ENV) received, set '%s=%s'\n", key, val);
687 udev_add_property(udev, key, val);
688 }
d59f11e1 689 } else {
aa8734ff 690 err(udev, "wrong key format '%s'\n", key);
d59f11e1 691 }
aa8734ff 692 free(key);
d59f11e1 693 }
adda4c68 694 worker_kill(udev, 0);
d59f11e1
KS
695 }
696
87d55ff6 697 i = udev_ctrl_get_set_children_max(ctrl_msg);
d59f11e1 698 if (i >= 0) {
87d55ff6
KS
699 info(udev, "udevd message (SET_MAX_CHILDREN) received, children_max=%i\n", i);
700 children_max = i;
d59f11e1 701 }
bb38678e 702
ff2c503d
KS
703 if (udev_ctrl_get_ping(ctrl_msg) > 0)
704 info(udev, "udevd message (SYNC) received\n");
705
706 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
707 info(udev, "udevd message (EXIT) received\n");
708 udev_exit = true;
709 /* keep reference to block the client until we exit */
710 udev_ctrl_connection_ref(ctrl_conn);
bb38678e 711 }
ff2c503d 712out:
d59f11e1 713 udev_ctrl_msg_unref(ctrl_msg);
ff2c503d 714 return udev_ctrl_connection_unref(ctrl_conn);
88f4b648 715}
4a231017 716
bd284db1
SJR
717/* read inotify messages */
718static int handle_inotify(struct udev *udev)
719{
4daa146b 720 int nbytes, pos;
bd284db1
SJR
721 char *buf;
722 struct inotify_event *ev;
bd284db1 723
ff2c503d 724 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
bd284db1
SJR
725 return 0;
726
727 buf = malloc(nbytes);
728 if (buf == NULL) {
45798927 729 err(udev, "error getting buffer for inotify\n");
1e03b754 730 return -1;
bd284db1
SJR
731 }
732
ff2c503d 733 nbytes = read(fd_inotify, buf, nbytes);
bd284db1 734
80be8c48 735 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
047f88bc 736 struct udev_device *dev;
bd284db1 737
80be8c48 738 ev = (struct inotify_event *)(buf + pos);
047f88bc
SJR
739 dev = udev_watch_lookup(udev, ev->wd);
740 if (dev != NULL) {
79e1912b 741 info(udev, "inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
bd284db1
SJR
742 if (ev->mask & IN_CLOSE_WRITE) {
743 char filename[UTIL_PATH_SIZE];
744 int fd;
745
047f88bc 746 info(udev, "device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
065db052 747 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
bd284db1 748 fd = open(filename, O_WRONLY);
e48e2912
KS
749 if (fd >= 0) {
750 if (write(fd, "change", 6) < 0)
751 info(udev, "error writing uevent: %m\n");
752 close(fd);
753 }
bd284db1
SJR
754 }
755 if (ev->mask & IN_IGNORED)
047f88bc
SJR
756 udev_watch_end(udev, dev);
757
758 udev_device_unref(dev);
bd284db1 759 }
b8e96d67 760
bd284db1
SJR
761 }
762
1e03b754 763 free(buf);
4aca304e 764 return 0;
bd284db1
SJR
765}
766
45798927 767static void handle_signal(struct udev *udev, int signo)
7fafc032 768{
1e03b754
KS
769 switch (signo) {
770 case SIGINT:
771 case SIGTERM:
c3804728 772 udev_exit = true;
1e03b754
KS
773 break;
774 case SIGCHLD:
88cbfb09 775 for (;;) {
1e03b754 776 pid_t pid;
45798927 777 int status;
1e03b754 778 struct udev_list_node *loop, *tmp;
5a73b25f 779
45798927 780 pid = waitpid(-1, &status, WNOHANG);
1e03b754
KS
781 if (pid <= 0)
782 break;
7fafc032 783
1e03b754
KS
784 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
785 struct worker *worker = node_to_worker(loop);
7e027927 786
1e03b754
KS
787 if (worker->pid != pid)
788 continue;
bc113de9 789 info(udev, "worker [%u] exit\n", pid);
b466e9ab 790
a95f0385
KS
791 if (WIFEXITED(status)) {
792 if (WEXITSTATUS(status) != 0)
793 err(udev, "worker [%u] exit with return code %i\n", pid, WEXITSTATUS(status));
794 } else if (WIFSIGNALED(status)) {
795 err(udev, "worker [%u] terminated by signal %i (%s)\n",
796 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
797 } else if (WIFSTOPPED(status)) {
798 err(udev, "worker [%u] stopped\n", pid);
799 } else if (WIFCONTINUED(status)) {
800 err(udev, "worker [%u] continued\n", pid);
801 } else {
802 err(udev, "worker [%u] exit with status 0x%04x\n", pid, status);
803 }
804
805 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
bc113de9 806 if (worker->event != NULL) {
a95f0385
KS
807 err(udev, "worker [%u] failed while handling '%s'\n",
808 pid, worker->event->devpath);
bc113de9 809 worker->event->exitcode = -32;
ff2c503d 810 event_queue_delete(worker->event, true);
a95f0385 811 /* drop reference taken for state 'running' */
bc113de9
KS
812 worker_unref(worker);
813 }
1e03b754 814 }
1e03b754 815 worker_unref(worker);
1e03b754
KS
816 break;
817 }
818 }
819 break;
820 case SIGHUP:
7c85d636 821 reload = true;
1e03b754 822 break;
f27125f9 823 }
824}
825
761dfddc
KS
826static void static_dev_create_from_modules(struct udev *udev)
827{
828 struct utsname kernel;
829 char modules[UTIL_PATH_SIZE];
830 char buf[4096];
831 FILE *f;
832
833 uname(&kernel);
834 util_strscpyl(modules, sizeof(modules), "/lib/modules/", kernel.release, "/modules.devname", NULL);
835 f = fopen(modules, "r");
836 if (f == NULL)
837 return;
838
839 while (fgets(buf, sizeof(buf), f) != NULL) {
840 char *s;
841 const char *modname;
842 const char *devname;
843 const char *devno;
844 int maj, min;
845 char type;
846 mode_t mode;
847 char filename[UTIL_PATH_SIZE];
848
849 if (buf[0] == '#')
850 continue;
851
852 modname = buf;
853 s = strchr(modname, ' ');
854 if (s == NULL)
855 continue;
856 s[0] = '\0';
857
858 devname = &s[1];
859 s = strchr(devname, ' ');
860 if (s == NULL)
861 continue;
862 s[0] = '\0';
863
864 devno = &s[1];
865 s = strchr(devno, ' ');
866 if (s == NULL)
867 s = strchr(devno, '\n');
868 if (s != NULL)
869 s[0] = '\0';
870 if (sscanf(devno, "%c%u:%u", &type, &maj, &min) != 3)
871 continue;
872
79449642 873 /* set sticky bit, so we do not remove the node on module unload */
761dfddc 874 if (type == 'c')
79449642 875 mode = 01600|S_IFCHR;
761dfddc 876 else if (type == 'b')
79449642 877 mode = 01600|S_IFBLK;
761dfddc
KS
878 else
879 continue;
880
881 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/", devname, NULL);
51f43b53 882 util_create_path_selinux(udev, filename);
761dfddc
KS
883 udev_selinux_setfscreatecon(udev, filename, mode);
884 info(udev, "mknod '%s' %c%u:%u\n", filename, type, maj, min);
885 if (mknod(filename, mode, makedev(maj, min)) < 0 && errno == EEXIST)
886 utimensat(AT_FDCWD, filename, NULL, 0);
887 udev_selinux_resetfscreatecon(udev);
888 }
889
890 fclose(f);
891}
892
51f43b53 893static int copy_dev_dir(struct udev *udev, DIR *dir_from, DIR *dir_to, int maxdepth)
cb9a0eee
KS
894{
895 struct dirent *dent;
896
897 for (dent = readdir(dir_from); dent != NULL; dent = readdir(dir_from)) {
898 struct stat stats;
899
900 if (dent->d_name[0] == '.')
901 continue;
902 if (fstatat(dirfd(dir_from), dent->d_name, &stats, AT_SYMLINK_NOFOLLOW) != 0)
903 continue;
904
905 if (S_ISBLK(stats.st_mode) || S_ISCHR(stats.st_mode)) {
906 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, stats.st_mode & 0777);
907 if (mknodat(dirfd(dir_to), dent->d_name, stats.st_mode, stats.st_rdev) == 0) {
908 fchmodat(dirfd(dir_to), dent->d_name, stats.st_mode & 0777, 0);
909 fchownat(dirfd(dir_to), dent->d_name, stats.st_uid, stats.st_gid, 0);
910 } else {
911 utimensat(dirfd(dir_to), dent->d_name, NULL, 0);
912 }
913 udev_selinux_resetfscreatecon(udev);
914 } else if (S_ISLNK(stats.st_mode)) {
915 char target[UTIL_PATH_SIZE];
916 ssize_t len;
917
918 len = readlinkat(dirfd(dir_from), dent->d_name, target, sizeof(target));
919 if (len <= 0 || len == (ssize_t)sizeof(target))
920 continue;
921 target[len] = '\0';
922 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, S_IFLNK);
923 if (symlinkat(target, dirfd(dir_to), dent->d_name) < 0 && errno == EEXIST)
924 utimensat(dirfd(dir_to), dent->d_name, NULL, AT_SYMLINK_NOFOLLOW);
925 udev_selinux_resetfscreatecon(udev);
926 } else if (S_ISDIR(stats.st_mode)) {
927 DIR *dir2_from, *dir2_to;
928
929 if (maxdepth == 0)
930 continue;
931
932 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, S_IFDIR|0755);
933 mkdirat(dirfd(dir_to), dent->d_name, 0755);
934 udev_selinux_resetfscreatecon(udev);
935
936 dir2_to = fdopendir(openat(dirfd(dir_to), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
937 if (dir2_to == NULL)
938 continue;
939
940 dir2_from = fdopendir(openat(dirfd(dir_from), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
941 if (dir2_from == NULL) {
942 closedir(dir2_to);
943 continue;
944 }
945
51f43b53 946 copy_dev_dir(udev, dir2_from, dir2_to, maxdepth-1);
cb9a0eee
KS
947
948 closedir(dir2_to);
949 closedir(dir2_from);
950 }
951 }
952
953 return 0;
954}
955
761dfddc 956static void static_dev_create_links(struct udev *udev, DIR *dir)
cb9a0eee
KS
957{
958 struct stdlinks {
959 const char *link;
960 const char *target;
961 };
962 static const struct stdlinks stdlinks[] = {
963 { "core", "/proc/kcore" },
4bfa5cf5 964 { "fd", "/proc/self/fd" },
cb9a0eee
KS
965 { "stdin", "/proc/self/fd/0" },
966 { "stdout", "/proc/self/fd/1" },
967 { "stderr", "/proc/self/fd/2" },
968 };
969 unsigned int i;
cb9a0eee 970
cb9a0eee 971 for (i = 0; i < ARRAY_SIZE(stdlinks); i++) {
08f11597
YK
972 struct stat sb;
973
974 if (stat(stdlinks[i].target, &sb) == 0) {
975 udev_selinux_setfscreateconat(udev, dirfd(dir), stdlinks[i].link, S_IFLNK);
976 if (symlinkat(stdlinks[i].target, dirfd(dir), stdlinks[i].link) < 0 && errno == EEXIST)
977 utimensat(dirfd(dir), stdlinks[i].link, NULL, AT_SYMLINK_NOFOLLOW);
978 udev_selinux_resetfscreatecon(udev);
979 }
cb9a0eee 980 }
761dfddc
KS
981}
982
983static void static_dev_create_from_devices(struct udev *udev, DIR *dir)
984{
985 DIR *dir_from;
cb9a0eee 986
cb9a0eee 987 dir_from = opendir(LIBEXECDIR "/devices");
761dfddc
KS
988 if (dir_from == NULL)
989 return;
51f43b53 990 copy_dev_dir(udev, dir_from, dir, 8);
761dfddc
KS
991 closedir(dir_from);
992}
993
994static void static_dev_create(struct udev *udev)
995{
996 DIR *dir;
cb9a0eee 997
761dfddc
KS
998 dir = opendir(udev_get_dev_path(udev));
999 if (dir == NULL)
1000 return;
1001
1002 static_dev_create_links(udev, dir);
1003 static_dev_create_from_devices(udev, dir);
1004
1005 closedir(dir);
cb9a0eee
KS
1006}
1007
1008static int mem_size_mb(void)
1009{
1010 FILE *f;
1011 char buf[4096];
1012 long int memsize = -1;
1013
1014 f = fopen("/proc/meminfo", "r");
1015 if (f == NULL)
1016 return -1;
1017
1018 while (fgets(buf, sizeof(buf), f) != NULL) {
1019 long int value;
1020
1021 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
1022 memsize = value / 1024;
1023 break;
1024 }
1025 }
1026
1027 fclose(f);
1028 return memsize;
1029}
1030
5f59fa09
KS
1031static int convert_db(struct udev *udev)
1032{
1033 char filename[UTIL_PATH_SIZE];
1034 FILE *f;
1035 struct udev_enumerate *udev_enumerate;
1036 struct udev_list_entry *list_entry;
1037
1038 /* current database */
4ec9c3e7 1039 util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data", NULL);
5f59fa09
KS
1040 if (access(filename, F_OK) >= 0)
1041 return 0;
1042
1043 /* make sure we do not get here again */
5f59fa09 1044 util_create_path(udev, filename);
4ec9c3e7 1045 mkdir(filename, 0755);
5f59fa09
KS
1046
1047 /* old database */
1048 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/db", NULL);
1049 if (access(filename, F_OK) < 0)
1050 return 0;
1051
1052 f = fopen("/dev/kmsg", "w");
1053 if (f != NULL) {
dff107dc 1054 fprintf(f, "<30>udevd[%u]: converting old udev database\n", getpid());
5f59fa09
KS
1055 fclose(f);
1056 }
1057
1058 udev_enumerate = udev_enumerate_new(udev);
1059 if (udev_enumerate == NULL)
1060 return -1;
1061 udev_enumerate_scan_devices(udev_enumerate);
1062 udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
1063 struct udev_device *device;
1064
1065 device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
1066 if (device == NULL)
1067 continue;
1068
1069 /* try to find the old database for devices without a current one */
1070 if (udev_device_read_db(device, NULL) < 0) {
1071 bool have_db;
1072 const char *id;
1073 struct stat stats;
1074 char devpath[UTIL_PATH_SIZE];
1075 char from[UTIL_PATH_SIZE];
1076
1077 have_db = false;
1078
1079 /* find database in old location */
1080 id = udev_device_get_id_filename(device);
1081 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev), "/.udev/db/", id, NULL);
1082 if (lstat(from, &stats) == 0) {
1083 if (!have_db) {
1084 udev_device_read_db(device, from);
1085 have_db = true;
1086 }
1087 unlink(from);
1088 }
1089
1090 /* find old database with $subsys:$sysname name */
1091 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev),
1092 "/.udev/db/", udev_device_get_subsystem(device), ":",
1093 udev_device_get_sysname(device), NULL);
1094 if (lstat(from, &stats) == 0) {
1095 if (!have_db) {
1096 udev_device_read_db(device, from);
1097 have_db = true;
1098 }
1099 unlink(from);
1100 }
1101
1102 /* find old database with the encoded devpath name */
1103 util_path_encode(udev_device_get_devpath(device), devpath, sizeof(devpath));
4ec9c3e7 1104 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev), "/.udev/db/", devpath, NULL);
5f59fa09
KS
1105 if (lstat(from, &stats) == 0) {
1106 if (!have_db) {
1107 udev_device_read_db(device, from);
1108 have_db = true;
1109 }
1110 unlink(from);
1111 }
1112
1113 /* write out new database */
1114 if (have_db)
1115 udev_device_update_db(device);
1116 }
1117 udev_device_unref(device);
1118 }
1119 udev_enumerate_unref(udev_enumerate);
1120 return 0;
1121}
1122
7459bcdc
KS
1123static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
1124{
1125 int ctrl = -1, netlink = -1;
1126 int fd, n;
1127
1128 n = sd_listen_fds(true);
1129 if (n <= 0)
1130 return -1;
1131
1132 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
1133 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
1134 if (ctrl >= 0)
1135 return -1;
1136 ctrl = fd;
1137 continue;
1138 }
1139
1140 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
1141 if (netlink >= 0)
1142 return -1;
1143 netlink = fd;
1144 continue;
1145 }
1146
1147 return -1;
1148 }
1149
1150 if (ctrl < 0 || netlink < 0)
1151 return -1;
1152
1153 info(udev, "ctrl=%i netlink=%i\n", ctrl, netlink);
1154 *rctrl = ctrl;
1155 *rnetlink = netlink;
1156 return 0;
1157}
1158
4f1795cc
KS
1159static bool check_rules_timestamp(struct udev *udev)
1160{
1161 char **p;
1162 unsigned long long *stamp_usec;
1163 int i, n;
1164 bool changed = false;
1165
1166 n = udev_get_rules_path(udev, &p, &stamp_usec);
1167 for (i = 0; i < n; i++) {
1168 struct stat stats;
1169
1170 if (stat(p[i], &stats) < 0)
1171 continue;
1172
1173 if (stamp_usec[i] == ts_usec(&stats.st_mtim))
1174 continue;
1175
1176 /* first check */
1177 if (stamp_usec[i] != 0) {
1178 info(udev, "reload - timestamp of '%s' changed\n", p[i]);
1179 changed = true;
1180 }
1181
1182 /* update timestamp */
1183 stamp_usec[i] = ts_usec(&stats.st_mtim);
1184 }
1185
1186 return changed;
1187}
1188
59345311 1189int main(int argc, char *argv[])
c2cf4012 1190{
7d563a17 1191 struct udev *udev;
3c189886 1192 FILE *f;
1e03b754 1193 sigset_t mask;
c3804728 1194 int daemonize = false;
5f03ed8a 1195 int resolve_names = 1;
b52a01ee 1196 static const struct option options[] = {
033e9f8c 1197 { "daemon", no_argument, NULL, 'd' },
033e9f8c 1198 { "debug", no_argument, NULL, 'D' },
337d1027 1199 { "children-max", required_argument, NULL, 'c' },
c830e98d 1200 { "exec-delay", required_argument, NULL, 'e' },
337d1027 1201 { "resolve-names", required_argument, NULL, 'N' },
033e9f8c
KS
1202 { "help", no_argument, NULL, 'h' },
1203 { "version", no_argument, NULL, 'V' },
b52a01ee
KS
1204 {}
1205 };
ff2c503d
KS
1206 int fd_ctrl = -1;
1207 int fd_netlink = -1;
1208 int fd_worker = -1;
1209 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1210 struct udev_ctrl_connection *ctrl_conn = NULL;
4f1795cc 1211 char **s;
e3396a2d 1212 int rc = 1;
53921bfa 1213
7d563a17
KS
1214 udev = udev_new();
1215 if (udev == NULL)
1216 goto exit;
1217
9060b066 1218 udev_log_init("udevd");
80df994c 1219 udev_set_log_fn(udev, udev_main_log);
aa8734ff 1220 info(udev, "version %s\n", VERSION);
c3b1fa66 1221 udev_selinux_init(udev);
95a6f4c8 1222
88cbfb09 1223 for (;;) {
7d563a17
KS
1224 int option;
1225
6ee9b2cb 1226 option = getopt_long(argc, argv, "c:deDtN:hV", options, NULL);
b52a01ee
KS
1227 if (option == -1)
1228 break;
1229
1230 switch (option) {
1231 case 'd':
c3804728 1232 daemonize = true;
b52a01ee 1233 break;
337d1027 1234 case 'c':
c830e98d
KS
1235 children_max = strtoul(optarg, NULL, 0);
1236 break;
1237 case 'e':
1238 exec_delay = strtoul(optarg, NULL, 0);
c7c00276 1239 break;
c70560fe 1240 case 'D':
c3804728 1241 debug = true;
7d563a17
KS
1242 if (udev_get_log_priority(udev) < LOG_INFO)
1243 udev_set_log_priority(udev, LOG_INFO);
9e8fe79b 1244 break;
5f03ed8a
SJR
1245 case 'N':
1246 if (strcmp (optarg, "early") == 0) {
1247 resolve_names = 1;
9032f119
SJR
1248 } else if (strcmp (optarg, "late") == 0) {
1249 resolve_names = 0;
5f03ed8a
SJR
1250 } else if (strcmp (optarg, "never") == 0) {
1251 resolve_names = -1;
1252 } else {
9032f119
SJR
1253 fprintf(stderr, "resolve-names must be early, late or never\n");
1254 err(udev, "resolve-names must be early, late or never\n");
5f03ed8a
SJR
1255 goto exit;
1256 }
1257 break;
b52a01ee 1258 case 'h':
c830e98d
KS
1259 printf("Usage: udevd OPTIONS\n"
1260 " --daemon\n"
1261 " --debug\n"
1262 " --children-max=<maximum number of workers>\n"
1263 " --exec-delay=<seconds to wait before executing RUN=>\n"
1264 " --resolve-names=early|late|never\n"
1265 " --version\n"
1266 " --help\n"
1267 "\n");
841e168c
MS
1268 goto exit;
1269 case 'V':
01618658 1270 printf("%s\n", VERSION);
e3396a2d 1271 goto exit;
b52a01ee
KS
1272 default:
1273 goto exit;
561d4c5a 1274 }
561d4c5a 1275 }
40caaeec 1276
c830e98d
KS
1277 /*
1278 * read the kernel commandline, in case we need to get into debug mode
1279 * udev.log-priority=<level> syslog priority
1280 * udev.children-max=<number of workers> events are fully serialized if set to 1
1281 *
1282 */
1283 f = fopen("/proc/cmdline", "r");
1284 if (f != NULL) {
1285 char cmdline[4096];
1286
1287 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
1288 char *pos;
1289
1290 pos = strstr(cmdline, "udev.log-priority=");
1291 if (pos != NULL) {
1292 pos += strlen("udev.log-priority=");
1293 udev_set_log_priority(udev, util_log_priority(pos));
1294 }
1295
1296 pos = strstr(cmdline, "udev.children-max=");
1297 if (pos != NULL) {
1298 pos += strlen("udev.children-max=");
1299 children_max = strtoul(pos, NULL, 0);
1300 }
1301
1302 pos = strstr(cmdline, "udev.exec-delay=");
1303 if (pos != NULL) {
1304 pos += strlen("udev.exec-delay=");
1305 exec_delay = strtoul(pos, NULL, 0);
1306 }
1307 }
1308 fclose(f);
1309 }
1310
1182b947
KS
1311 if (getuid() != 0) {
1312 fprintf(stderr, "root privileges required\n");
1313 err(udev, "root privileges required\n");
1314 goto exit;
1315 }
1316
1317 /* set umask before creating any file/directory */
1318 chdir("/");
1319 umask(022);
1320
1a6ab670
MS
1321 /* create standard links, copy static nodes, create nodes from modules */
1322 static_dev_create(udev);
1323 static_dev_create_from_modules(udev);
1324
1182b947 1325 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
8b463136
KS
1326 if (daemonize) {
1327 int fd;
1328
1329 fd = open("/dev/null", O_RDWR);
1330 if (fd >= 0) {
1331 if (write(STDOUT_FILENO, 0, 0) < 0)
1332 dup2(fd, STDOUT_FILENO);
1333 if (write(STDERR_FILENO, 0, 0) < 0)
1334 dup2(fd, STDERR_FILENO);
1335 if (fd > STDERR_FILENO)
1336 close(fd);
1337 } else {
1338 fprintf(stderr, "cannot open /dev/null\n");
1339 err(udev, "cannot open /dev/null\n");
1340 }
5edec024 1341 }
5edec024 1342
7459bcdc
KS
1343 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1344 /* get control and netlink socket from from systemd */
5cc4112e 1345 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
7459bcdc
KS
1346 if (udev_ctrl == NULL) {
1347 err(udev, "error taking over udev control socket");
1348 rc = 1;
1349 goto exit;
1350 }
1351
1352 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1353 if (monitor == NULL) {
1354 err(udev, "error taking over netlink socket\n");
1355 rc = 3;
1356 goto exit;
1357 }
1358 } else {
1359 /* open control and netlink socket */
5cc4112e 1360 udev_ctrl = udev_ctrl_new(udev);
7459bcdc
KS
1361 if (udev_ctrl == NULL) {
1362 fprintf(stderr, "error initializing udev control socket");
1363 err(udev, "error initializing udev control socket");
1364 rc = 1;
1365 goto exit;
1366 }
1367 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1368
1369 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1370 if (monitor == NULL) {
1371 fprintf(stderr, "error initializing netlink socket\n");
1372 err(udev, "error initializing netlink socket\n");
1373 rc = 3;
1374 goto exit;
1375 }
1376 fd_netlink = udev_monitor_get_fd(monitor);
1377 }
1378
1379 if (udev_monitor_enable_receiving(monitor) < 0) {
1380 fprintf(stderr, "error binding netlink socket\n");
1381 err(udev, "error binding netlink socket\n");
1382 rc = 3;
d59f11e1
KS
1383 goto exit;
1384 }
7459bcdc 1385
d59f11e1 1386 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
fc1de713
KS
1387 fprintf(stderr, "error binding udev control socket\n");
1388 err(udev, "error binding udev control socket\n");
d59f11e1 1389 rc = 1;
833b3c68
KS
1390 goto exit;
1391 }
1392
1e03b754 1393 udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
1e03b754 1394
2738ec2c
KS
1395 /* create queue file before signalling 'ready', to make sure we block 'settle' */
1396 udev_queue_export = udev_queue_export_new(udev);
1397 if (udev_queue_export == NULL) {
1398 err(udev, "error creating queue file\n");
1399 goto exit;
1400 }
1401
ff2c503d
KS
1402 if (daemonize) {
1403 pid_t pid;
8b463136 1404 int fd;
ff2c503d
KS
1405
1406 pid = fork();
1407 switch (pid) {
1408 case 0:
1409 break;
1410 case -1:
1411 err(udev, "fork of daemon failed: %m\n");
1412 rc = 4;
1413 goto exit;
1414 default:
2738ec2c 1415 rc = EXIT_SUCCESS;
1f5a5100 1416 goto exit_daemonize;
ff2c503d 1417 }
8b463136
KS
1418
1419 setsid();
1420
1421 fd = open("/proc/self/oom_score_adj", O_RDWR);
1422 if (fd < 0) {
1423 /* Fallback to old interface */
1424 fd = open("/proc/self/oom_adj", O_RDWR);
1425 if (fd < 0) {
1426 err(udev, "error disabling OOM: %m\n");
1427 } else {
1428 /* OOM_DISABLE == -17 */
1429 write(fd, "-17", 3);
1430 close(fd);
1431 }
1432 } else {
1433 write(fd, "-1000", 5);
1434 close(fd);
1435 }
ff2c503d
KS
1436 } else {
1437 sd_notify(1, "READY=1");
1438 }
1439
8b463136
KS
1440 f = fopen("/dev/kmsg", "w");
1441 if (f != NULL) {
dff107dc 1442 fprintf(f, "<30>udevd[%u]: starting version " VERSION "\n", getpid());
8b463136
KS
1443 fclose(f);
1444 }
1445
1446 if (!debug) {
1447 int fd;
1448
1449 fd = open("/dev/null", O_RDWR);
1450 if (fd >= 0) {
1451 dup2(fd, STDIN_FILENO);
1452 dup2(fd, STDOUT_FILENO);
1453 dup2(fd, STDERR_FILENO);
1454 close(fd);
1455 }
1456 }
1457
ff2c503d
KS
1458 fd_inotify = udev_watch_init(udev);
1459 if (fd_inotify < 0) {
1e03b754
KS
1460 fprintf(stderr, "error initializing inotify\n");
1461 err(udev, "error initializing inotify\n");
1462 rc = 4;
1463 goto exit;
1464 }
1e03b754
KS
1465 udev_watch_restore(udev);
1466
1467 /* block and listen to all signals on signalfd */
1468 sigfillset(&mask);
2181d30a 1469 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
82063a88 1470 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
ff2c503d 1471 if (fd_signal < 0) {
82063a88
KS
1472 fprintf(stderr, "error creating signalfd\n");
1473 err(udev, "error creating signalfd\n");
1e03b754
KS
1474 rc = 5;
1475 goto exit;
1476 }
1477
1478 /* unnamed socket from workers to the main daemon */
26347a4c 1479 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
82063a88
KS
1480 fprintf(stderr, "error creating socketpair\n");
1481 err(udev, "error creating socketpair\n");
1e03b754
KS
1482 rc = 6;
1483 goto exit;
1484 }
ff2c503d 1485 fd_worker = worker_watch[READ_END];
833b3c68 1486
779f4de1 1487 udev_builtin_init(udev);
aa29418a 1488
5f03ed8a 1489 rules = udev_rules_new(udev, resolve_names);
d7ddce18
KS
1490 if (rules == NULL) {
1491 err(udev, "error reading rules\n");
1492 goto exit;
1493 }
1e03b754 1494
ff2c503d
KS
1495 memset(&ep_ctrl, 0, sizeof(struct epoll_event));
1496 ep_ctrl.events = EPOLLIN;
1497 ep_ctrl.data.fd = fd_ctrl;
7459bcdc 1498
ff2c503d
KS
1499 memset(&ep_inotify, 0, sizeof(struct epoll_event));
1500 ep_inotify.events = EPOLLIN;
1501 ep_inotify.data.fd = fd_inotify;
7459bcdc 1502
ff2c503d
KS
1503 memset(&ep_signal, 0, sizeof(struct epoll_event));
1504 ep_signal.events = EPOLLIN;
1505 ep_signal.data.fd = fd_signal;
7459bcdc 1506
ff2c503d
KS
1507 memset(&ep_netlink, 0, sizeof(struct epoll_event));
1508 ep_netlink.events = EPOLLIN;
1509 ep_netlink.data.fd = fd_netlink;
7459bcdc 1510
ff2c503d
KS
1511 memset(&ep_worker, 0, sizeof(struct epoll_event));
1512 ep_worker.events = EPOLLIN;
1513 ep_worker.data.fd = fd_worker;
7459bcdc 1514
ff2c503d
KS
1515 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1516 if (fd_ep < 0) {
1517 err(udev, "error creating epoll fd: %m\n");
1518 goto exit;
1519 }
1520 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1521 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1522 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1523 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1524 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1525 err(udev, "fail to add fds to epoll: %m\n");
1526 goto exit;
1527 }
1528
5f59fa09
KS
1529 /* if needed, convert old database from earlier udev version */
1530 convert_db(udev);
1531
337d1027 1532 if (children_max <= 0) {
c830e98d
KS
1533 int memsize = mem_size_mb();
1534
1535 /* set value depending on the amount of RAM */
1536 if (memsize > 0)
1537 children_max = 128 + (memsize / 8);
1538 else
1539 children_max = 128;
337d1027
KS
1540 }
1541 info(udev, "set children_max to %u\n", children_max);
a15f42c4 1542
761dfddc
KS
1543 udev_rules_apply_static_dev_perms(rules);
1544
869c9031
KS
1545 udev_list_node_init(&event_list);
1546 udev_list_node_init(&worker_list);
1e03b754 1547
ff2c503d 1548 for (;;) {
4f1795cc 1549 static unsigned long long last_usec;
ff2c503d 1550 struct epoll_event ev[8];
e9a77fd8 1551 int fdcount;
1e03b754 1552 int timeout;
ff2c503d
KS
1553 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1554 int i;
1555
1556 if (udev_exit) {
1557 /* close sources of new events and discard buffered events */
1558 if (fd_ctrl >= 0) {
1559 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1560 fd_ctrl = -1;
1561 }
1562 if (monitor != NULL) {
1563 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1564 udev_monitor_unref(monitor);
1565 monitor = NULL;
1566 }
1567 if (fd_inotify >= 0) {
1568 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1569 close(fd_inotify);
1570 fd_inotify = -1;
1571 }
3210a72b 1572
ff2c503d
KS
1573 /* discard queued events and kill workers */
1574 event_queue_cleanup(udev, EVENT_QUEUED);
1575 worker_kill(udev, 0);
1576
1577 /* exit after all has cleaned up */
869c9031 1578 if (udev_list_node_is_empty(&event_list) && udev_list_node_is_empty(&worker_list))
ff2c503d
KS
1579 break;
1580
1581 /* timeout at exit for workers to finish */
1582 timeout = 60 * 1000;
869c9031 1583 } else if (udev_list_node_is_empty(&event_list) && children > 2) {
ff2c503d 1584 /* set timeout to kill idle workers */
1e03b754 1585 timeout = 3 * 1000;
ff2c503d 1586 } else {
1e03b754 1587 timeout = -1;
ff2c503d
KS
1588 }
1589 fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), timeout);
1e03b754
KS
1590 if (fdcount < 0)
1591 continue;
021a294c 1592
ff2c503d
KS
1593 if (fdcount == 0) {
1594 if (udev_exit) {
1595 info(udev, "timeout, giving up waiting for workers to finish\n");
1596 break;
1597 }
1598
1599 /* timeout - kill idle workers */
adda4c68 1600 worker_kill(udev, 2);
ff2c503d
KS
1601 }
1602
1603 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1604 for (i = 0; i < fdcount; i++) {
1605 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1606 is_worker = true;
1607 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1608 is_netlink = true;
1609 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1610 is_signal = true;
1611 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1612 is_inotify = true;
1613 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1614 is_ctrl = true;
1615 }
e9a77fd8 1616
4f1795cc
KS
1617 /* check for changed config, every 3 seconds at most */
1618 if ((now_usec() - last_usec) > 3 * 1000 * 1000) {
1619 if (check_rules_timestamp(udev))
1620 reload = true;
1621 if (udev_builtin_validate(udev))
1622 reload = true;
1623
1624 last_usec = now_usec();
1625 }
1626
1627 /* reload requested, HUP signal received, rules changed, builtin changed */
1628 if (reload) {
1629 worker_kill(udev, 0);
1630 rules = udev_rules_unref(rules);
1631 udev_builtin_exit(udev);
1632 reload = 0;
1633 }
1634
1e03b754 1635 /* event has finished */
ff2c503d
KS
1636 if (is_worker)
1637 worker_returned(fd_worker);
e9a77fd8 1638
ff2c503d 1639 if (is_netlink) {
1e03b754 1640 struct udev_device *dev;
3210a72b 1641
1e03b754 1642 dev = udev_monitor_receive_device(monitor);
54da6290 1643 if (dev != NULL) {
a20a57a7 1644 udev_device_set_usec_initialized(dev, now_usec());
40929a02
YK
1645 if (event_queue_insert(dev) < 0)
1646 udev_device_unref(dev);
54da6290 1647 }
2f6cbd19 1648 }
e5a2989e 1649
1e03b754 1650 /* start new events */
7c85d636
KS
1651 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1652 if (rules == NULL)
1653 rules = udev_rules_new(udev, resolve_names);
1654 if (rules != NULL)
1655 event_queue_start(udev);
1656 }
aa8734ff 1657
ff2c503d 1658 if (is_signal) {
1e03b754
KS
1659 struct signalfd_siginfo fdsi;
1660 ssize_t size;
aa8734ff 1661
ff2c503d 1662 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1e03b754 1663 if (size == sizeof(struct signalfd_siginfo))
45798927 1664 handle_signal(udev, fdsi.ssi_signo);
021a294c 1665 }
e5a2989e 1666
ff2c503d
KS
1667 /* we are shutting down, the events below are not handled anymore */
1668 if (udev_exit)
1669 continue;
1670
4f1795cc 1671 /* device node watch */
ff2c503d 1672 if (is_inotify)
4aca304e 1673 handle_inotify(udev);
c895fd00 1674
1e03b754 1675 /*
1e03b754 1676 * This needs to be after the inotify handling, to make sure,
ff2c503d 1677 * that the ping is send back after the possibly generated
1e03b754 1678 * "change" events by the inotify device node watch.
ff2c503d
KS
1679 *
1680 * A single time we may receive a client connection which we need to
1681 * keep open to block the client. It will be closed right before we
1682 * exit.
1e03b754 1683 */
ff2c503d
KS
1684 if (is_ctrl)
1685 ctrl_conn = handle_ctrl_msg(udev_ctrl);
53921bfa 1686 }
1e03b754 1687
2738ec2c 1688 rc = EXIT_SUCCESS;
53921bfa 1689exit:
2738ec2c 1690 udev_queue_export_cleanup(udev_queue_export);
1f5a5100
KS
1691 udev_ctrl_cleanup(udev_ctrl);
1692exit_daemonize:
ff2c503d
KS
1693 if (fd_ep >= 0)
1694 close(fd_ep);
1695 worker_list_cleanup(udev);
1696 event_queue_cleanup(udev, EVENT_UNDEF);
d7ddce18 1697 udev_rules_unref(rules);
779f4de1 1698 udev_builtin_exit(udev);
ff2c503d
KS
1699 if (fd_signal >= 0)
1700 close(fd_signal);
1e03b754
KS
1701 if (worker_watch[READ_END] >= 0)
1702 close(worker_watch[READ_END]);
1703 if (worker_watch[WRITE_END] >= 0)
1704 close(worker_watch[WRITE_END]);
1705 udev_monitor_unref(monitor);
ff2c503d
KS
1706 udev_queue_export_unref(udev_queue_export);
1707 udev_ctrl_connection_unref(ctrl_conn);
1708 udev_ctrl_unref(udev_ctrl);
c3b1fa66 1709 udev_selinux_exit(udev);
e598c573 1710 udev_unref(udev);
9060b066 1711 udev_log_close();
833b3c68 1712 return rc;
7fafc032 1713}