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