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