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