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