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