chiark / gitweb /
1f769fbce0fff8d581b61f86e5645ab07629c72a
[elogind.git] / udevd.c
1 /*
2  * udevd.c - event listener and serializer
3  *
4  * Copyright (C) 2004-2005 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 <signal.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <dirent.h>
32 #include <fcntl.h>
33 #include <syslog.h>
34 #include <sys/select.h>
35 #include <sys/wait.h>
36 #include <sys/time.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40 #include <sys/sysinfo.h>
41 #include <sys/stat.h>
42 #include <sys/ioctl.h>
43 #include <linux/types.h>
44 #include <linux/netlink.h>
45
46 #include "list.h"
47 #include "udev_libc_wrapper.h"
48 #include "udev.h"
49 #include "udev_version.h"
50 #include "udev_rules.h"
51 #include "udev_utils.h"
52 #include "udevd.h"
53 #include "logging.h"
54
55 /* global variables*/
56 struct udev_rules rules;
57 static int udevd_sock;
58 static int uevent_netlink_sock;
59 static int inotify_fd;
60 static pid_t sid;
61
62 static int signal_pipe[2] = {-1, -1};
63 static volatile int sigchilds_waiting;
64 static volatile int run_msg_q;
65 static volatile int udev_exit;
66 static volatile int reload_config;
67 static int init_phase = 1;
68 static int run_exec_q;
69 static int stop_exec_q;
70 static int event_timeout;
71 static int max_childs;
72 static int max_childs_running;
73 static unsigned long long expected_seqnum;
74 static char udev_log[32];
75
76 static LIST_HEAD(msg_list);
77 static LIST_HEAD(exec_list);
78 static LIST_HEAD(running_list);
79
80
81 #ifdef USE_LOG
82 void log_message(int priority, const char *format, ...)
83 {
84         va_list args;
85
86         if (priority > udev_log_priority)
87                 return;
88
89         va_start(args, format);
90         vsyslog(priority, format, args);
91         va_end(args);
92 }
93 #endif
94
95 static void msg_dump_queue(void)
96 {
97 #ifdef DEBUG
98         struct uevent_msg *msg;
99
100         list_for_each_entry(msg, &msg_list, node)
101                 dbg("sequence %llu in queue", msg->seqnum);
102 #endif
103 }
104
105 static void msg_queue_delete(struct uevent_msg *msg)
106 {
107         list_del(&msg->node);
108         free(msg);
109 }
110
111 /* orders the message in the queue by sequence number */
112 static void msg_queue_insert(struct uevent_msg *msg)
113 {
114         struct uevent_msg *loop_msg;
115         struct sysinfo info;
116
117         if (msg->seqnum == 0) {
118                 dbg("no SEQNUM, move straight to the exec queue");
119                 list_add_tail(&msg->node, &exec_list);
120                 run_exec_q = 1;
121                 return;
122         }
123
124         /* store timestamp of queuing */
125         sysinfo(&info);
126         msg->queue_time = info.uptime;
127
128         /* with the first event we provide a phase of shorter timeout */
129         if (init_phase) {
130                 static long init_time;
131
132                 if (init_time == 0)
133                         init_time = info.uptime;
134                 if (info.uptime - init_time >= UDEVD_INIT_TIME)
135                         init_phase = 0;
136         }
137
138         /* sort message by sequence number into list */
139         list_for_each_entry_reverse(loop_msg, &msg_list, node) {
140                 if (loop_msg->seqnum < msg->seqnum)
141                         break;
142
143                 if (loop_msg->seqnum == msg->seqnum) {
144                         dbg("ignoring duplicate message seq %llu", msg->seqnum);
145                         free(msg);
146                         return;
147                 }
148         }
149         list_add(&msg->node, &loop_msg->node);
150         info("seq %llu queued, '%s' '%s'", msg->seqnum, msg->action, msg->devpath);
151
152         /* run msg queue manager */
153         run_msg_q = 1;
154
155         return;
156 }
157
158 static void asmlinkage udev_event_sig_handler(int signum)
159 {
160         if (signum == SIGALRM)
161                 exit(1);
162 }
163
164 static int udev_event_process(struct uevent_msg *msg)
165 {
166         struct sigaction act;
167         struct udevice udev;
168         struct name_entry *name_loop;
169         int i;
170         int retval;
171
172         /* set signal handlers */
173         memset(&act, 0x00, sizeof(act));
174         act.sa_handler = (void (*)(int)) udev_event_sig_handler;
175         sigemptyset (&act.sa_mask);
176         act.sa_flags = 0;
177         sigaction(SIGALRM, &act, NULL);
178
179         /* trigger timeout to prevent hanging processes */
180         alarm(UDEV_ALARM_TIMEOUT);
181
182         /* reconstruct env from message */
183         for (i = 0; msg->envp[i]; i++)
184                 putenv(msg->envp[i]);
185
186         udev_init_device(&udev, msg->devpath, msg->subsystem, msg->action);
187         retval = udev_process_event(&rules, &udev);
188
189         /* run programs collected by RUN-key*/
190         if (!retval) {
191                 list_for_each_entry(name_loop, &udev.run_list, node) {
192                         if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
193                                 pass_env_to_socket(&name_loop->name[strlen("socket:")], msg->devpath, msg->action);
194                         else
195                                 run_program(name_loop->name, udev.subsystem, NULL, 0, NULL, (udev_log_priority >= LOG_INFO));
196                 }
197         }
198
199         udev_cleanup_device(&udev);
200
201         return 0;
202 }
203
204 /* runs event and removes event from run queue when finished */
205 static void udev_event_run(struct uevent_msg *msg)
206 {
207         pid_t pid;
208         struct sysinfo info;
209
210         pid = fork();
211         switch (pid) {
212         case 0:
213                 /* child */
214                 if (uevent_netlink_sock > 0)
215                         close(uevent_netlink_sock);
216                 if (inotify_fd > 0)
217                         close(inotify_fd);
218                 close(udevd_sock);
219                 close(signal_pipe[READ_END]);
220                 close(signal_pipe[WRITE_END]);
221                 logging_close();
222
223                 logging_init("udevd-event");
224                 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
225                 udev_event_process(msg);
226                 info("seq %llu finished", msg->seqnum);
227
228                 logging_close();
229                 exit(0);
230         case -1:
231                 err("fork of child failed");
232                 msg_queue_delete(msg);
233                 break;
234         default:
235                 /* get SIGCHLD in main loop */
236                 sysinfo(&info);
237                 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
238                      msg->seqnum, pid,  msg->action, msg->subsystem, info.uptime - msg->queue_time);
239                 msg->pid = pid;
240         }
241 }
242
243 static int running_processes(void)
244 {
245         int f;
246         static char buf[4096];
247         int len;
248         int running;
249         const char *pos;
250
251         f = open("/proc/stat", O_RDONLY);
252         if (f == -1)
253                 return -1;
254
255         len = read(f, buf, sizeof(buf)-1);
256         close(f);
257
258         if (len <= 0)
259                 return -1;
260         else
261                 buf[len] = '\0';
262
263         pos = strstr(buf, "procs_running ");
264         if (pos == NULL)
265                 return -1;
266
267         if (sscanf(pos, "procs_running %u", &running) != 1)
268                 return -1;
269
270         return running;
271 }
272
273 /* return the number of process es in our session, count only until limit */
274 static int running_processes_in_session(pid_t session, int limit)
275 {
276         DIR *dir;
277         struct dirent *dent;
278         int running = 0;
279
280         dir = opendir("/proc");
281         if (!dir)
282                 return -1;
283
284         /* read process info from /proc */
285         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
286                 int f;
287                 char procdir[64];
288                 char line[256];
289                 const char *pos;
290                 char state;
291                 pid_t ppid, pgrp, sess;
292                 int len;
293
294                 if (!isdigit(dent->d_name[0]))
295                         continue;
296
297                 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
298                 procdir[sizeof(procdir)-1] = '\0';
299
300                 f = open(procdir, O_RDONLY);
301                 if (f == -1)
302                         continue;
303
304                 len = read(f, line, sizeof(line)-1);
305                 close(f);
306
307                 if (len <= 0)
308                         continue;
309                 else
310                         line[len] = '\0';
311
312                 /* skip ugly program name */
313                 pos = strrchr(line, ')') + 2;
314                 if (pos == NULL)
315                         continue;
316
317                 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
318                         continue;
319
320                 /* count only processes in our session */
321                 if (sess != session)
322                         continue;
323
324                 /* count only running, no sleeping processes */
325                 if (state != 'R')
326                         continue;
327
328                 running++;
329                 if (limit > 0 && running >= limit)
330                         break;
331         }
332         closedir(dir);
333
334         return running;
335 }
336
337 static int compare_devpath(const char *running, const char *waiting)
338 {
339         int i;
340
341         for (i = 0; i < PATH_SIZE; i++) {
342                 /* identical device event found */
343                 if (running[i] == '\0' && waiting[i] == '\0')
344                         return 1;
345
346                 /* parent device event found */
347                 if (running[i] == '\0' && waiting[i] == '/')
348                         return 2;
349
350                 /* child device event found */
351                 if (running[i] == '/' && waiting[i] == '\0')
352                         return 3;
353
354                 /* no matching event */
355                 if (running[i] != waiting[i])
356                         break;
357         }
358
359         return 0;
360 }
361
362 /* returns still running task for the same device, its parent or its physical device */
363 static int running_with_devpath(struct uevent_msg *msg, int limit)
364 {
365         struct uevent_msg *loop_msg;
366         int childs_count = 0;
367
368         if (msg->devpath == NULL)
369                 return 0;
370
371         /* skip any events with a timeout set */
372         if (msg->timeout != 0)
373                 return 0;
374
375         list_for_each_entry(loop_msg, &running_list, node) {
376                 if (limit && childs_count++ > limit) {
377                         dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
378                         return 1;
379                 }
380                 if (loop_msg->devpath == NULL)
381                         continue;
382
383                 /* return running parent/child device event */
384                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
385                         dbg("%llu, child device event still running %llu (%s)",
386                             msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
387                         return 2;
388                 }
389
390                 /* return running physical device event */
391                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
392                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
393                                 dbg("%llu, physical device event still running %llu (%s)",
394                                     msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
395                                 return 3;
396                         }
397         }
398
399         return 0;
400 }
401
402 /* exec queue management routine executes the events and serializes events in the same sequence */
403 static void exec_queue_manager(void)
404 {
405         struct uevent_msg *loop_msg;
406         struct uevent_msg *tmp_msg;
407         int running;
408
409         if (list_empty(&exec_list))
410                 return;
411
412         running = running_processes();
413         dbg("%d processes runnning on system", running);
414         if (running < 0)
415                 running = max_childs_running;
416
417         list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
418                 /* check running processes in our session and possibly throttle */
419                 if (running >= max_childs_running) {
420                         running = running_processes_in_session(sid, max_childs_running+10);
421                         dbg("at least %d processes running in session", running);
422                         if (running >= max_childs_running) {
423                                 dbg("delay seq %llu, cause too many processes already running",
424                                     loop_msg->seqnum);
425                                 return;
426                         }
427                 }
428
429                 if (running_with_devpath(loop_msg, max_childs) == 0) {
430                         /* move event to run list */
431                         list_move_tail(&loop_msg->node, &running_list);
432                         udev_event_run(loop_msg);
433                         running++;
434                         dbg("moved seq %llu to running list", loop_msg->seqnum);
435                 } else
436                         dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
437         }
438 }
439
440 static void msg_move_exec(struct uevent_msg *msg)
441 {
442         list_move_tail(&msg->node, &exec_list);
443         run_exec_q = 1;
444         expected_seqnum = msg->seqnum+1;
445         dbg("moved seq %llu to exec, next expected is %llu",
446                 msg->seqnum, expected_seqnum);
447 }
448
449 /* msg queue management routine handles the timeouts and dispatches the events */
450 static void msg_queue_manager(void)
451 {
452         struct uevent_msg *loop_msg;
453         struct uevent_msg *tmp_msg;
454         struct sysinfo info;
455         long msg_age = 0;
456         int timeout = event_timeout;
457
458         dbg("msg queue manager, next expected is %llu", expected_seqnum);
459 recheck:
460         sysinfo(&info);
461         list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
462                 /* move event with expected sequence to the exec list */
463                 if (loop_msg->seqnum == expected_seqnum) {
464                         msg_move_exec(loop_msg);
465                         continue;
466                 }
467
468                 /* limit timeout during initialization phase */
469                 if (init_phase) {
470                         if (timeout > UDEVD_INIT_EVENT_TIMEOUT)
471                                 timeout = UDEVD_INIT_EVENT_TIMEOUT;
472                         dbg("initialization phase, timeout %i seconds", timeout);
473                 }
474
475                 /* move event with expired timeout to the exec list */
476                 msg_age = info.uptime - loop_msg->queue_time;
477                 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
478                 if (msg_age >= timeout) {
479                         msg_move_exec(loop_msg);
480                         goto recheck;
481                 } else
482                         break;
483         }
484
485         msg_dump_queue();
486
487         /* set timeout for remaining queued events */
488         if (!list_empty(&msg_list)) {
489                 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
490                 info("next event expires in %li seconds", timeout - msg_age);
491                 setitimer(ITIMER_REAL, &itv, NULL);
492         }
493 }
494
495 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
496 {
497         int bufpos;
498         int i;
499         struct uevent_msg *msg;
500         int major = 0;
501         int minor = 0;
502
503         msg = malloc(sizeof(struct uevent_msg) + buf_size);
504         if (msg == NULL)
505                 return NULL;
506         memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
507
508         /* copy environment buffer and reconstruct envp */
509         memcpy(msg->envbuf, buf, buf_size);
510         bufpos = 0;
511         for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
512                 int keylen;
513                 char *key;
514
515                 key = &msg->envbuf[bufpos];
516                 keylen = strlen(key);
517                 msg->envp[i] = key;
518                 bufpos += keylen + 1;
519                 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
520
521                 /* remember some keys for further processing */
522                 if (strncmp(key, "ACTION=", 7) == 0)
523                         msg->action = &key[7];
524                 else if (strncmp(key, "DEVPATH=", 8) == 0)
525                         msg->devpath = &key[8];
526                 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
527                         msg->subsystem = &key[10];
528                 else if (strncmp(key, "SEQNUM=", 7) == 0)
529                         msg->seqnum = strtoull(&key[7], NULL, 10);
530                 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
531                         msg->physdevpath = &key[12];
532                 else if (strncmp(key, "MAJOR=", 6) == 0)
533                         major = strtoull(&key[6], NULL, 10);
534                 else if (strncmp(key, "MINOR=", 6) == 0)
535                         minor = strtoull(&key[6], NULL, 10);
536                 else if (strncmp(key, "TIMEOUT=", 8) == 0)
537                         msg->timeout = strtoull(&key[8], NULL, 10);
538         }
539         msg->devt = makedev(major, minor);
540         msg->envp[i++] = "UDEVD_EVENT=1";
541         msg->envp[i] = NULL;
542
543         return msg;
544 }
545
546 /* receive the udevd message from userspace */
547 static struct uevent_msg *get_udevd_msg(void)
548 {
549         static struct udevd_msg usend_msg;
550         struct uevent_msg *msg;
551         ssize_t size;
552         struct msghdr smsg;
553         struct cmsghdr *cmsg;
554         struct iovec iov;
555         struct ucred *cred;
556         char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
557         int envbuf_size;
558         int *intval;
559
560         memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
561         iov.iov_base = &usend_msg;
562         iov.iov_len = sizeof(struct udevd_msg);
563
564         memset(&smsg, 0x00, sizeof(struct msghdr));
565         smsg.msg_iov = &iov;
566         smsg.msg_iovlen = 1;
567         smsg.msg_control = cred_msg;
568         smsg.msg_controllen = sizeof(cred_msg);
569
570         size = recvmsg(udevd_sock, &smsg, 0);
571         if (size <  0) {
572                 if (errno != EINTR)
573                         err("unable to receive udevd message");
574                 return NULL;
575         }
576         cmsg = CMSG_FIRSTHDR(&smsg);
577         cred = (struct ucred *) CMSG_DATA(cmsg);
578
579         if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
580                 err("no sender credentials received, message ignored");
581                 return NULL;
582         }
583
584         if (cred->uid != 0) {
585                 err("sender uid=%i, message ignored", cred->uid);
586                 return NULL;
587         }
588
589         if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
590                 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
591                 return NULL;
592         }
593
594         switch (usend_msg.type) {
595         case UDEVD_UEVENT_UDEVSEND:
596         case UDEVD_UEVENT_INITSEND:
597                 info("udevd event message received");
598                 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
599                 dbg("envbuf_size=%i", envbuf_size);
600                 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
601                 if (msg == NULL)
602                         return NULL;
603                 msg->type = usend_msg.type;
604                 return msg;
605         case UDEVD_STOP_EXEC_QUEUE:
606                 info("udevd message (STOP_EXEC_QUEUE) received");
607                 stop_exec_q = 1;
608                 break;
609         case UDEVD_START_EXEC_QUEUE:
610                 info("udevd message (START_EXEC_QUEUE) received");
611                 stop_exec_q = 0;
612                 exec_queue_manager();
613                 break;
614         case UDEVD_SET_LOG_LEVEL:
615                 intval = (int *) usend_msg.envbuf;
616                 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
617                 udev_log_priority = *intval;
618                 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
619                 putenv(udev_log);
620                 break;
621         case UDEVD_SET_MAX_CHILDS:
622                 intval = (int *) usend_msg.envbuf;
623                 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
624                 max_childs = *intval;
625                 break;
626         case UDEVD_RELOAD_RULES:
627                 info("udevd message (RELOAD_RULES) received");
628                 reload_config = 1;
629                 break;
630         default:
631                 dbg("unknown message type");
632         }
633         return NULL;
634 }
635
636 /* receive the kernel user event message and do some sanity checks */
637 static struct uevent_msg *get_netlink_msg(void)
638 {
639         struct uevent_msg *msg;
640         int bufpos;
641         ssize_t size;
642         static char buffer[UEVENT_BUFFER_SIZE + 512];
643         char *pos;
644
645         size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
646         if (size <  0) {
647                 if (errno != EINTR)
648                         err("unable to receive udevd message");
649                 return NULL;
650         }
651
652         if ((size_t)size > sizeof(buffer)-1)
653                 size = sizeof(buffer)-1;
654         buffer[size] = '\0';
655         dbg("uevent_size=%zi", size);
656
657         /* start of event payload */
658         bufpos = strlen(buffer)+1;
659         msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
660         if (msg == NULL)
661                 return NULL;
662         msg->type = UDEVD_UEVENT_NETLINK;
663
664         /* validate message */
665         pos = strchr(buffer, '@');
666         if (pos == NULL) {
667                 err("invalid uevent '%s'", buffer);
668                 free(msg);
669                 return NULL;
670         }
671         pos[0] = '\0';
672
673         if (msg->action == NULL) {
674                 info("no ACTION in payload found, skip event '%s'", buffer);
675                 free(msg);
676                 return NULL;
677         }
678
679         if (strcmp(msg->action, buffer) != 0) {
680                 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
681                 free(msg);
682                 return NULL;
683         }
684
685         return msg;
686 }
687
688 static void asmlinkage sig_handler(int signum)
689 {
690         switch (signum) {
691                 case SIGINT:
692                 case SIGTERM:
693                         udev_exit = 1;
694                         break;
695                 case SIGALRM:
696                         /* set flag, then write to pipe if needed */
697                         run_msg_q = 1;
698                         break;
699                 case SIGCHLD:
700                         /* set flag, then write to pipe if needed */
701                         sigchilds_waiting = 1;
702                         break;
703                 case SIGHUP:
704                         reload_config = 1;
705                         break;
706         }
707
708         /* write to pipe, which will wakeup select() in our mainloop */
709         write(signal_pipe[WRITE_END], "", 1);
710 }
711
712 static void udev_done(int pid)
713 {
714         /* find msg associated with pid and delete it */
715         struct uevent_msg *msg;
716         struct sysinfo info;
717
718         list_for_each_entry(msg, &running_list, node) {
719                 if (msg->pid == pid) {
720                         sysinfo(&info);
721                         if (msg->queue_time)
722                                 info("seq %llu, pid [%d] exit, %ld seconds old", msg->seqnum, msg->pid, info.uptime - msg->queue_time);
723                         else
724                                 info("seq 0, pid [%d] exit", msg->pid);
725                         msg_queue_delete(msg);
726
727                         /* we want to run the exec queue manager since there may
728                          * be events waiting with the devpath of the one that
729                          * just finished
730                          */
731                         run_exec_q = 1;
732                         return;
733                 }
734         }
735 }
736
737 static void reap_sigchilds(void)
738 {
739         pid_t pid;
740
741         while (1) {
742                 pid = waitpid(-1, NULL, WNOHANG);
743                 if (pid <= 0)
744                         break;
745                 udev_done(pid);
746         }
747 }
748
749 static int init_udevd_socket(void)
750 {
751         struct sockaddr_un saddr;
752         const int buffersize = 16 * 1024 * 1024;
753         socklen_t addrlen;
754         const int feature_on = 1;
755         int retval;
756
757         memset(&saddr, 0x00, sizeof(saddr));
758         saddr.sun_family = AF_LOCAL;
759         /* use abstract namespace for socket path */
760         strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
761         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
762
763         udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
764         if (udevd_sock == -1) {
765                 err("error getting socket, %s", strerror(errno));
766                 return -1;
767         }
768
769         /* set receive buffersize */
770         setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
771
772         /* the bind takes care of ensuring only one copy running */
773         retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
774         if (retval < 0) {
775                 err("bind failed, %s", strerror(errno));
776                 close(udevd_sock);
777                 return -1;
778         }
779
780         /* enable receiving of the sender credentials */
781         setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
782
783         return 0;
784 }
785
786 static int init_uevent_netlink_sock(void)
787 {
788         struct sockaddr_nl snl;
789         const int buffersize = 16 * 1024 * 1024;
790         int retval;
791
792         memset(&snl, 0x00, sizeof(struct sockaddr_nl));
793         snl.nl_family = AF_NETLINK;
794         snl.nl_pid = getpid();
795         snl.nl_groups = 0xffffffff;
796
797         uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
798         if (uevent_netlink_sock == -1) {
799                 err("error getting socket, %s", strerror(errno));
800                 return -1;
801         }
802
803         /* set receive buffersize */
804         setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
805
806         retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl,
807                       sizeof(struct sockaddr_nl));
808         if (retval < 0) {
809                 err("bind failed, %s", strerror(errno));
810                 close(uevent_netlink_sock);
811                 uevent_netlink_sock = -1;
812                 return -1;
813         }
814
815         return 0;
816 }
817
818 int main(int argc, char *argv[], char *envp[])
819 {
820         int retval;
821         int devnull;
822         struct sigaction act;
823         fd_set readfds;
824         const char *value;
825         int uevent_netlink_active = 0;
826         int daemonize = 0;
827         int i;
828
829         /* set std fd's to /dev/null, if the kernel forks us, we don't have them at all */
830         devnull = open("/dev/null", O_RDWR);
831         if (devnull >= 0)  {
832                 if (devnull != STDIN_FILENO)
833                         dup2(devnull, STDIN_FILENO);
834                 if (devnull != STDOUT_FILENO)
835                         dup2(devnull, STDOUT_FILENO);
836                 if (devnull != STDERR_FILENO)
837                         dup2(devnull, STDERR_FILENO);
838                 if (devnull > STDERR_FILENO)
839                         close(devnull);
840         }
841
842         logging_init("udevd");
843         if (devnull < 0)
844                 err("fatal, could not open /dev/null");
845
846         udev_init_config();
847         dbg("version %s", UDEV_VERSION);
848
849         if (getuid() != 0) {
850                 err("need to be root, exit");
851                 goto exit;
852         }
853
854         for (i = 1 ; i < argc; i++) {
855                 char *arg = argv[i];
856                 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
857                         info("will daemonize");
858                         daemonize = 1;
859                 }
860                 if (strcmp(arg, "--stop-exec-queue") == 0) {
861                         info("will not execute events until START_EXEC_QUEUE is received");
862                         stop_exec_q = 1;
863                 }
864         }
865
866         if (daemonize) {
867                 pid_t pid;
868
869                 pid = fork();
870                 switch (pid) {
871                 case 0:
872                         dbg("damonized fork running");
873                         break;
874                 case -1:
875                         err("fork of daemon failed");
876                         goto exit;
877                 default:
878                         logging_close();
879                         exit(0);
880                 }
881         }
882
883         /* become session leader */
884         sid = setsid();
885         dbg("our session is %d", sid);
886
887         chdir("/");
888         umask(umask(077) | 022);
889
890         /* set a reasonable scheduling priority for the daemon */
891         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
892
893         /* setup signal handler pipe */
894         retval = pipe(signal_pipe);
895         if (retval < 0) {
896                 err("error getting pipes: %s", strerror(errno));
897                 goto exit;
898         }
899         retval = fcntl(signal_pipe[READ_END], F_SETFL, O_NONBLOCK);
900         if (retval < 0) {
901                 err("error fcntl on read pipe: %s", strerror(errno));
902                 goto exit;
903         }
904         retval = fcntl(signal_pipe[WRITE_END], F_SETFL, O_NONBLOCK);
905         if (retval < 0) {
906                 err("error fcntl on write pipe: %s", strerror(errno));
907                 goto exit;
908         }
909
910         /* set signal handlers */
911         memset(&act, 0x00, sizeof(struct sigaction));
912         act.sa_handler = (void (*)(int)) sig_handler;
913         sigemptyset(&act.sa_mask);
914         act.sa_flags = SA_RESTART;
915         sigaction(SIGINT, &act, NULL);
916         sigaction(SIGTERM, &act, NULL);
917         sigaction(SIGALRM, &act, NULL);
918         sigaction(SIGCHLD, &act, NULL);
919         sigaction(SIGHUP, &act, NULL);
920
921         /* parse the rules and keep it in memory */
922         udev_rules_init(&rules, 0, 1);
923
924         if (init_udevd_socket() < 0) {
925                 if (errno == EADDRINUSE)
926                         dbg("another udevd running, exit");
927                 else
928                         dbg("error initializing udevd socket: %s", strerror(errno));
929
930                 goto exit;
931         }
932
933         if (init_uevent_netlink_sock() < 0)
934                 err("uevent socket not available");
935
936         /* watch rules directory */
937         inotify_fd = inotify_init();
938         if (inotify_fd > 0)
939                 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
940
941         /* init of expected_seqnum value */
942         value = getenv("UDEVD_EXPECTED_SEQNUM");
943         if (value) {
944                 expected_seqnum = strtoull(value, NULL, 10);
945                 info("initialize expected_seqnum to %llu", expected_seqnum);
946         }
947
948         /* timeout to wait for missing events */
949         value = getenv("UDEVD_EVENT_TIMEOUT");
950         if (value)
951                 event_timeout = strtoul(value, NULL, 10);
952         else
953                 event_timeout = UDEVD_EVENT_TIMEOUT;
954         info("initialize event_timeout to %u", event_timeout);
955
956         /* maximum limit of forked childs */
957         value = getenv("UDEVD_MAX_CHILDS");
958         if (value)
959                 max_childs = strtoul(value, NULL, 10);
960         else
961                 max_childs = UDEVD_MAX_CHILDS;
962         info("initialize max_childs to %u", max_childs);
963
964         /* start to throttle forking if maximum number of _running_ childs is reached */
965         value = getenv("UDEVD_MAX_CHILDS_RUNNING");
966         if (value)
967                 max_childs_running = strtoull(value, NULL, 10);
968         else
969                 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
970         info("initialize max_childs_running to %u", max_childs_running);
971
972         /* clear environment for forked event processes */
973         clearenv();
974
975         /* export log_priority , as called programs may want to follow that setting */
976         sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
977         putenv(udev_log);
978
979         while (!udev_exit) {
980                 struct uevent_msg *msg;
981                 int fdcount;
982
983                 FD_ZERO(&readfds);
984                 FD_SET(signal_pipe[READ_END], &readfds);
985                 FD_SET(udevd_sock, &readfds);
986                 if (uevent_netlink_sock > 0)
987                         FD_SET(uevent_netlink_sock, &readfds);
988                 if (inotify_fd > 0)
989                         FD_SET(inotify_fd, &readfds);
990
991                 fdcount = select(UDEV_MAX(uevent_netlink_sock, inotify_fd)+1, &readfds, NULL, NULL, NULL);
992                 if (fdcount < 0) {
993                         if (errno != EINTR)
994                                 dbg("error in select: %s", strerror(errno));
995                         continue;
996                 }
997
998                 /* get user socket message */
999                 if (FD_ISSET(udevd_sock, &readfds)) {
1000                         msg = get_udevd_msg();
1001                         if (msg) {
1002                                 /* discard kernel messages if netlink is active */
1003                                 if (uevent_netlink_active && msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
1004                                         info("skip uevent_helper message with SEQNUM, netlink is active");
1005                                         free(msg);
1006                                 } else
1007                                         msg_queue_insert(msg);
1008                         }
1009                 }
1010
1011                 /* get kernel netlink message */
1012                 if ((uevent_netlink_sock > 0) && FD_ISSET(uevent_netlink_sock, &readfds)) {
1013                         msg = get_netlink_msg();
1014                         if (msg) {
1015                                 msg_queue_insert(msg);
1016                                 /* disable udevsend with first netlink message */
1017                                 if (!uevent_netlink_active) {
1018                                         info("uevent_nl message received, disable udevsend messages");
1019                                         uevent_netlink_active = 1;
1020                                 }
1021                         }
1022                 }
1023
1024                 /* received a signal, clear our notification pipe */
1025                 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1026                         char buf[256];
1027
1028                         read(signal_pipe[READ_END], &buf, sizeof(buf));
1029                 }
1030
1031                 /* rules directory inotify watch */
1032                 if ((inotify_fd > 0) && FD_ISSET(inotify_fd, &readfds)) {
1033                         int nbytes;
1034
1035                         /* discard all possible events, we can just reload the config */
1036                         if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1037                                 char *buf;
1038
1039                                 reload_config = 1;
1040                                 buf = malloc(nbytes);
1041                                 if (!buf) {
1042                                         err("error getting buffer for inotify, disable watching");
1043                                         close(inotify_fd);
1044                                         inotify_fd = -1;
1045                                 }
1046                                 read(inotify_fd, buf, nbytes);
1047                                 free(buf);
1048                         }
1049                 }
1050
1051                 /* rules changed, set by inotify or a signal*/
1052                 if (reload_config) {
1053                         reload_config = 0;
1054                         udev_rules_close(&rules);
1055                         udev_rules_init(&rules, 0, 1);
1056                 }
1057
1058                 /* forked child have returned */
1059                 if (sigchilds_waiting) {
1060                         sigchilds_waiting = 0;
1061                         reap_sigchilds();
1062                 }
1063
1064                 if (run_msg_q) {
1065                         run_msg_q = 0;
1066                         msg_queue_manager();
1067                 }
1068
1069                 if (run_exec_q) {
1070                          /* clean up running_list before calling exec_queue_manager() */
1071                         if (sigchilds_waiting) {
1072                                 sigchilds_waiting = 0;
1073                                 reap_sigchilds();
1074                         }
1075
1076                         run_exec_q = 0;
1077                         if (!stop_exec_q)
1078                                 exec_queue_manager();
1079                 }
1080         }
1081
1082 exit:
1083         udev_rules_close(&rules);
1084
1085         if (signal_pipe[READ_END] > 0)
1086                 close(signal_pipe[READ_END]);
1087         if (signal_pipe[WRITE_END] > 0)
1088                 close(signal_pipe[WRITE_END]);
1089
1090         if (udevd_sock > 0)
1091                 close(udevd_sock);
1092         if (inotify_fd > 0)
1093                 close(inotify_fd);
1094         if (uevent_netlink_sock > 0)
1095                 close(uevent_netlink_sock);
1096
1097         logging_close();
1098
1099         return 0;
1100 }