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