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