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