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