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