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