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