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