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