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