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