chiark / gitweb /
[PATCH] udevd: it's obviously not the brightest idea to exit a device node manager...
[elogind.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 <sys/time.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <sys/un.h>
35 #include <fcntl.h>
36 #include <sys/sysinfo.h>
37 #include <sys/stat.h>
38
39 #include "list.h"
40 #include "udev.h"
41 #include "udev_version.h"
42 #include "udev_utils.h"
43 #include "udevd.h"
44 #include "logging.h"
45
46 /* global variables*/
47 static int udevsendsock;
48
49 static int pipefds[2];
50 static long startup_time;
51 static unsigned long long expected_seqnum = 0;
52 static volatile int sigchilds_waiting;
53 static volatile int run_msg_q;
54 static volatile int sig_flag;
55 static int run_exec_q;
56
57 static LIST_HEAD(msg_list);
58 static LIST_HEAD(exec_list);
59 static LIST_HEAD(running_list);
60
61 static void exec_queue_manager(void);
62 static void msg_queue_manager(void);
63 static void user_sighandler(void);
64 static void reap_sigchilds(void);
65 char *udev_bin;
66
67 #ifdef LOG
68 void log_message (int level, const char *format, ...)
69 {
70         va_list args;
71
72         va_start(args, format);
73         vsyslog(level, format, args);
74         va_end(args);
75 }
76 #endif
77
78 #define msg_dump(msg) \
79         dbg("msg_dump: sequence %llu, '%s', '%s', '%s'", \
80         msg->seqnum, msg->action, msg->devpath, msg->subsystem);
81
82 static void msg_dump_queue(void)
83 {
84 #ifdef DEBUG
85         struct hotplug_msg *msg;
86
87         list_for_each_entry(msg, &msg_list, list)
88                 dbg("sequence %llu in queue", msg->seqnum);
89 #endif
90 }
91
92 static void run_queue_delete(struct hotplug_msg *msg)
93 {
94         list_del(&msg->list);
95         free(msg);
96 }
97
98 /* orders the message in the queue by sequence number */
99 static void msg_queue_insert(struct hotplug_msg *msg)
100 {
101         struct hotplug_msg *loop_msg;
102         struct sysinfo info;
103
104         if (msg->seqnum == 0) {
105                 dbg("no SEQNUM, move straight to the exec queue");
106                 list_add(&msg->list, &exec_list);
107                 run_exec_q = 1;
108                 return;
109         }
110
111         /* sort message by sequence number into list */
112         list_for_each_entry_reverse(loop_msg, &msg_list, list) {
113                 if (loop_msg->seqnum < msg->seqnum)
114                         break;
115
116                 if (loop_msg->seqnum == msg->seqnum) {
117                         dbg("ignoring duplicate message seq %llu", msg->seqnum);
118                         return;
119                 }
120         }
121
122         /* store timestamp of queuing */
123         sysinfo(&info);
124         msg->queue_time = info.uptime;
125
126         list_add(&msg->list, &loop_msg->list);
127         dbg("queued message seq %llu", msg->seqnum);
128
129         /* run msg queue manager */
130         run_msg_q = 1;
131
132         return;
133 }
134
135 /* forks event and removes event from run queue when finished */
136 static void udev_run(struct hotplug_msg *msg)
137 {
138         char *const argv[] = { "udev", msg->subsystem, NULL };
139         pid_t pid;
140
141         pid = fork();
142         switch (pid) {
143         case 0:
144                 /* child */
145                 close(udevsendsock);
146                 logging_close();
147                 execve(udev_bin, argv, msg->envp);
148                 dbg("exec of child failed");
149                 _exit(1);
150                 break;
151         case -1:
152                 dbg("fork of child failed");
153                 run_queue_delete(msg);
154                 /* note: we never managed to run, so we had no impact on 
155                  * running_with_devpath(), so don't bother setting run_exec_q
156                  */
157                 break;
158         default:
159                 /* get SIGCHLD in main loop */
160                 dbg("==> exec seq %llu [%d] working at '%s'", msg->seqnum, pid, msg->devpath);
161                 msg->pid = pid;
162         }
163 }
164
165 static int compare_devpath(const char *running, const char *waiting)
166 {
167         int i;
168
169         for (i = 0; i < DEVPATH_SIZE; i++) {
170                 /* identical device event found */
171                 if (running[i] == '\0' && waiting[i] == '\0')
172                         return 1;
173
174                 /* parent device event found */
175                 if (running[i] == '\0' && waiting[i] == '/')
176                         return 2;
177
178                 /* child device event found */
179                 if (running[i] == '/' && waiting[i] == '\0')
180                         return 3;
181
182                 /* no matching event */
183                 if (running[i] != waiting[i])
184                         break;
185         }
186
187         return 0;
188 }
189
190 /* returns still running task for the same device, its parent or its physical device */
191 static struct hotplug_msg *running_with_devpath(struct hotplug_msg *msg)
192 {
193         struct hotplug_msg *loop_msg;
194
195         if (msg->devpath == NULL)
196                 return NULL;
197
198         list_for_each_entry(loop_msg, &running_list, list) {
199                 if (loop_msg->devpath == NULL)
200                         continue;
201
202                 /* return running parent/child device event */
203                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0)
204                         return loop_msg;
205
206                 /* return running physical device event */
207                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
208                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0)
209                                 return loop_msg;
210         }
211
212         return NULL;
213 }
214
215 /* exec queue management routine executes the events and serializes events in the same sequence */
216 static void exec_queue_manager(void)
217 {
218         struct hotplug_msg *loop_msg;
219         struct hotplug_msg *tmp_msg;
220         struct hotplug_msg *msg;
221
222         list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, list) {
223                 msg = running_with_devpath(loop_msg);
224                 if (!msg) {
225                         /* move event to run list */
226                         list_move_tail(&loop_msg->list, &running_list);
227                         udev_run(loop_msg);
228                         dbg("moved seq %llu to running list", loop_msg->seqnum);
229                 } else {
230                         dbg("delay seq %llu (%s), cause seq %llu (%s) is still running",
231                             loop_msg->seqnum, loop_msg->devpath, msg->seqnum, msg->devpath);
232                 }
233         }
234 }
235
236 static void msg_move_exec(struct hotplug_msg *msg)
237 {
238         list_move_tail(&msg->list, &exec_list);
239         run_exec_q = 1;
240         expected_seqnum = msg->seqnum+1;
241         dbg("moved seq %llu to exec, next expected is %llu",
242                 msg->seqnum, expected_seqnum);
243 }
244
245 /* msg queue management routine handles the timeouts and dispatches the events */
246 static void msg_queue_manager(void)
247 {
248         struct hotplug_msg *loop_msg;
249         struct hotplug_msg *tmp_msg;
250         struct sysinfo info;
251         long msg_age = 0;
252         static int timeout = EVENT_INIT_TIMEOUT_SEC;
253         static int init = 1;
254
255         dbg("msg queue manager, next expected is %llu", expected_seqnum);
256 recheck:
257         list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, list) {
258                 /* move event with expected sequence to the exec list */
259                 if (loop_msg->seqnum == expected_seqnum) {
260                         msg_move_exec(loop_msg);
261                         continue;
262                 }
263
264                 /* see if we are in the initialization phase and wait for the very first events */
265                 if (init && (info.uptime - startup_time >= INIT_TIME_SEC)) {
266                         init = 0;
267                         timeout = EVENT_TIMEOUT_SEC;
268                         dbg("initialization phase passed, set timeout to %i seconds", EVENT_TIMEOUT_SEC);
269                 }
270
271                 /* move event with expired timeout to the exec list */
272                 sysinfo(&info);
273                 msg_age = info.uptime - loop_msg->queue_time;
274                 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
275                 if (msg_age >= timeout) {
276                         msg_move_exec(loop_msg);
277                         goto recheck;
278                 } else {
279                         break;
280                 }
281         }
282
283         msg_dump_queue();
284
285         /* set timeout for remaining queued events */
286         if (list_empty(&msg_list) == 0) {
287                 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
288                 dbg("next event expires in %li seconds", timeout - msg_age);
289                 setitimer(ITIMER_REAL, &itv, NULL);
290         }
291 }
292
293 /* receive the udevsend message and do some sanity checks */
294 static struct hotplug_msg *get_udevsend_msg(void)
295 {
296         static struct udevsend_msg usend_msg;
297         struct hotplug_msg *msg;
298         int bufpos;
299         int i;
300         ssize_t size;
301         struct msghdr smsg;
302         struct cmsghdr *cmsg;
303         struct iovec iov;
304         struct ucred *cred;
305         char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
306         int envbuf_size;
307
308         memset(&usend_msg, 0x00, sizeof(struct udevsend_msg));
309         iov.iov_base = &usend_msg;
310         iov.iov_len = sizeof(struct udevsend_msg);
311
312         memset(&smsg, 0x00, sizeof(struct msghdr));
313         smsg.msg_iov = &iov;
314         smsg.msg_iovlen = 1;
315         smsg.msg_control = cred_msg;
316         smsg.msg_controllen = sizeof(cred_msg);
317
318         size = recvmsg(udevsendsock, &smsg, 0);
319         if (size <  0) {
320                 if (errno != EINTR)
321                         dbg("unable to receive udevsend message");
322                 return NULL;
323         }
324         cmsg = CMSG_FIRSTHDR(&smsg);
325         cred = (struct ucred *) CMSG_DATA(cmsg);
326
327         if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
328                 dbg("no sender credentials received, message ignored");
329                 return NULL;
330         }
331
332         if (cred->uid != 0) {
333                 dbg("sender uid=%i, message ignored", cred->uid);
334                 return NULL;
335         }
336
337         if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
338                 dbg("message magic '%s' doesn't match, ignore it", usend_msg.magic);
339                 return NULL;
340         }
341
342         envbuf_size = size - offsetof(struct udevsend_msg, envbuf);
343         dbg("envbuf_size=%i", envbuf_size);
344         msg = malloc(sizeof(struct hotplug_msg) + envbuf_size);
345         if (msg == NULL)
346                 return NULL;
347
348         memset(msg, 0x00, sizeof(struct hotplug_msg) + envbuf_size);
349
350         /* copy environment buffer and reconstruct envp */
351         memcpy(msg->envbuf, usend_msg.envbuf, envbuf_size);
352         bufpos = 0;
353         for (i = 0; (bufpos < envbuf_size) && (i < HOTPLUG_NUM_ENVP-2); i++) {
354                 int keylen;
355                 char *key;
356
357                 key = &msg->envbuf[bufpos];
358                 keylen = strlen(key);
359                 msg->envp[i] = key;
360                 bufpos += keylen + 1;
361                 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
362
363                 /* remember some keys for further processing */
364                 if (strncmp(key, "ACTION=", 7) == 0)
365                         msg->action = &key[7];
366
367                 if (strncmp(key, "DEVPATH=", 8) == 0)
368                         msg->devpath = &key[8];
369
370                 if (strncmp(key, "SUBSYSTEM=", 10) == 0)
371                         msg->subsystem = &key[10];
372
373                 if (strncmp(key, "SEQNUM=", 7) == 0)
374                         msg->seqnum = strtoull(&key[7], NULL, 10);
375
376                 if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
377                         msg->physdevpath = &key[12];
378         }
379         msg->envp[i++] = "UDEVD_EVENT=1";
380         msg->envp[i] = NULL;
381
382         return msg;
383 }
384
385 static void asmlinkage sig_handler(int signum)
386 {
387         int rc;
388
389         switch (signum) {
390                 case SIGINT:
391                 case SIGTERM:
392                         exit(20 + signum);
393                         break;
394                 case SIGALRM:
395                         /* set flag, then write to pipe if needed */
396                         run_msg_q = 1;
397                         goto do_write;
398                         break;
399                 case SIGCHLD:
400                         /* set flag, then write to pipe if needed */
401                         sigchilds_waiting = 1;
402                         goto do_write;
403                         break;
404         }
405
406 do_write:
407         /* if pipe is empty, write to pipe to force select to return
408          * immediately when it gets called
409          */
410         if (!sig_flag) {
411                 rc = write(pipefds[1],&signum,sizeof(signum));
412                 if (rc >= 0)
413                         sig_flag = 1;
414         }
415 }
416
417 static void udev_done(int pid)
418 {
419         /* find msg associated with pid and delete it */
420         struct hotplug_msg *msg;
421
422         list_for_each_entry(msg, &running_list, list) {
423                 if (msg->pid == pid) {
424                         dbg("<== exec seq %llu came back", msg->seqnum);
425                         run_queue_delete(msg);
426
427                         /* we want to run the exec queue manager since there may
428                          * be events waiting with the devpath of the one that
429                          * just finished
430                          */
431                         run_exec_q = 1;
432                         return;
433                 }
434         }
435 }
436
437 static void reap_sigchilds(void)
438 {
439         while(1) {
440                 int pid = waitpid(-1, NULL, WNOHANG);
441                 if ((pid == -1) || (pid == 0))
442                         break;
443                 udev_done(pid);
444         }
445 }
446
447 /* just read everything from the pipe and clear the flag,
448  * the flags was set in the signal handler
449  */
450 static void user_sighandler(void)
451 {
452         int sig;
453
454         while(1) {
455                 int rc = read(pipefds[0], &sig, sizeof(sig));
456                 if (rc < 0)
457                         break;
458
459                 sig_flag = 0;
460         }
461 }
462
463 static int init_udevsend_socket(void)
464 {
465         struct sockaddr_un saddr;
466         socklen_t addrlen;
467         const int feature_on = 1;
468         int retval;
469
470         memset(&saddr, 0x00, sizeof(saddr));
471         saddr.sun_family = AF_LOCAL;
472         /* use abstract namespace for socket path */
473         strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
474         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
475
476         udevsendsock = socket(AF_LOCAL, SOCK_DGRAM, 0);
477         if (udevsendsock == -1) {
478                 dbg("error getting socket, %s", strerror(errno));
479                 return -1;
480         }
481
482         /* the bind takes care of ensuring only one copy running */
483         retval = bind(udevsendsock, (struct sockaddr *) &saddr, addrlen);
484         if (retval < 0) {
485                 dbg("bind failed, %s", strerror(errno));
486                 close(udevsendsock);
487                 return -1;
488         }
489
490         /* enable receiving of the sender credentials */
491         setsockopt(udevsendsock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
492
493         return 0;
494 }
495
496 int main(int argc, char *argv[], char *envp[])
497 {
498         struct sysinfo info;
499         int maxsockplus;
500         int retval;
501         int fd;
502         struct sigaction act;
503         fd_set readfds;
504
505         logging_init("udevd");
506         dbg("version %s", UDEV_VERSION);
507
508         if (getuid() != 0) {
509                 dbg("need to be root, exit");
510                 goto exit;
511         }
512
513         /* daemonize on request */
514         if (argc == 2 && strcmp(argv[1], "-d") == 0) {
515                 pid_t pid;
516
517                 pid = fork();
518                 switch (pid) {
519                 case 0:
520                         dbg("damonized fork running");
521                         break;
522                 case -1:
523                         dbg("fork of daemon failed");
524                         goto exit;
525                 default:
526                         logging_close();
527                         exit(0);
528                 }
529         }
530
531         /* make sure we don't lock any path */
532         chdir("/");
533         umask(umask(077) | 022);
534
535         /* Set fds to dev/null */
536         fd = open( "/dev/null", O_RDWR );
537         if (fd >= 0)  {
538                 dup2(fd, 0);
539                 dup2(fd, 1);
540                 dup2(fd, 2);
541                 if (fd > 2)
542                         close(fd);
543         } else
544                 dbg("error opening /dev/null %s", strerror(errno));
545
546         /* become session leader */
547         setsid();
548
549         /* setup signal handler pipe */
550         retval = pipe(pipefds);
551         if (retval < 0) {
552                 dbg("error getting pipes: %s", strerror(errno));
553                 goto exit;
554         }
555
556         retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
557         if (retval < 0) {
558                 dbg("error fcntl on read pipe: %s", strerror(errno));
559                 goto exit;
560         }
561         retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
562         if (retval < 0)
563                 dbg("error fcntl on read pipe: %s", strerror(errno));
564
565         retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
566         if (retval < 0) {
567                 dbg("error fcntl on write pipe: %s", strerror(errno));
568                 goto exit;
569         }
570         retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
571         if (retval < 0)
572                 dbg("error fcntl on write pipe: %s", strerror(errno));
573
574         /* set signal handlers */
575         act.sa_handler = (void (*) (int))sig_handler;
576         sigemptyset(&act.sa_mask);
577         act.sa_flags = SA_RESTART;
578         sigaction(SIGINT, &act, NULL);
579         sigaction(SIGTERM, &act, NULL);
580         sigaction(SIGALRM, &act, NULL);
581         sigaction(SIGCHLD, &act, NULL);
582
583         if (init_udevsend_socket() < 0) {
584                 if (errno == EADDRINUSE)
585                         dbg("another udevd running, exit");
586                 else
587                         dbg("error initialising udevsend socket: %s", strerror(errno));
588
589                 goto exit;
590         }
591
592         /* possible override of udev binary, used for testing */
593         udev_bin = getenv("UDEV_BIN");
594         if (udev_bin != NULL)
595                 dbg("udev binary is set to '%s'", udev_bin);
596         else
597                 udev_bin = UDEV_BIN;
598
599         /* handle special startup timeout*/
600         sysinfo(&info);
601         startup_time = info.uptime;
602
603         FD_ZERO(&readfds);
604         FD_SET(udevsendsock, &readfds);
605         FD_SET(pipefds[0], &readfds);
606         maxsockplus = udevsendsock+1;
607         while (1) {
608                 struct hotplug_msg *msg;
609
610                 fd_set workreadfds = readfds;
611                 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
612
613                 if (retval < 0) {
614                         if (errno != EINTR)
615                                 dbg("error in select: %s", strerror(errno));
616                         continue;
617                 }
618
619                 if (FD_ISSET(udevsendsock, &workreadfds)) {
620                         msg = get_udevsend_msg();
621                         if (msg)
622                                 msg_queue_insert(msg);
623                 }
624
625                 if (FD_ISSET(pipefds[0], &workreadfds))
626                         user_sighandler();
627
628                 if (sigchilds_waiting) {
629                         sigchilds_waiting = 0;
630                         reap_sigchilds();
631                 }
632
633                 if (run_msg_q) {
634                         run_msg_q = 0;
635                         msg_queue_manager();
636                 }
637
638                 if (run_exec_q) {
639                          /* clean up running_list before calling exec_queue_manager() */
640                         if (sigchilds_waiting) {
641                                 sigchilds_waiting = 0;
642                                 reap_sigchilds();
643                         }
644
645                         run_exec_q = 0;
646                         exec_queue_manager();
647                 }
648         }
649
650 exit:
651         logging_close();
652         return 1;
653 }