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