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