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