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