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