]> git.ipfire.org Git - thirdparty/systemd.git/blob - udevd.c
[PATCH] udev_volume_id: volume_id version 034
[thirdparty/systemd.git] / udevd.c
1 /*
2 * udevd.c - hotplug event serializer
3 *
4 * Copyright (C) 2004 Kay Sievers <kay.sievers@vrfy.org>
5 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
6 *
7 *
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation version 2 of the License.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 675 Mass Ave, Cambridge, MA 02139, USA.
20 *
21 */
22
23 #include <stddef.h>
24 #include <sys/wait.h>
25 #include <signal.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <ctype.h>
32 #include <dirent.h>
33 #include <fcntl.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/un.h>
38 #include <sys/sysinfo.h>
39 #include <sys/stat.h>
40
41 #include "list.h"
42 #include "udev.h"
43 #include "udev_version.h"
44 #include "udev_utils.h"
45 #include "udevd.h"
46 #include "logging.h"
47
48 /* global variables*/
49 static int udevsendsock;
50 static pid_t sid;
51
52 static int pipefds[2];
53 static long startup_time;
54 static unsigned long long expected_seqnum = 0;
55 static volatile int sigchilds_waiting;
56 static volatile int run_msg_q;
57 static volatile int sig_flag;
58 static int run_exec_q;
59
60 static LIST_HEAD(msg_list);
61 static LIST_HEAD(exec_list);
62 static LIST_HEAD(running_list);
63
64 static void exec_queue_manager(void);
65 static void msg_queue_manager(void);
66 static void user_sighandler(void);
67 static void reap_sigchilds(void);
68 char *udev_bin;
69
70 #ifdef LOG
71 void log_message (int level, const char *format, ...)
72 {
73 va_list args;
74
75 va_start(args, format);
76 vsyslog(level, format, args);
77 va_end(args);
78 }
79 #endif
80
81 #define msg_dump(msg) \
82 dbg("msg_dump: sequence %llu, '%s', '%s', '%s'", \
83 msg->seqnum, msg->action, msg->devpath, msg->subsystem);
84
85 static void msg_dump_queue(void)
86 {
87 #ifdef DEBUG
88 struct hotplug_msg *msg;
89
90 list_for_each_entry(msg, &msg_list, list)
91 dbg("sequence %llu in queue", msg->seqnum);
92 #endif
93 }
94
95 static void run_queue_delete(struct hotplug_msg *msg)
96 {
97 list_del(&msg->list);
98 free(msg);
99 }
100
101 /* orders the message in the queue by sequence number */
102 static void msg_queue_insert(struct hotplug_msg *msg)
103 {
104 struct hotplug_msg *loop_msg;
105 struct sysinfo info;
106
107 if (msg->seqnum == 0) {
108 dbg("no SEQNUM, move straight to the exec queue");
109 list_add(&msg->list, &exec_list);
110 run_exec_q = 1;
111 return;
112 }
113
114 /* sort message by sequence number into list */
115 list_for_each_entry_reverse(loop_msg, &msg_list, list) {
116 if (loop_msg->seqnum < msg->seqnum)
117 break;
118
119 if (loop_msg->seqnum == msg->seqnum) {
120 dbg("ignoring duplicate message seq %llu", msg->seqnum);
121 return;
122 }
123 }
124
125 /* store timestamp of queuing */
126 sysinfo(&info);
127 msg->queue_time = info.uptime;
128
129 list_add(&msg->list, &loop_msg->list);
130 dbg("queued message seq %llu", msg->seqnum);
131
132 /* run msg queue manager */
133 run_msg_q = 1;
134
135 return;
136 }
137
138 /* forks event and removes event from run queue when finished */
139 static void udev_run(struct hotplug_msg *msg)
140 {
141 char *const argv[] = { "udev", msg->subsystem, NULL };
142 pid_t pid;
143
144 pid = fork();
145 switch (pid) {
146 case 0:
147 /* child */
148 close(udevsendsock);
149 logging_close();
150
151 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
152 execve(udev_bin, argv, msg->envp);
153 dbg("exec of child failed");
154 _exit(1);
155 break;
156 case -1:
157 dbg("fork of child failed");
158 run_queue_delete(msg);
159 break;
160 default:
161 /* get SIGCHLD in main loop */
162 dbg("==> exec seq %llu [%d] working at '%s'", msg->seqnum, pid, msg->devpath);
163 msg->pid = pid;
164 }
165 }
166
167 static int running_processes(void)
168 {
169 int f;
170 static char buf[4096];
171 int len;
172 int running;
173 const char *pos;
174
175 f = open("/proc/stat", O_RDONLY);
176 if (f == -1)
177 return -1;
178
179 len = read(f, buf, sizeof(buf));
180 close(f);
181
182 if (len <= 0)
183 return -1;
184 else
185 buf[len] = '\0';
186
187 pos = strstr(buf, "procs_running ");
188 if (pos == NULL)
189 return -1;
190
191 if (sscanf(pos, "procs_running %u", &running) != 1)
192 return -1;
193
194 return running;
195 }
196
197 /* return the number of process es in our session, count only until limit */
198 static int running_processes_in_session(pid_t session, int limit)
199 {
200 DIR *dir;
201 struct dirent *dent;
202 int running = 0;
203
204 dir = opendir("/proc");
205 if (!dir)
206 return -1;
207
208 /* read process info from /proc */
209 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
210 int f;
211 char procdir[64];
212 char line[256];
213 const char *pos;
214 char state;
215 pid_t ppid, pgrp, sess;
216 int len;
217
218 if (!isdigit(dent->d_name[0]))
219 continue;
220
221 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
222 procdir[sizeof(procdir)-1] = '\0';
223
224 f = open(procdir, O_RDONLY);
225 if (f == -1)
226 continue;
227
228 len = read(f, line, sizeof(line));
229 close(f);
230
231 if (len <= 0)
232 continue;
233 else
234 line[len] = '\0';
235
236 /* skip ugly program name */
237 pos = strrchr(line, ')') + 2;
238 if (pos == NULL)
239 continue;
240
241 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
242 continue;
243
244 /* count only processes in our session */
245 if (sess != session)
246 continue;
247
248 /* count only running, no sleeping processes */
249 if (state != 'R')
250 continue;
251
252 running++;
253 if (limit > 0 && running >= limit)
254 break;
255 }
256 closedir(dir);
257
258 return running;
259 }
260
261 static int compare_devpath(const char *running, const char *waiting)
262 {
263 int i;
264
265 for (i = 0; i < DEVPATH_SIZE; i++) {
266 /* identical device event found */
267 if (running[i] == '\0' && waiting[i] == '\0')
268 return 1;
269
270 /* parent device event found */
271 if (running[i] == '\0' && waiting[i] == '/')
272 return 2;
273
274 /* child device event found */
275 if (running[i] == '/' && waiting[i] == '\0')
276 return 3;
277
278 /* no matching event */
279 if (running[i] != waiting[i])
280 break;
281 }
282
283 return 0;
284 }
285
286 /* returns still running task for the same device, its parent or its physical device */
287 static struct hotplug_msg *running_with_devpath(struct hotplug_msg *msg)
288 {
289 struct hotplug_msg *loop_msg;
290
291 if (msg->devpath == NULL)
292 return NULL;
293
294 list_for_each_entry(loop_msg, &running_list, list) {
295 if (loop_msg->devpath == NULL)
296 continue;
297
298 /* return running parent/child device event */
299 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0)
300 return loop_msg;
301
302 /* return running physical device event */
303 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
304 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0)
305 return loop_msg;
306 }
307
308 return NULL;
309 }
310
311 /* exec queue management routine executes the events and serializes events in the same sequence */
312 static void exec_queue_manager(void)
313 {
314 struct hotplug_msg *loop_msg;
315 struct hotplug_msg *tmp_msg;
316 struct hotplug_msg *msg;
317 int running;
318
319 running = running_processes();
320 dbg("%d processes runnning on system", running);
321 if (running < 0)
322 running = THROTTLE_MAX_RUNNING_CHILDS;
323
324 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, list) {
325 /* check running processes in our session and possibly throttle */
326 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
327 running = running_processes_in_session(sid, THROTTLE_MAX_RUNNING_CHILDS+10);
328 dbg("%d processes running in session", running);
329 if (running >= THROTTLE_MAX_RUNNING_CHILDS) {
330 dbg("delay seq %llu, cause too many processes already running", loop_msg->seqnum);
331 return;
332 }
333 }
334
335 msg = running_with_devpath(loop_msg);
336 if (!msg) {
337 /* move event to run list */
338 list_move_tail(&loop_msg->list, &running_list);
339 udev_run(loop_msg);
340 running++;
341 dbg("moved seq %llu to running list", loop_msg->seqnum);
342 } else {
343 dbg("delay seq %llu (%s), cause seq %llu (%s) is still running",
344 loop_msg->seqnum, loop_msg->devpath, msg->seqnum, msg->devpath);
345 }
346 }
347 }
348
349 static void msg_move_exec(struct hotplug_msg *msg)
350 {
351 list_move_tail(&msg->list, &exec_list);
352 run_exec_q = 1;
353 expected_seqnum = msg->seqnum+1;
354 dbg("moved seq %llu to exec, next expected is %llu",
355 msg->seqnum, expected_seqnum);
356 }
357
358 /* msg queue management routine handles the timeouts and dispatches the events */
359 static void msg_queue_manager(void)
360 {
361 struct hotplug_msg *loop_msg;
362 struct hotplug_msg *tmp_msg;
363 struct sysinfo info;
364 long msg_age = 0;
365 static int timeout = EVENT_INIT_TIMEOUT_SEC;
366 static int init = 1;
367
368 dbg("msg queue manager, next expected is %llu", expected_seqnum);
369 recheck:
370 list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, list) {
371 /* move event with expected sequence to the exec list */
372 if (loop_msg->seqnum == expected_seqnum) {
373 msg_move_exec(loop_msg);
374 continue;
375 }
376
377 /* see if we are in the initialization phase and wait for the very first events */
378 if (init && (info.uptime - startup_time >= INIT_TIME_SEC)) {
379 init = 0;
380 timeout = EVENT_TIMEOUT_SEC;
381 dbg("initialization phase passed, set timeout to %i seconds", EVENT_TIMEOUT_SEC);
382 }
383
384 /* move event with expired timeout to the exec list */
385 sysinfo(&info);
386 msg_age = info.uptime - loop_msg->queue_time;
387 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
388 if (msg_age >= timeout) {
389 msg_move_exec(loop_msg);
390 goto recheck;
391 } else {
392 break;
393 }
394 }
395
396 msg_dump_queue();
397
398 /* set timeout for remaining queued events */
399 if (list_empty(&msg_list) == 0) {
400 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
401 dbg("next event expires in %li seconds", timeout - msg_age);
402 setitimer(ITIMER_REAL, &itv, NULL);
403 }
404 }
405
406 /* receive the udevsend message and do some sanity checks */
407 static struct hotplug_msg *get_udevsend_msg(void)
408 {
409 static struct udevsend_msg usend_msg;
410 struct hotplug_msg *msg;
411 int bufpos;
412 int i;
413 ssize_t size;
414 struct msghdr smsg;
415 struct cmsghdr *cmsg;
416 struct iovec iov;
417 struct ucred *cred;
418 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
419 int envbuf_size;
420
421 memset(&usend_msg, 0x00, sizeof(struct udevsend_msg));
422 iov.iov_base = &usend_msg;
423 iov.iov_len = sizeof(struct udevsend_msg);
424
425 memset(&smsg, 0x00, sizeof(struct msghdr));
426 smsg.msg_iov = &iov;
427 smsg.msg_iovlen = 1;
428 smsg.msg_control = cred_msg;
429 smsg.msg_controllen = sizeof(cred_msg);
430
431 size = recvmsg(udevsendsock, &smsg, 0);
432 if (size < 0) {
433 if (errno != EINTR)
434 dbg("unable to receive udevsend message");
435 return NULL;
436 }
437 cmsg = CMSG_FIRSTHDR(&smsg);
438 cred = (struct ucred *) CMSG_DATA(cmsg);
439
440 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
441 dbg("no sender credentials received, message ignored");
442 return NULL;
443 }
444
445 if (cred->uid != 0) {
446 dbg("sender uid=%i, message ignored", cred->uid);
447 return NULL;
448 }
449
450 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
451 dbg("message magic '%s' doesn't match, ignore it", usend_msg.magic);
452 return NULL;
453 }
454
455 envbuf_size = size - offsetof(struct udevsend_msg, envbuf);
456 dbg("envbuf_size=%i", envbuf_size);
457 msg = malloc(sizeof(struct hotplug_msg) + envbuf_size);
458 if (msg == NULL)
459 return NULL;
460
461 memset(msg, 0x00, sizeof(struct hotplug_msg) + envbuf_size);
462
463 /* copy environment buffer and reconstruct envp */
464 memcpy(msg->envbuf, usend_msg.envbuf, envbuf_size);
465 bufpos = 0;
466 for (i = 0; (bufpos < envbuf_size) && (i < HOTPLUG_NUM_ENVP-2); i++) {
467 int keylen;
468 char *key;
469
470 key = &msg->envbuf[bufpos];
471 keylen = strlen(key);
472 msg->envp[i] = key;
473 bufpos += keylen + 1;
474 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
475
476 /* remember some keys for further processing */
477 if (strncmp(key, "ACTION=", 7) == 0)
478 msg->action = &key[7];
479
480 if (strncmp(key, "DEVPATH=", 8) == 0)
481 msg->devpath = &key[8];
482
483 if (strncmp(key, "SUBSYSTEM=", 10) == 0)
484 msg->subsystem = &key[10];
485
486 if (strncmp(key, "SEQNUM=", 7) == 0)
487 msg->seqnum = strtoull(&key[7], NULL, 10);
488
489 if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
490 msg->physdevpath = &key[12];
491 }
492 msg->envp[i++] = "UDEVD_EVENT=1";
493 msg->envp[i] = NULL;
494
495 return msg;
496 }
497
498 static void asmlinkage sig_handler(int signum)
499 {
500 int rc;
501
502 switch (signum) {
503 case SIGINT:
504 case SIGTERM:
505 exit(20 + signum);
506 break;
507 case SIGALRM:
508 /* set flag, then write to pipe if needed */
509 run_msg_q = 1;
510 goto do_write;
511 break;
512 case SIGCHLD:
513 /* set flag, then write to pipe if needed */
514 sigchilds_waiting = 1;
515 goto do_write;
516 break;
517 }
518
519 do_write:
520 /* if pipe is empty, write to pipe to force select to return
521 * immediately when it gets called
522 */
523 if (!sig_flag) {
524 rc = write(pipefds[1],&signum,sizeof(signum));
525 if (rc >= 0)
526 sig_flag = 1;
527 }
528 }
529
530 static void udev_done(int pid)
531 {
532 /* find msg associated with pid and delete it */
533 struct hotplug_msg *msg;
534
535 list_for_each_entry(msg, &running_list, list) {
536 if (msg->pid == pid) {
537 dbg("<== exec seq %llu came back", msg->seqnum);
538 run_queue_delete(msg);
539
540 /* we want to run the exec queue manager since there may
541 * be events waiting with the devpath of the one that
542 * just finished
543 */
544 run_exec_q = 1;
545 return;
546 }
547 }
548 }
549
550 static void reap_sigchilds(void)
551 {
552 while(1) {
553 int pid = waitpid(-1, NULL, WNOHANG);
554 if ((pid == -1) || (pid == 0))
555 break;
556 udev_done(pid);
557 }
558 }
559
560 /* just read everything from the pipe and clear the flag,
561 * the flags was set in the signal handler
562 */
563 static void user_sighandler(void)
564 {
565 int sig;
566
567 while(1) {
568 int rc = read(pipefds[0], &sig, sizeof(sig));
569 if (rc < 0)
570 break;
571
572 sig_flag = 0;
573 }
574 }
575
576 static int init_udevsend_socket(void)
577 {
578 struct sockaddr_un saddr;
579 socklen_t addrlen;
580 const int feature_on = 1;
581 int retval;
582
583 memset(&saddr, 0x00, sizeof(saddr));
584 saddr.sun_family = AF_LOCAL;
585 /* use abstract namespace for socket path */
586 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
587 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
588
589 udevsendsock = socket(AF_LOCAL, SOCK_DGRAM, 0);
590 if (udevsendsock == -1) {
591 dbg("error getting socket, %s", strerror(errno));
592 return -1;
593 }
594
595 /* the bind takes care of ensuring only one copy running */
596 retval = bind(udevsendsock, (struct sockaddr *) &saddr, addrlen);
597 if (retval < 0) {
598 dbg("bind failed, %s", strerror(errno));
599 close(udevsendsock);
600 return -1;
601 }
602
603 /* enable receiving of the sender credentials */
604 setsockopt(udevsendsock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
605
606 return 0;
607 }
608
609 int main(int argc, char *argv[], char *envp[])
610 {
611 struct sysinfo info;
612 int maxsockplus;
613 int retval;
614 int fd;
615 struct sigaction act;
616 fd_set readfds;
617 const char *udevd_expected_seqnum;
618
619 logging_init("udevd");
620 dbg("version %s", UDEV_VERSION);
621
622 if (getuid() != 0) {
623 dbg("need to be root, exit");
624 goto exit;
625 }
626
627 /* daemonize on request */
628 if (argc == 2 && strcmp(argv[1], "-d") == 0) {
629 pid_t pid;
630
631 pid = fork();
632 switch (pid) {
633 case 0:
634 dbg("damonized fork running");
635 break;
636 case -1:
637 dbg("fork of daemon failed");
638 goto exit;
639 default:
640 logging_close();
641 exit(0);
642 }
643 }
644
645 /* become session leader */
646 sid = setsid();
647 dbg("our session is %d", sid);
648
649 /* make sure we don't lock any path */
650 chdir("/");
651 umask(umask(077) | 022);
652
653 /*set a reasonable scheduling priority for the daemon */
654 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
655
656 /* Set fds to dev/null */
657 fd = open( "/dev/null", O_RDWR );
658 if (fd >= 0) {
659 dup2(fd, 0);
660 dup2(fd, 1);
661 dup2(fd, 2);
662 if (fd > 2)
663 close(fd);
664 } else
665 dbg("error opening /dev/null %s", strerror(errno));
666
667 /* setup signal handler pipe */
668 retval = pipe(pipefds);
669 if (retval < 0) {
670 dbg("error getting pipes: %s", strerror(errno));
671 goto exit;
672 }
673
674 retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
675 if (retval < 0) {
676 dbg("error fcntl on read pipe: %s", strerror(errno));
677 goto exit;
678 }
679 retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
680 if (retval < 0)
681 dbg("error fcntl on read pipe: %s", strerror(errno));
682
683 retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
684 if (retval < 0) {
685 dbg("error fcntl on write pipe: %s", strerror(errno));
686 goto exit;
687 }
688 retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
689 if (retval < 0)
690 dbg("error fcntl on write pipe: %s", strerror(errno));
691
692 /* set signal handlers */
693 memset(&act, 0x00, sizeof(struct sigaction));
694 act.sa_handler = (void (*) (int))sig_handler;
695 sigemptyset(&act.sa_mask);
696 act.sa_flags = SA_RESTART;
697 sigaction(SIGINT, &act, NULL);
698 sigaction(SIGTERM, &act, NULL);
699 sigaction(SIGALRM, &act, NULL);
700 sigaction(SIGCHLD, &act, NULL);
701
702 if (init_udevsend_socket() < 0) {
703 if (errno == EADDRINUSE)
704 dbg("another udevd running, exit");
705 else
706 dbg("error initialising udevsend socket: %s", strerror(errno));
707
708 goto exit;
709 }
710
711 /* possible override of udev binary, used for testing */
712 udev_bin = getenv("UDEV_BIN");
713 if (udev_bin != NULL)
714 dbg("udev binary is set to '%s'", udev_bin);
715 else
716 udev_bin = UDEV_BIN;
717
718 /* possible init of expected_seqnum value */
719 udevd_expected_seqnum = getenv("UDEVD_EXPECTED_SEQNUM");
720 if (udevd_expected_seqnum != NULL) {
721 expected_seqnum = strtoull(udevd_expected_seqnum, NULL, 10);
722 dbg("initialize expected_seqnum to %llu", expected_seqnum);
723 }
724
725 /* get current time to provide shorter timeout on startup */
726 sysinfo(&info);
727 startup_time = info.uptime;
728
729 FD_ZERO(&readfds);
730 FD_SET(udevsendsock, &readfds);
731 FD_SET(pipefds[0], &readfds);
732 maxsockplus = udevsendsock+1;
733 while (1) {
734 struct hotplug_msg *msg;
735
736 fd_set workreadfds = readfds;
737 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
738
739 if (retval < 0) {
740 if (errno != EINTR)
741 dbg("error in select: %s", strerror(errno));
742 continue;
743 }
744
745 if (FD_ISSET(udevsendsock, &workreadfds)) {
746 msg = get_udevsend_msg();
747 if (msg)
748 msg_queue_insert(msg);
749 }
750
751 if (FD_ISSET(pipefds[0], &workreadfds))
752 user_sighandler();
753
754 if (sigchilds_waiting) {
755 sigchilds_waiting = 0;
756 reap_sigchilds();
757 }
758
759 if (run_msg_q) {
760 run_msg_q = 0;
761 msg_queue_manager();
762 }
763
764 if (run_exec_q) {
765 /* clean up running_list before calling exec_queue_manager() */
766 if (sigchilds_waiting) {
767 sigchilds_waiting = 0;
768 reap_sigchilds();
769 }
770
771 run_exec_q = 0;
772 exec_queue_manager();
773 }
774 }
775
776 exit:
777 logging_close();
778 return 1;
779 }