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