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