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