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