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