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